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/482] 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/482] 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/482] 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 9c191793e23276359b025bcd2bf5940f24376510 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:29:00 -0800 Subject: [PATCH 004/482] Images: a PNG read a row at a time counts all of the reader's buffers The room estimate for a large PNG read a row at a time counted 32 bytes a column. The png reader also keeps at least 128 KiB of rows already read, the 32 KiB deflate window and a growth step in its stream buffer, and up to four rows for wide images, so a decode could be approved with less room than reading takes. The estimate now comes from the PNG header's row length and these buffers, and a PNG is read a row at a time only while that estimate fits the decode allowance. --- crates/render/src/paint.rs | 43 ++++++++++++++++++--------- crates/render/src/tests.rs | 60 ++++++++++++++++++++------------------ 2 files changed, 61 insertions(+), 42 deletions(-) diff --git a/crates/render/src/paint.rs b/crates/render/src/paint.rs index e3c5ed30b1..b9ce01a7b3 100644 --- a/crates/render/src/paint.rs +++ b/crates/render/src/paint.rs @@ -189,8 +189,7 @@ fn fits_beside_pinned(bytes: u64) -> bool { /// all: an image that isn't a PNG, JPEG, GIF or WebP; an image of more pixels than the allowance /// has bytes (2,147,483,648 pixels, or 536,870,912 in the web app; 46,341 × 46,341 is more); and an /// image whose decoded samples take more than the allowance, unless it is a PNG that isn't -/// interlaced and is at most the allowance divided by [`ROW_SCRATCH`] pixels wide (read a row at a -/// time). +/// interlaced whose reader's buffers ([`png_row_scratch`]) fit the allowance (read a row at a time). pub fn reduced_size(bytes: &[u8]) -> Option<(u32, u32)> { reduction(bytes, allowance()).map(|r| r.to) } @@ -228,26 +227,44 @@ fn reduction(bytes: &[u8], allowance: u64) -> Option { return None; } let to = fitted_dims(w, h, allowance)?; - // The PNG reader's row buffers take at most `ROW_SCRATCH` bytes a column, also within the allowance. - let rows = format == image::ImageFormat::Png - && u64::from(w).saturating_mul(ROW_SCRATCH) <= allowance - && png_reader(bytes).is_some_and(|r| !r.info().interlaced); - let scratch = if rows { - u64::from(w) * ROW_SCRATCH + // A PNG that isn't interlaced is read a row at a time when the reader's buffers fit the allowance. + let row_scratch = if format == image::ImageFormat::Png { + png_reader(bytes).filter(|r| !r.info().interlaced).and_then(|r| png_row_scratch(&r)).filter(|&s| s <= allowance) } else { + None + }; + let rows = row_scratch.is_some(); + let scratch = row_scratch.unwrap_or_else(|| { let band = u64::from(BAND) * u64::from(w) * (u64::from(d.color_type().bytes_per_pixel()) + 4); d.total_bytes().saturating_add(band) - }; + }); (rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch }) } /// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time. const BAND: u32 = 16; -/// The most memory a column of a PNG read a row at a time takes in the reader's row buffers: the -/// row as stored (up to 8 bytes a pixel and a filter byte), the row before it, and the row given -/// out (up to 4 bytes a pixel). -const ROW_SCRATCH: u64 = 32; +/// The bytes of rows already read that png 0.18's reader keeps in its stream buffer, at least, +/// before it moves the rest of the buffer back to the start. +const PNG_KEPT_ROWS: u64 = 128 << 10; + +/// The deflate window png 0.18's reader keeps after the rows it has unfiltered, and the step its +/// stream buffer grows by. +const PNG_WINDOW_AND_STEP: u64 = (32 << 10) + (8 << 10); + +/// The most memory `r` takes in its buffers to read its image a row at a time: the stream buffer +/// holds the rows already read up to [`PNG_KEPT_ROWS`] or four rows, whichever is more, the previous +/// and current rows, and [`PNG_WINDOW_AND_STEP`], and may have up to twice that reserved; a copy of +/// a stored row and the row given out come on top. `None` when a row given out doesn't fit memory. +fn png_row_scratch(r: &png::Reader>) -> Option { + let info = r.info(); + // A filter byte and the row's samples, in whole bytes. + let stored = 1 + (u64::from(info.width) * info.color_type.samples() as u64 * info.bit_depth as u64).div_ceil(8); + let out = u64::try_from(r.output_line_size(info.width)?).ok()?; + let kept = (stored * 4).next_multiple_of(64).max(PNG_KEPT_ROWS); + let stream = kept + stored * 2 + PNG_WINDOW_AND_STEP; + Some(stream * 2 + stored + out) +} /// The largest size of at most `w`×`h` pixels, keeping their proportions, whose pixels take at most /// `allowance` bytes as RGBA, with sides of at most `u16::MAX` pixels. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e1ded30c8e..d97de7a3c9 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1648,46 +1648,48 @@ fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec { #[test] fn a_png_past_the_allowance_draws_at_reduced_size() { use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; - let img = image::ImageBuffer::, _>::from_fn(64, 48, |x, _| { - if x < 32 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) } + let img = image::ImageBuffer::, _>::from_fn(256, 400, |x, _| { + if x < 128 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) } }); let png = encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png); - // 64 × 48 is 12,288 bytes as RGBA; 36 × 27 is the largest within 4,096. - assert_eq!(with_allowance(4096, || paint::reduced_size(&png)), Some((36, 27))); + // 256 × 400 is 409,600 bytes as RGBA; 252 × 395 is the largest within 400,000. + assert_eq!(with_allowance(400_000, || paint::reduced_size(&png)), Some((252, 395))); assert_eq!(paint::reduced_size(&png), None, "within the 2 GB allowance"); - let mut d = Document::new(64.0, 48.0); + let mut d = Document::new(256.0, 400.0); d.images.insert("over".into(), ImageBlob::new("image/png", png)); let id = d.alloc_id(); - let im = ImageObject { key: "over".into(), width: 64, height: 48, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let im = + ImageObject { key: "over".into(), width: 256, height: 400, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); let failed = decode_failures(); // As on screen, where an image that can't be decoded draws as a crossed box. let screen = RenderOptions { smooth_images: false, mark_undecoded_images: true, ..Default::default() }; - let r = with_allowance(4096, || Renderer::new().render(&d, 64, 48, Affine::IDENTITY, &screen)); + let r = with_allowance(400_000, || Renderer::new().render(&d, 256, 400, Affine::IDENTITY, &screen)); assert_eq!(decode_failures(), failed); - assert_eq!((r.pixel(8, 24), r.pixel(56, 24)), ([200, 40, 40, 255], [40, 40, 200, 255])); - // 16 × 16 at 16 bits a sample is 2,048 bytes decoded and 1,024 as RGBA: past 1,500 as decoded - // and within it as RGBA, it is read a row at a time at its own size. - let small = image::ImageBuffer::, _>::from_pixel(16, 16, image::Rgba([51400, 10280, 10280, 65535])); + assert_eq!((r.pixel(32, 200), r.pixel(224, 200)), ([200, 40, 40, 255], [40, 40, 200, 255])); + // 256 × 256 at 16 bits a sample is 524,288 bytes decoded and 262,144 as RGBA: past 400,000 as + // decoded and within it as RGBA, it is read a row at a time at its own size. + let small = image::ImageBuffer::, _>::from_pixel(256, 256, image::Rgba([51400, 10280, 10280, 65535])); let small = encoded(image::DynamicImage::ImageRgba16(small), image::ImageFormat::Png); - assert_eq!(with_allowance(1500, || paint::reduced_size(&small)), Some((16, 16))); - let pm = with_allowance(1500, || paint::decode_pixmap(&small)).expect("read a row at a time"); + assert_eq!(with_allowance(400_000, || paint::reduced_size(&small)), Some((256, 256))); + let pm = with_allowance(400_000, || paint::decode_pixmap(&small)).expect("read a row at a time"); let c = pm.sample(3, 3); - assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (16, 16, [200, 40, 40, 255])); - // A row is read only while the reader's row buffers, 32 bytes a column, fit the allowance: - // 128 columns do within 4,096 bytes, and 129 columns are not decoded (their samples, 8 bytes a - // pixel, are past it too). + assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (256, 256, [200, 40, 40, 255])); + // A row is read only while the reader's buffers fit the allowance. Below 4,096 columns of 16-bit + // RGBA they take 344,069 bytes and 44 a column: 1,271 columns take 399,993 bytes, within 400,000, + // and 1,272 columns take 400,037 and are not decoded (their samples, 8 bytes a pixel, are past + // it too). let wide = |w: u32| { - let img = image::ImageBuffer::, _>::from_pixel(w, 6, image::Rgba([51400, 10280, 10280, 65535])); + let img = image::ImageBuffer::, _>::from_pixel(w, 40, image::Rgba([51400, 10280, 10280, 65535])); encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png) }; - assert_eq!(with_allowance(4096, || paint::reduced_size(&wide(128))), Some((128, 6))); - assert_eq!(with_allowance(4096, || paint::reduced_size(&wide(129))), None); - // An image of more pixels than the allowance has bytes is not read: 128 × 32 8-bit gray pixels - // are drawn at 64 × 16 within 4,096 bytes, and 128 × 33 are not. - let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(128, h, image::Luma([90]))), image::ImageFormat::Png); - assert_eq!(with_allowance(4096, || paint::reduced_size(&gray(32))), Some((64, 16))); - assert_eq!(with_allowance(4096, || paint::reduced_size(&gray(33))), None); + assert_eq!(with_allowance(400_000, || paint::reduced_size(&wide(1271))), Some((1271, 40))); + assert_eq!(with_allowance(400_000, || paint::reduced_size(&wide(1272))), None); + // An image of more pixels than the allowance has bytes is not read: 1,000 × 400 8-bit gray + // pixels are drawn at 500 × 200 within 400,000 bytes, and 1,000 × 401 are not. + let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(1000, h, image::Luma([90]))), image::ImageFormat::Png); + assert_eq!(with_allowance(400_000, || paint::reduced_size(&gray(400))), Some((500, 200))); + assert_eq!(with_allowance(400_000, || paint::reduced_size(&gray(401))), None); } /// A JPEG whose RGB samples are within the allowance but whose RGBA is past it is decoded whole @@ -1730,13 +1732,13 @@ fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() { // Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result // of 15,768 bytes. let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg); - // Read a row at a time: 64 columns of 32 bytes in the reader's row buffers, beside a 36 × 27 - // result of 3,888 bytes. + // Read a row at a time: 355,333 bytes in the reader's buffers for 256 columns of 16-bit RGBA, + // beside a 252 × 395 result of 398,160 bytes. let png = encoded( - image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(64, 48, image::Rgba([51400, 10280, 10280, 65535]))), + image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(256, 400, image::Rgba([51400, 10280, 10280, 65535]))), image::ImageFormat::Png, ); - for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 4_096, 3_888 + 2_048, (36, 27))] { + for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 400_000, 398_160 + 355_333, (252, 395))] { let failed = decode_failures(); let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes))); assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later"); From 663c3264ca0e257407a9bd191db3d2a4072f70db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:17:39 -0800 Subject: [PATCH 005/482] Type: list stylistic sets whose lookups come from FeatureVariations A variable font can leave an ssNN feature empty in GSUB or GPOS and supply its lookups through a FeatureVariations substitution. The OpenType panel skipped those sets because the default feature has no lookups. A set is now listed when a substitution in a variation record replaces its feature with one that has lookups, and its name is read from the default feature or the substituted one. Records after one without conditions are ignored, and at most 4096 variation records and 4096 substitutions are read per table. Follows #5447. --- crates/text/src/fontdb/stylistic_sets.rs | 152 +++++++++++++++++++---- 1 file changed, 125 insertions(+), 27 deletions(-) diff --git a/crates/text/src/fontdb/stylistic_sets.rs b/crates/text/src/fontdb/stylistic_sets.rs index 8d65782270..d2b1177b9b 100644 --- a/crates/text/src/fontdb/stylistic_sets.rs +++ b/crates/text/src/fontdb/stylistic_sets.rs @@ -1,8 +1,11 @@ //! The font-defined OpenType stylistic sets offered by the OpenType panel. //! -use skrifa::raw::TableProvider; -use skrifa::raw::tables::layout::{FeatureList, FeatureParams}; +use std::collections::HashMap; + +use skrifa::raw::tables::layout::{Feature, FeatureList, FeatureParams, FeatureVariations}; +use skrifa::raw::types::Tag; +use skrifa::raw::{ResolveOffset, TableProvider}; use super::FontFace; use super::names::name; @@ -24,20 +27,71 @@ fn number(tag: [u8; 4]) -> Option { (1..=20).contains(&n).then_some(n) } +/// The features that FeatureVariations substitutions replace with a feature that has lookups, +/// keyed by feature index. A variable font can leave a set's default feature empty and supply its +/// lookups only at some variation locations. `tags` holds each feature's tag, which a substituted +/// feature needs to read its parameters. At most 4096 variation records and 4096 substitutions are +/// read. +fn variation_features<'a>(variations: Option>, tags: &[Tag]) -> HashMap> { + let mut found = HashMap::new(); + let Some(variations) = variations else { return found }; + let mut budget = 4096_usize; + for record in variations.feature_variation_records().iter().take(4096) { + if let Some(Ok(substitution)) = record.feature_table_substitution(variations.offset_data()) { + for replacement in substitution.substitutions() { + if budget == 0 { + return found; + } + budget -= 1; + let index = usize::from(replacement.feature_index()); + let Some(&tag) = tags.get(index) else { continue }; + if let Ok(alternate) = replacement.alternate_feature_offset().resolve_with_args::(substitution.offset_data(), tag) + && !alternate.lookup_list_indices().is_empty() + { + found.entry(index).or_insert(alternate); + } + } + } + // Only the first record whose conditions match applies, so records after one without + // conditions are never used. + let unconditional = match record.condition_set(variations.offset_data()) { + None => true, + Some(Ok(conditions)) => conditions.condition_count() == 0, + Some(Err(_)) => false, + }; + if unconditional { + break; + } + } + found +} + /// Collect registered set records from either layout table. Fonts may carry a set in GSUB, GPOS, -/// or both. `labels[n - 1]` is `Some` once set `n` is found, holding its readable custom name if -/// any record supplies one. -fn collect(font: &skrifa::FontRef<'_>, features: FeatureList<'_>, labels: &mut [Option>; 20]) { - for record in features.feature_records().iter().take(4096) { +/// or both. A record with no lookups counts only when a FeatureVariations substitution gives it +/// some. `labels[n - 1]` is `Some` once set `n` is found, holding its readable custom name if any +/// record supplies one. +fn collect( + font: &skrifa::FontRef<'_>, + features: FeatureList<'_>, + variations: Option>, + labels: &mut [Option>; 20], +) { + let tags: Vec = features.feature_records().iter().take(4096).map(|record| record.feature_tag()).collect(); + let substituted = variation_features(variations, &tags); + for (index, record) in features.feature_records().iter().enumerate().take(4096) { let Some(n) = number(record.feature_tag().to_be_bytes()) else { continue }; - let Ok(feature) = record.feature(features.offset_data()) else { continue }; - if feature.lookup_list_indices().is_empty() { + let Ok(default) = record.feature(features.offset_data()) else { continue }; + let label = |feature: &Feature<'_>| { + feature.feature_params().and_then(Result::ok).and_then(|params| match params { + FeatureParams::StylisticSet(p) => name(font, &[p.ui_name_id()]), + _ => None, + }) + }; + let alternate = substituted.get(&index); + if default.lookup_list_indices().is_empty() && alternate.is_none() { continue; } - let custom = feature.feature_params().and_then(Result::ok).and_then(|params| match params { - FeatureParams::StylisticSet(p) => name(font, &[p.ui_name_id()]), - _ => None, - }); + let custom = label(&default).or_else(|| alternate.and_then(label)); let slot = &mut labels[n - 1]; if custom.is_some() { *slot = Some(custom); @@ -56,12 +110,12 @@ impl FontFace { if let Ok(gsub) = font.gsub() && let Ok(features) = gsub.feature_list() { - collect(&font, features, &mut labels); + collect(&font, features, gsub.feature_variations().and_then(Result::ok), &mut labels); } if let Ok(gpos) = font.gpos() && let Ok(features) = gpos.feature_list() { - collect(&font, features, &mut labels); + collect(&font, features, gpos.feature_variations().and_then(Result::ok), &mut labels); } labels.into_iter().enumerate().filter_map(|(i, name)| Some(StylisticSet { number: u8::try_from(i + 1).ok()?, name: name? })).collect() } @@ -74,10 +128,11 @@ mod tests { use write_fonts::FontBuilder; use write_fonts::tables::gsub::{Gsub, SingleSubstFormat2, SubstitutionLookup, SubstitutionLookupList}; use write_fonts::tables::layout::{ - CoverageFormat1, Feature, FeatureList, FeatureParams as WriteParams, FeatureRecord, LangSys, Lookup, Script, ScriptList, ScriptRecord, - StylisticSetParams, + Condition, ConditionFormat1, ConditionSet, CoverageFormat1, Feature, FeatureList, FeatureParams as WriteParams, FeatureRecord, + FeatureTableSubstitution, FeatureTableSubstitutionRecord, FeatureVariationRecord, FeatureVariations as WriteVariations, LangSys, Lookup, + Script, ScriptList, ScriptRecord, StylisticSetParams, }; - use write_fonts::types::{GlyphId16, NameId, Tag}; + use write_fonts::types::{F2Dot14, GlyphId16, NameId, Tag}; #[test] fn registered_set_numbers_only() { @@ -88,19 +143,14 @@ mod tests { assert_eq!(number(*b"salt"), None); } - #[test] - fn face_lists_only_its_sets_with_the_fonts_name() { + fn face_with(features: FeatureList, variations: Option) -> std::sync::Arc { const BASE: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf"); let base = skrifa::FontRef::new(BASE).unwrap(); let gid = |c| GlyphId16::new(u16::try_from(base.charmap().map(c).unwrap().to_u32()).unwrap()); let subst = SingleSubstFormat2::new(CoverageFormat1::new(vec![gid('a')]).into(), vec![gid('A')]); let lookup = SubstitutionLookup::Single(Lookup::new(Default::default(), vec![subst.into()])); - let features = FeatureList::new(vec![ - FeatureRecord::new(Tag::new(b"ss01"), Feature::new(Some(WriteParams::StylisticSet(StylisticSetParams::new(NameId::new(256)))), vec![0])), - FeatureRecord::new(Tag::new(b"ss03"), Feature::new(None, vec![0])), - FeatureRecord::new(Tag::new(b"ss05"), Feature::new(None, vec![])), - ]); - let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(vec![0, 1, 2])), vec![]))]); + let indices = (0..u16::try_from(features.feature_records.len()).unwrap()).collect(); + let scripts = ScriptList::new(vec![ScriptRecord::new(Tag::new(b"DFLT"), Script::new(Some(LangSys::new(indices)), vec![]))]); let mut builder = FontBuilder::new(); let names = crate::test_fonts::name_table(&[ (1, "Stylistic Test Sans"), @@ -111,7 +161,9 @@ mod tests { ]) .unwrap(); builder.add_raw(Tag::new(b"name"), names); - builder.add_table(&Gsub::new(scripts, features, SubstitutionLookupList::new(vec![lookup]))).unwrap(); + let mut gsub = Gsub::new(scripts, features, SubstitutionLookupList::new(vec![lookup])); + gsub.feature_variations = variations.into(); + builder.add_table(&gsub).unwrap(); for record in base.table_directory.table_records() { let tag = Tag::new(&record.tag().to_be_bytes()); if !builder.contains(tag) { @@ -120,7 +172,53 @@ mod tests { } let db = super::super::FontDb::with_font_dirs(vec![]); assert_eq!(db.add_font(builder.build()), 1); - let face = db.face("Stylistic Test Sans", "Regular").unwrap(); + db.face("Stylistic Test Sans", "Regular").unwrap() + } + + fn set_params() -> Option { + Some(WriteParams::StylisticSet(StylisticSetParams::new(NameId::new(256)))) + } + + #[test] + fn face_lists_only_its_sets_with_the_fonts_name() { + let features = FeatureList::new(vec![ + FeatureRecord::new(Tag::new(b"ss01"), Feature::new(set_params(), vec![0])), + FeatureRecord::new(Tag::new(b"ss03"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"ss05"), Feature::new(None, vec![])), + ]); + let face = face_with(features, None); assert_eq!(face.stylistic_sets(), [StylisticSet { number: 1, name: Some("Curved Capitals".into()) }, StylisticSet { number: 3, name: None }]); } + + #[test] + fn a_set_whose_lookups_come_from_feature_variations_is_listed() { + let features = FeatureList::new(vec![ + FeatureRecord::new(Tag::new(b"ss02"), Feature::new(None, vec![0])), + FeatureRecord::new(Tag::new(b"ss05"), Feature::new(None, vec![])), + FeatureRecord::new(Tag::new(b"ss07"), Feature::new(None, vec![])), + FeatureRecord::new(Tag::new(b"ss09"), Feature::new(set_params(), vec![])), + ]); + let condition = + ConditionSet::new(vec![Condition::Format1AxisRange(ConditionFormat1::new(0, F2Dot14::from_f32(0.5), F2Dot14::from_f32(1.0)))]); + let conditional = FeatureTableSubstitution::new(vec![ + FeatureTableSubstitutionRecord::new(1, Feature::new(set_params(), vec![0])), + FeatureTableSubstitutionRecord::new(2, Feature::new(None, vec![])), + ]); + let always = FeatureTableSubstitution::new(vec![FeatureTableSubstitutionRecord::new(3, Feature::new(None, vec![0]))]); + let unreachable = FeatureTableSubstitution::new(vec![FeatureTableSubstitutionRecord::new(2, Feature::new(None, vec![0]))]); + let variations = WriteVariations::new(vec![ + FeatureVariationRecord::new(Some(condition), Some(conditional)), + FeatureVariationRecord::new(None, Some(always)), + FeatureVariationRecord::new(None, Some(unreachable)), + ]); + let face = face_with(features, Some(variations)); + assert_eq!( + face.stylistic_sets(), + [ + StylisticSet { number: 2, name: None }, + StylisticSet { number: 5, name: Some("Curved Capitals".into()) }, + StylisticSet { number: 9, name: Some("Curved Capitals".into()) }, + ] + ); + } } From a8c6d078e5608e3ad00f8ace2a1daa55afaf6a72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:08:54 -0800 Subject: [PATCH 006/482] .ai import: blends keep their Specified Distance and Smooth Color spacing A blend's record in the editing data holds its Blend Options spacing. Word 1 is the spacing: 0 is Smooth Color, 1 is Specified Steps and 2 is Specified Distance. For Specified Distance, word 2 is the distance in points as a 32-bit float. The reader took only records whose word 1 is 1, so every Smooth Color and Specified Distance blend came in as its drawn steps. A Smooth Color or Specified Distance blend now opens live with that spacing where VectorCraft lays out as many steps between each pair of keys as the file draws, in the same places and colors. Otherwise it keeps its drawn steps with the existing note. The distance is read as the shortest decimal that reads back as the stored float. The steps are counted before anything is laid out, and a blend takes from the import's budget only when its count matches. Specified Steps blends are read as before, with the steps counted from the drawn ones. Tests: import::ai::tests::a_blend_keeps_its_spacing, a_blend_of_three_keys_keeps_its_distance_between_each_pair, a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them, import::ai::blend::tests::records_say_their_spacing, a_blend_takes_from_the_budget_only_when_it_is_laid_out, a_distance_past_the_keys_lays_out_no_steps, and the fuzz case ai_blend_spacing_never_panics. --- crates/engine/tests/import_fuzz.rs | 20 +- crates/eps/src/import/ai/blend.rs | 192 ++++++++++++++++---- crates/eps/src/import/ai/read/containers.rs | 4 +- crates/eps/src/import/ai/tests.rs | 126 ++++++++++++- docs/target-app-parity.md | 1 + 5 files changed, 300 insertions(+), 43 deletions(-) diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 095d0ec146..fda4ad8903 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -5715,8 +5715,15 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() { /// A blend in `.ai` editing data, written by hand: two keys (10 pt squares, red on the left, blue on /// the right) on a straight spine, `steps` steps drawn between them as the blend lays them out, and -/// the record (`DCBA`, version 1, two keys `A` and `B`, see `vectorcraft_eps`' AI blend reader). +/// the record (`DCBA`, Specified Steps, two keys `A` and `B`, see `vectorcraft_eps`' AI blend +/// reader). fn blend_text(steps: usize) -> String { + blend_text_spaced(steps, [1, 0, 0]) +} + +/// [`blend_text`] with the record's spacing words `spacing`: the spacing (word 1), the bits of the +/// distance (word 2, a 32-bit float) and word 4. +fn blend_text_spaced(steps: usize, spacing: [u32; 3]) -> String { use std::fmt::Write; let square = |x: f64, hidden: bool, t: f64| { let p = if hidden { "%_" } else { "" }; @@ -5740,7 +5747,8 @@ fn blend_text(steps: usize) -> String { s += &square(t * span, false, t); } s += "U\n9 () XW\n0 Ae\n"; - let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), 1, 0, 0, 0, 0, 0, 0, 0, 0, 2]; + let [kind, distance, count] = spacing; + let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), kind, distance, 0, count, 0, 0, 0, 0, 0, 2]; for id in ['A', 'B'] { words.extend([id as u32, 0, 0, 0, 0, 0]); } @@ -5788,6 +5796,14 @@ proptest! { survive("a .ai blend far out", || Some(vectorcraft_eps::layered_ai(&far, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; survive("mutated .ai blend", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; } + + /// A `.ai` blend whose record holds any spacing, distance bits (zero, negative, tiny, NaN, + /// infinite) and step count: read live, as its drawn steps, or not at all, never panicking. + #[test] + fn ai_blend_spacing_never_panics(steps in 1usize..6, kind in prop_oneof![0u32..4, any::()], distance in prop_oneof![any::(), prop::sample::select(vec![0u32, 0x8000_0000, 1, 0x7f80_0000, 0xff80_0000, 0x7fc0_0000, 0x7f7f_ffff, 0x41c8_0000])], count in prop_oneof![0u32..1_100, any::()]) { + let private = ai_private(&blend_text_spaced(steps, [kind, distance, count])); + survive("a .ai blend's spacing", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?; + } } /// A graph in `.ai` editing data, written by hand from the version 7 specification's chapter 17: diff --git a/crates/eps/src/import/ai/blend.rs b/crates/eps/src/import/ai/blend.rs index 553ab64b8c..494a11cdc5 100644 --- a/crates/eps/src/import/ai/blend.rs +++ b/crates/eps/src/import/ai/blend.rs @@ -3,24 +3,29 @@ //! What a blend is and does is Illustrator's public documentation: key objects, the spine the //! steps follow, Blend Options' Spacing (Smooth Color, Specified Steps, Specified Distance) and //! Orientation (Align to Page, Align to Path), Replace Spine and Reverse Spine -//! (). +//! (, +//! ). //! //! How the editing data writes one isn't documented. As written in files users sent (used //! locally, never committed): the blend's own art on `%_` lines, a group holding the key objects //! and the spine, each object's `/ArtDictionary` naming its part (`ShapeBlendPathType`: `K` a key, //! `S` the spine) and a key's id (`ShapeBlendPathID`); then the steps drawn, a group on plain //! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines. Those bytes -//! start `DCBA`, version 1; word 10 (little endian) is the number of keys, and the words after it -//! a record per key that starts with the key's id. What the other words mean isn't known, so the -//! spacing and orientation are taken from the steps drawn instead: as many steps as they have -//! between two keys, and whichever orientation lays the blend out as they are drawn. A blend whose -//! parts don't agree, or that doesn't come out as drawn, keeps its drawn steps. +//! start `DCBA`. +//! +//! The reader reads the words after `DCBA` (little endian) this way. Word 1 is the spacing: 0 is +//! Smooth Color, 1 is Specified Steps and 2 is Specified Distance. For Specified Distance, word 2 +//! is the distance in points, as a 32-bit float. Word 10 is the number of keys, and the words after +//! it are a record of six words per key that starts with the key's id. For Specified Steps, the +//! steps between two keys are counted from the steps drawn. The orientation is taken from the steps +//! drawn: whichever one lays the blend out as they are drawn. A blend whose parts don't agree, +//! whose spacing isn't one of these, or that doesn't come out as drawn, keeps its drawn steps. use std::collections::HashMap; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::blend::blend_expand; +use vectorcraft_doc::blend::{blend_expand, blend_steps}; use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec}; use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind}; use vectorcraft_geom::{PathData, Point}; @@ -55,15 +60,40 @@ pub(super) fn hex_bytes(hex: &[u8]) -> Option> { hex.as_chunks::<2>().0.iter().map(|&[a, b]| Some(digit(a)? << 4 | digit(b)?)).collect() } -/// The keys' ids in a blend's record, in its order; `None` for a record that isn't one. -pub(super) fn record_ids(bytes: &[u8]) -> Option> { +/// What a blend's record says: its keys' ids, in its order, and its spacing. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Record { + pub(super) ids: Vec, + /// `None`: Specified Steps, whose steps the reader counts from the drawn ones. + pub(super) spacing: Option, +} + +/// A blend's record, or `None` for a record that isn't one or whose spacing isn't read: an +/// unknown spacing, or a distance that isn't a positive number. +pub(super) fn record(bytes: &[u8]) -> Option { if bytes.get(..4)? != b"DCBA" || bytes.len() > MAX_RECORD { return None; } let words: Vec = bytes.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect(); - if words.get(1) != Some(&1) { - return None; - } + let spacing = match *words.get(1)? { + 0 => Some(BlendSpacing::SmoothColor), + 1 => None, + 2 => Some(BlendSpacing::Distance(distance(*words.get(2)?)?)), + _ => return None, + }; + let ids = record_ids(&words)?; + Some(Record { ids, spacing }) +} + +/// The distance in a record's word `bits` (a 32-bit float), as the shortest decimal that reads +/// back as that float (2.3 for the float nearest 2.3), or `None` when it isn't a positive number. +fn distance(bits: u32) -> Option { + let d: f64 = f32::from_bits(bits).to_string().parse().ok()?; + (d.is_finite() && d > 0.0).then_some(d) +} + +/// The keys' ids in a blend's record `words`, in its order; `None` when they aren't there. +fn record_ids(words: &[u32]) -> Option> { let count = usize::try_from(*words.get(10)?).ok().filter(|c| (2..=MAX_KEYS).contains(c))?; let rest = words.len().checked_sub(11)?; if rest == 0 || !rest.is_multiple_of(count) { @@ -80,14 +110,15 @@ pub(super) fn record_ids(bytes: &[u8]) -> Option> { } /// The blend `edit` (its key objects and spine, as their dictionaries name them in `roles`) and -/// `drawn` (its steps as the file draws them) make, with the keys of the record `ids`: one live -/// blend, or `None` when they don't agree or it doesn't come out as drawn. +/// `drawn` (its steps as the file draws them) make, with the keys and spacing of `record`: one +/// live blend, or `None` when they don't agree or it doesn't come out as drawn. /// /// `budget`: how many more objects blends may lay out in this import; a blend that would lay out /// more isn't made live (each blend is laid out twice, once per orientation, and checked against /// its drawn steps, so a file of huge blends mustn't stall the import). What it lays out is taken /// from it. -pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Roles, budget: &mut usize) -> Option { +pub(super) fn live_blend(edit: &Node, drawn: &Node, record: &Record, roles: &Roles, budget: &mut usize) -> Option { + let ids = &record.ids; let parts = edit.children()?; let role = |n: &Arc| roles.get(&n.id); let keys: Vec> = parts.iter().filter(|n| role(n).is_some_and(|(t, _)| t == "K")).cloned().collect(); @@ -106,20 +137,10 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Role if named != listed || named.windows(2).any(|w| w.first() == w.get(1)) { return None; } - // The steps between two keys: the drawn objects that aren't keys, shared out. let drawn: Vec<&Arc> = drawn.children()?.iter().collect(); - let between = (drawn.len().checked_sub(keys.len())?).checked_div(keys.len() - 1)?; - if between == 0 || between > MAX_STEPS || drawn.len() != keys.len() + between * (keys.len() - 1) || drawn.len() > MAX_BLEND_OBJECTS { + if drawn.len() < keys.len() || drawn.len() > MAX_BLEND_OBJECTS { return None; } - // Both orientations are laid out. - let cost = drawn.len().saturating_mul(2); - if cost > *budget { - return None; - } - *budget -= cost; - // The drawn steps' centres and paints, once. - let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::>()?; let keys: Vec> = keys .into_iter() .map(|k| { @@ -130,12 +151,34 @@ pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Role .collect(); let spine = spine?; let key_anchors = on_spine(&keys, &spine)?; - let spacing = BlendSpacing::Steps(u32::try_from(between).ok()?); + let spacing = match record.spacing { + // Specified Steps: the steps between two keys are the drawn objects that aren't keys, + // shared out. + None => { + let between = (drawn.len() - keys.len()).checked_div(keys.len() - 1)?; + BlendSpacing::Steps(u32::try_from(between).ok().filter(|n| (1..=MAX_STEPS as u32).contains(n))?) + } + Some(spacing) => spacing, + }; + // Both orientations are laid out, as many objects as are drawn each. + let cost = drawn.len().saturating_mul(2); + if cost > *budget { + return None; + } + let spec = BlendSpec { spacing, spine: Some(spine), key_anchors, ..BlendSpec::default() }; + // As many objects as the spacing lays out between each pair of keys (the orientation doesn't + // change how many), counted before anything is laid out: as many as are drawn. + if blend_steps(&keys, &spec).into_iter().fold(keys.len(), usize::saturating_add) != drawn.len() { + return None; + } + *budget -= cost; + // The drawn steps' centres and paints, once. + let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::>()?; // The orientation that lays the steps out as drawn, the closest when both do. [BlendOrientation::AlignToPage, BlendOrientation::AlignToPath] .into_iter() .filter_map(|orientation| { - let spec = BlendSpec { spacing, orientation, spine: Some(spine.clone()), key_anchors: key_anchors.clone(), ..BlendSpec::default() }; + let spec = BlendSpec { orientation, ..spec.clone() }; let laid = blend_expand(&keys, &spec); let off = how_far(&laid, &drawn)?; Some((off, spec)) @@ -242,7 +285,7 @@ fn how_far(laid: &[Node], drawn: &[(Point, Fill)]) -> Option { mod tests { use super::*; - /// Records that aren't one: too short, another magic, another version, key counts out of + /// Records that aren't one: too short, another magic, an unknown spacing, key counts out of /// range or not dividing the rest, ids that aren't letters or digits, and hex digits that /// don't pair up. None of them panics. #[test] @@ -250,7 +293,7 @@ mod tests { let words = |w: &[u32]| w.iter().flat_map(|x| x.to_le_bytes()).collect::>(); let magic = u32::from_le_bytes(*b"DCBA"); let good = words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 'A' as u32, 0, 0, 0, 0, 0, 'B' as u32, 0, 0, 0, 0, 0]); - assert_eq!(record_ids(&good), Some(vec!["A".to_string(), "B".to_string()])); + assert_eq!(record(&good).map(|r| r.ids), Some(vec!["A".to_string(), "B".to_string()])); for bad in [ vec![], b"DCB".to_vec(), @@ -262,7 +305,33 @@ mod tests { words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0x20, 0, 66, 0]), words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, u32::MAX]), ] { - assert_eq!(record_ids(&bad), None, "{bad:?}"); + assert_eq!(record(&bad), None, "{bad:?}"); + } + } + + /// The spacing at word 1 (0 Smooth Color, 1 Specified Steps, 2 Specified Distance) and, for + /// Specified Distance, the distance at word 2 as a 32-bit float, read as the decimal it was + /// typed as. Specified Steps leaves the steps to be counted from the drawn ones, whatever word + /// 4 holds. An unknown spacing, or a distance that isn't a positive number, isn't read. + #[test] + fn records_say_their_spacing() { + let words = |spacing: u32, distance: f32, steps: u32| { + let magic = u32::from_le_bytes(*b"DCBA"); + [magic, spacing, distance.to_bits(), 0, steps, 0, 0, 0, 0, 0, 2, 'A' as u32, 0, 0, 0, 0, 0, 'B' as u32, 0, 0, 0, 0, 0] + .iter() + .flat_map(|x| x.to_le_bytes()) + .collect::>() + }; + let spacing = |b: Vec| record(&b).map(|r| r.spacing); + assert_eq!(spacing(words(0, 4.0, 254)), Some(Some(BlendSpacing::SmoothColor))); + assert_eq!(spacing(words(1, 50.0, 3)), Some(None)); + assert_eq!(spacing(words(1, 0.0, 0)), Some(None)); + assert_eq!(spacing(words(2, 12.5, 7)), Some(Some(BlendSpacing::Distance(12.5)))); + assert_eq!(spacing(words(2, 2.3, 0)), Some(Some(BlendSpacing::Distance(2.3)))); + assert_eq!(spacing(words(2, 0.1, 0)), Some(Some(BlendSpacing::Distance(0.1)))); + assert_eq!(spacing(words(2, 12345.67, 0)), Some(Some(BlendSpacing::Distance(12345.67)))); + for (kind, distance) in [(2, 0.0), (2, -10.0), (2, f32::NAN), (2, f32::INFINITY), (3, 10.0), (u32::MAX, 10.0)] { + assert_eq!(spacing(words(kind, distance, 7)), None, "spacing {kind}, distance {distance}"); } assert_eq!(hex_bytes(b"4A4"), None); assert_eq!(hex_bytes(b"4G"), None); @@ -276,10 +345,69 @@ mod tests { let edit = Node::new(NodeId(1), NodeKind::Group { children: vec![], clip: false }); let drawn = Node::new(NodeId(2), NodeKind::Group { children: vec![], clip: false }); let mut budget = 1; - assert!(live_blend(&edit, &drawn, &["A".into(), "B".into()], &Roles::new(), &mut budget).is_none()); + let record = Record { ids: vec!["A".into(), "B".into()], spacing: None }; + assert!(live_blend(&edit, &drawn, &record, &Roles::new(), &mut budget).is_none()); assert_eq!(budget, 1); } + /// Two 20 pt keys (`A` at x 0 and `B` at x 100) on a straight spine through their centers, + /// with three 20 pt steps drawn evenly between them: the blend's edit group, its drawn steps + /// and the roles naming its parts. + fn two_keys() -> (Node, Node, Roles) { + let square = |id: u64, x: f64| { + let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 40.0, x + 20.0, 60.0)); + Arc::new(Node::path(NodeId(id), path, Default::default())) + }; + let spine = vectorcraft_geom::shapes::line(Point::new(10.0, 50.0), Point::new(110.0, 50.0)); + let spine = Arc::new(Node::path(NodeId(3), spine, Default::default())); + let edit = Node::new(NodeId(10), NodeKind::Group { children: vec![square(1, 0.0), square(2, 100.0), spine], clip: false }); + let steps = (0..5u32).map(|i| square(20 + u64::from(i), f64::from(i) * 25.0)).collect(); + let drawn = Node::new(NodeId(11), NodeKind::Group { children: steps, clip: false }); + let roles = Roles::from([ + (NodeId(1), ("K".to_string(), Some("A".to_string()))), + (NodeId(2), ("K".to_string(), Some("B".to_string()))), + (NodeId(3), ("S".to_string(), None)), + ]); + (edit, drawn, roles) + } + + /// The budget: a blend whose two layouts (one per orientation, five objects each) fit in what + /// is left is made live and takes ten; one that doesn't fit, or whose spacing lays out another + /// number of steps than are drawn, isn't made live and takes nothing. + #[test] + fn a_blend_takes_from_the_budget_only_when_it_is_laid_out() { + let (edit, drawn, roles) = two_keys(); + let steps = Record { ids: vec!["A".into(), "B".into()], spacing: None }; + let mut budget = 10; + assert!(matches!(live_blend(&edit, &drawn, &steps, &roles, &mut budget), Some(NodeKind::Blend { .. }))); + assert_eq!(budget, 0); + let mut budget = 9; + assert!(live_blend(&edit, &drawn, &steps, &roles, &mut budget).is_none()); + assert_eq!(budget, 9, "a blend past the budget takes nothing"); + let nine = Record { spacing: Some(BlendSpacing::Distance(10.0)), ..steps }; + let mut budget = 10; + assert!(live_blend(&edit, &drawn, &nine, &roles, &mut budget).is_none()); + assert_eq!(budget, 10, "a spacing that lays out nine steps where three are drawn takes nothing"); + } + + /// A distance longer than the keys are apart lays out no steps: a blend drawn as its two keys + /// alone comes in live with that distance, and one of Specified Steps drawn that way doesn't. + #[test] + fn a_distance_past_the_keys_lays_out_no_steps() { + let (edit, drawn, roles) = two_keys(); + let NodeKind::Group { children, .. } = &drawn.kind else { panic!("a group") }; + let keys_alone = [children[0].clone(), children[4].clone()]; + let drawn = Node::new(NodeId(11), NodeKind::Group { children: keys_alone.to_vec(), clip: false }); + let far = Record { ids: vec!["A".into(), "B".into()], spacing: Some(BlendSpacing::Distance(150.0)) }; + let mut budget = 10; + let Some(NodeKind::Blend { spec, .. }) = live_blend(&edit, &drawn, &far, &roles, &mut budget) else { panic!("a live blend") }; + assert_eq!(spec.spacing, BlendSpacing::Distance(150.0)); + assert_eq!(budget, 6); + let steps = Record { spacing: None, ..far }; + assert!(live_blend(&edit, &drawn, &steps, &roles, &mut budget).is_none()); + assert_eq!(budget, 6); + } + /// Two drawn steps on one laid object don't both match it: each laid object matches one drawn /// one, so a drawing the blend doesn't lay out isn't taken for it. #[test] diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index a37471ba61..09d056a4e2 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -540,7 +540,7 @@ impl<'a> Reader<'a> { /// the drawn steps stay, without the blend's own art drawn over them (see [`super::blend`]). pub(super) fn end_blend(&mut self) { let Some((_, hex)) = self.blend_record.take() else { return }; - let ids = crate::import::ai::blend::hex_bytes(&hex).as_deref().and_then(crate::import::ai::blend::record_ids); + let record = crate::import::ai::blend::hex_bytes(&hex).as_deref().and_then(crate::import::ai::blend::record); let roles = &self.blend_roles; let Some(f) = self.frames.last_mut() else { return }; let n = f.children.len(); @@ -558,7 +558,7 @@ impl<'a> Reader<'a> { return; } let mut budget = self.blend_budget; - let live = ids.and_then(|ids| crate::import::ai::blend::live_blend(edit, steps, &ids, roles, &mut budget)); + let live = record.and_then(|record| crate::import::ai::blend::live_blend(edit, steps, &record, roles, &mut budget)); self.blend_budget = budget; let Some(mut steps) = f.children.pop() else { return }; let Some(_edit) = f.children.pop() else { return }; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index c1061901f8..152f6afa87 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -4303,10 +4303,16 @@ fn layer_options_of_nine_to_twelve_operands() { } /// A blend's record as the editing data writes it after `(Adobe Path Blends) 1 0 n XP`: `DCBA`, -/// version 1, then (as far as the reader reads it) the number of keys at word 10 and a record of -/// six words per key starting with its id. Hand-written; the other words are zero. +/// Specified Steps, then (as far as the reader reads it) the number of keys at word 10 and a record +/// of six words per key starting with its id. Hand-written; the other words are zero. fn blend_record(ids: &[char]) -> String { - let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), 1, 0, 0, 0, 0, 0, 0, 0, 0, ids.len() as u32]; + blend_record_spaced(ids, 1, 0.0, 0) +} + +/// [`blend_record`] with the spacing `spacing` at word 1 (0 Smooth Color, 1 Specified Steps, 2 +/// Specified Distance), the distance `distance` at word 2 and `steps` at word 4. +fn blend_record_spaced(ids: &[char], spacing: u32, distance: f32, steps: u32) -> String { + let mut words: Vec = vec![u32::from_le_bytes(*b"DCBA"), spacing, distance.to_bits(), 0, steps, 0, 0, 0, 0, 0, ids.len() as u32]; for id in ids { words.extend([*id as u32, 0, 0, 0, 0, 0]); } @@ -4332,11 +4338,16 @@ fn blend_part(kind: &str, id: Option<&str>) -> String { /// `spine` (path operators, `%_` lines), with its drawn steps (three between the keys) and the /// record `record`. fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String { - let (red, blue) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]); + blend_file_colored(spine, ids, record, [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]) +} + +/// [`blend_file`] with the left key in RGB `from`, the right one in `to`, and the steps drawn +/// between their colors. +fn blend_file_colored(spine: &str, ids: [Option<&str>; 2], record: &str, from: [f64; 3], to: [f64; 3]) -> String { let mut art = String::from("%_0 Ae\n%_u\n"); - art += &square(0.0, 40.0, 20.0, red, true); + art += &square(0.0, 40.0, 20.0, from, true); art += &blend_part("K", ids[0]); - art += &square(100.0, 40.0, 20.0, blue, true); + art += &square(100.0, 40.0, 20.0, to, true); art += &blend_part("K", ids[1]); art += spine; art += "%_N\n"; @@ -4344,7 +4355,8 @@ fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String { art += "%_U\n%_9 () XW\nu\n"; for i in 0..5 { let t = i as f64 / 4.0; - art += &square(t * 100.0, 40.0, 20.0, [1.0 - t, 0.0, t], false); + let rgb = [0, 1, 2].map(|c| from[c] + (to[c] - from[c]) * t); + art += &square(t * 100.0, 40.0, 20.0, rgb, false); } art += "U\n9 () XW\n0 Ae\n"; art += record; @@ -4389,6 +4401,106 @@ fn a_blends_spine_written_backwards_keeps_its_keys_order() { assert_eq!(spec.key_anchors, vec![1, 0], "the red key on the spine's end, the blue one on its start"); } +/// A blend's spacing comes from its record: Specified Distance with its distance (25 pt from one +/// step's edge to the corresponding edge of the next lays three out between keys 100 pt apart), +/// Smooth Color (keys 5/255 apart in blue take three steps), and Specified Steps with the steps +/// counted from the drawn ones, whatever its record's word 4 holds. The distance counts along the +/// spine between the keys, also where the spine runs on past the last key. +#[test] +fn a_blend_keeps_its_spacing() { + use vectorcraft_doc::live::BlendSpacing; + let straight = "%_10 50 m\n%_110 50 L\n"; + let longer = "%_10 50 m\n%_110 50 L\n%_1010 50 L\n"; + let (red, nearly_red, blue) = ([1.0, 0.0, 0.0], [1.0, 0.0, 5.0 / 255.0], [0.0, 0.0, 1.0]); + for (spine, record, (from, to), spacing) in [ + (straight, blend_record_spaced(&['A', 'B'], 2, 25.0, 3), (red, blue), BlendSpacing::Distance(25.0)), + (longer, blend_record_spaced(&['A', 'B'], 2, 25.0, 3), (red, blue), BlendSpacing::Distance(25.0)), + (straight, blend_record_spaced(&['A', 'B'], 0, 4.0, 3), (red, nearly_red), BlendSpacing::SmoothColor), + (straight, blend_record_spaced(&['A', 'B'], 1, 25.0, 3), (red, blue), BlendSpacing::Steps(3)), + (straight, blend_record_spaced(&['A', 'B'], 1, 12.5, 7), (red, blue), BlendSpacing::Steps(3)), + ] { + let (blend, warnings) = read_blend(&blend_file_colored(spine, [Some("A"), Some("B")], &record, from, to)); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend for {spacing:?}: {:?} {warnings:?}", blend.kind) }; + assert_eq!(spec.spacing, spacing); + assert_eq!(vectorcraft_doc::blend::blend_expand(children, spec).len(), 5, "{spacing:?}"); + assert!(!warnings.iter().any(|w| w == super::blend::DRAWN), "{spacing:?}: {warnings:?}"); + } +} + +/// A blend whose spacing doesn't lay out its drawn steps keeps them: a distance that lays out +/// nine, and Smooth Color between red and blue (more steps than the three drawn); and so does a +/// spacing the reader doesn't know or a distance that isn't a positive number. +#[test] +fn a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them() { + let straight = "%_10 50 m\n%_110 50 L\n"; + for record in [ + blend_record_spaced(&['A', 'B'], 2, 10.0, 9), + blend_record_spaced(&['A', 'B'], 0, 4.0, 254), + blend_record_spaced(&['A', 'B'], 3, 25.0, 3), + blend_record_spaced(&['A', 'B'], 2, 0.0, 3), + blend_record_spaced(&['A', 'B'], 2, f32::NAN, 3), + blend_record_spaced(&['A', 'B'], 2, 1e-30, 3), + ] { + let (blend, warnings) = read_blend(&blend_file(straight, [Some("A"), Some("B")], &record)); + assert!(!matches!(blend.kind, NodeKind::Blend { .. }), "{record}: {:?}", blend.kind); + assert_eq!(blend.children().map(|c| c.len()), Some(5), "the five drawn squares"); + assert!(warnings.iter().any(|w| w == super::blend::DRAWN), "{warnings:?}"); + } +} + +/// Three keys with Specified Distance, unevenly spaced on a straight spine (red at x 0, blue at +/// 100, green at 150, 20 pt squares): 25 pt lays three steps out between the first two keys and +/// one between the last two, and a blend drawn that way comes in live. The same seven objects +/// drawn two and two between the keys keep their drawn steps. +#[test] +fn a_blend_of_three_keys_keeps_its_distance_between_each_pair() { + use vectorcraft_doc::live::BlendSpacing; + let (red, blue, green) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]); + let mix = |a: [f64; 3], b: [f64; 3], t: f64| [0, 1, 2].map(|c| a[c] + (b[c] - a[c]) * t); + let file = |drawn: &[(f64, [f64; 3])]| { + let mut art = String::from("%_0 Ae\n%_u\n"); + for (x, rgb, id) in [(0.0, red, "A"), (100.0, blue, "B"), (150.0, green, "C")] { + art += &square(x, 40.0, 20.0, rgb, true); + art += &blend_part("K", Some(id)); + } + art += "%_10 50 m\n%_110 50 L\n%_160 50 L\n%_N\n"; + art += &blend_part("S", None); + art += "%_U\n%_9 () XW\nu\n"; + for &(x, rgb) in drawn { + art += &square(x, 40.0, 20.0, rgb, false); + } + art += "U\n9 () XW\n0 Ae\n"; + art += &blend_record_spaced(&['A', 'B', 'C'], 2, 25.0, 0); + art + }; + let three_and_one = [ + (0.0, red), + (25.0, mix(red, blue, 0.25)), + (50.0, mix(red, blue, 0.5)), + (75.0, mix(red, blue, 0.75)), + (100.0, blue), + (125.0, mix(blue, green, 0.5)), + (150.0, green), + ]; + let (blend, warnings) = read_blend(&file(&three_and_one)); + let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {warnings:?}", blend.kind) }; + assert_eq!(spec.spacing, BlendSpacing::Distance(25.0)); + assert_eq!(vectorcraft_doc::blend::blend_steps(children, spec), vec![3, 1]); + let two_and_two = [ + (0.0, red), + (100.0 / 3.0, mix(red, blue, 1.0 / 3.0)), + (200.0 / 3.0, mix(red, blue, 2.0 / 3.0)), + (100.0, blue), + (350.0 / 3.0, mix(blue, green, 1.0 / 3.0)), + (400.0 / 3.0, mix(blue, green, 2.0 / 3.0)), + (150.0, green), + ]; + let (blend, warnings) = read_blend(&file(&two_and_two)); + assert!(!matches!(blend.kind, NodeKind::Blend { .. }), "{:?}", blend.kind); + assert_eq!(blend.children().map(|c| c.len()), Some(7), "the seven drawn squares"); + assert!(warnings.iter().any(|w| w == super::blend::DRAWN), "{warnings:?}"); +} + /// A curved spine (a line, a curve and a line) is read with its points exactly; a blend whose drawn /// steps don't follow it (they are drawn on a straight line here) keeps its drawn steps. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b2b2767eab..bf40ee19a9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -995,6 +995,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Envelope Options › Anti-Alias off draws an envelope's distorted images without smoothing, and Preserve Shape Using › Transparency gives each piece of a distorted image an opacity mask in its shape instead of a clipping mask ([Envelope panel options](http://web.archive.org/web/20260513013456/https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/envelope-panel-options.html)). The four polynomial distributions are original approximations of the public description, not measured numeric parity. See [Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). + A blend in a `.ai` or EPS opened from its editing data keeps a Specified Distance spacing with its distance ([Blend Options](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-options-overview.html)) where VectorCraft lays out as many steps between each pair of keys as the file draws, in the same places and colors. A Smooth Color blend opens live only where VectorCraft's own Smooth Color step count equals the drawn steps, and VectorCraft often counts a different number. A blend that VectorCraft doesn't lay out as drawn keeps its drawn steps with a note (`import::ai::tests::a_blend_keeps_its_spacing`, `a_blend_of_three_keys_keeps_its_distance_between_each_pair`, `a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them`). - Create Strokes uses exact squared Euclidean distances and Guo–Hall thinning in bounded per-blob crops. Maximal-disc pruning, split-crossing merges and degree-two joins simplify its skeleton graph. The whole-blob width rule and ink fitting remain; 46 code-drawn inputs measure ends and junctions in [`image-trace-quality.md`](image-trace-quality.md#centre-lines). Junction degrees measure 44/45 correct in each input variant; remaining spurs are recorded. This is a measured skeleton improvement; the Image Trace score, missing per-feature selection and width controls, and estimates remain unchanged. Object › Live Paint › Merge adds the other selected paths and Live Paint groups to the bottom selected Live Paint group ([Live Paint groups](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/live-paint-groups.html)), which keeps its id, the paint of its faces and edges, and its name, lock, visibility, transparency, appearance, opacity mask and graphic style link. Object › Live Paint › Make with a Live Paint group selected, and a Live Paint Bucket click on a selected path beside a selected Live Paint group, add the paths to that group the same way. Make, Merge and the Live Paint Bucket take paths, compound paths and groups of them; with type, an image or another object among the selection they report that it has to be converted to paths first and change nothing, as type and raster images can't go into a Live Paint group directly ([Create Live Paint groups](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/create-live-paint-groups.html)); before, such an object went among the group's hidden sources and vanished from the canvas. Evidence: `tests_build::live_paint_refuses_type_and_images_and_changes_nothing`. From a176ffae468f251ccf9ed9855bab32cb77e1c6b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:16:33 -0800 Subject: [PATCH 007/482] PDF/.ai import: the file is read and checked once when it opens Opening a .ai or a PDF read and checked the whole file up to five times: for the document it carries, for whether it holds the editor's private data, for the import, for the editor's copy and for its File Info. Each pass parses the file and walks every object, about 190 ms on a 15 MB .ai. - vectorcraft_pdf::open_pdf reads and checks the file once, on the import's deep-stack thread, and import_opened imports pages from that reading. document.open takes the carried document, the page count, the editor's copy and the File Info from it. The editor's copy is read after the page import and only when the file is not restored from a carried document; so is the File Info. - A .ai saved without PDF compatibility opened with pages that name every page reads its editor's copy from the same reading. - document.pdfInfo reads the file once for its pages and the thumbnail. - The Open and Place dialogs read the file once to decide whether to ask for pages, instead of twice. A file whose PDF part fails the check still reads its editing data separately, as before. --- crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/fileio/load.rs | 101 ++++++++++++------ crates/engine/src/cmd/fileio/pdfimport.rs | 50 +++++---- .../engine/src/cmd/fileio/tests_aiimport.rs | 19 ++++ crates/pdf/Cargo.toml | 4 + crates/pdf/src/import.rs | 2 +- crates/pdf/src/import/entry.rs | 37 +++++-- crates/pdf/src/lib.rs | 9 +- crates/pdf/src/pages.rs | 78 +++++++++++++- crates/ui-egui/src/dialogs/import_pdf.rs | 8 +- 10 files changed, 237 insertions(+), 73 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 87e2d48be5..6789a21163 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -61,6 +61,8 @@ vectorcraft-testkit = { workspace = true } proptest = { workspace = true } # A variable font built in code (no font file is committed). vectorcraft-text = { workspace = true, features = ["test-fonts"] } +# How many times an open reads a PDF. +vectorcraft-pdf = { workspace = true, features = ["read-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index 7aa436f4e9..eca365ca16 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -165,14 +165,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result { /// of its art, which it carries: its layers and hidden objects as they were, and the art outside /// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read. /// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its -/// first page's `UserUnit`) → (document, warnings, whether its layers were read). -fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec, unit: f64) -> (Document, Vec, bool) { - if opts.pages.is_some() || !opts.layers || !opts.editing_data { - return (doc, warnings, false); - } - let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings, false) }; +/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `private`: the +/// editor's copy ([`editing_copy`]). +fn through_editing_data( + private: Option<&[u8]>, + opts: &LoadOptions, + doc: Document, + warnings: Vec, + unit: f64, +) -> (Document, Vec, bool) { + let Some(private) = private else { return (doc, warnings, false) }; let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines; - let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined, opts.trust_editing_data, unit); + let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(private, doc, warnings, outlined, opts.trust_editing_data, unit); // The layers weren't read (or couldn't be): the notes of reading the PDF part still hold. if !read { return (doc, warnings, false); @@ -189,18 +193,33 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning (doc, warnings, true) } -/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's -/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers or the -/// editing data are off), an error when it can't be read. -fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option)>> { - if opts.pages.is_some() || !opts.layers || !opts.editing_data { +/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page), `opened`, from the +/// editor's own copy of its art alone: `None` when the file has none (or the pages picked don't +/// name every page, or layers or the editing data are off), an error when it can't be read. +fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option)>> { + if !every_page(opened.page_count(), opts) || !opts.layers || !opts.editing_data { return None; } - let private = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref())?; - Some( - vectorcraft_eps::ai_alone(&private) - .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))), - ) + let private = opened.illustrator_data()?; + Some(editing_copy_alone(&private)) +} + +/// [`from_editing_data_alone`] of `private`, the editor's copy already read. +fn editing_copy_alone(private: &[u8]) -> Result<(Document, Vec)> { + vectorcraft_eps::ai_alone(private) + .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))) +} + +/// Does a file opened with `opts` read the editor's own copy of its art: no pages picked, and +/// layers and the editing data on? +fn reads_editing_copy(opts: &LoadOptions) -> bool { + opts.pages.is_none() && opts.layers && opts.editing_data +} + +/// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`] +/// reads it), when `opts` read it ([`reads_editing_copy`]). +fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option> { + reads_editing_copy(opts).then(|| opened.illustrator_data()).flatten() } /// A `.ai`, or a PDF saved with the editing data, whose PDF part can't be read (`e`, the import's @@ -266,10 +285,10 @@ pub(crate) fn is_placeholder(e: &EngineError) -> bool { e.to_string() == vectorcraft_pdf::PdfError::PlaceholderOnly.to_string() } -/// Do `opts` read every page of the PDF `bytes`: no `pages`, or a range that names each one? -fn every_page(bytes: &[u8], opts: &LoadOptions) -> bool { +/// Do `opts` read every page of a PDF of `count` pages: no `pages`, or a range that names each one? +fn every_page(count: usize, opts: &LoadOptions) -> bool { let Some(range) = &opts.pages else { return true }; - vectorcraft_pdf::info(bytes, opts.password.as_deref()).is_ok_and(|i| parse_range(range, i.pages.len()).is_ok_and(|p| p.len() == i.pages.len())) + parse_range(range, count).is_ok_and(|p| p.len() == count) } /// Page `page_index` (0-based) read from a PDF or `.ai` (`read`, as [`super::page_document`] reads @@ -306,6 +325,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result None => err(format!("can't open `{name}`: not a format VectorCraft reads (see document.formats)")), })?; let title = file_name(name); + // The File Info a PDF, `.ai` or `.ait` gives. + let mut file_info = None; let mut converted = false; let mut preview_only = false; let mut editing_data = false; @@ -332,13 +353,22 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result restore_or_import(editing, || import_svg(&text, folder.as_deref()))? } "pdf" | "ai" | "ait" => { + // The file is read and checked once, for the document it carries, its pages, the + // editor's copy and its File Info. + let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref()); // Saved with Preserve Editing: the document it carries, unless some pages are picked. let editing = (opts.pages.is_none() && opts.native) - .then(|| vectorcraft_pdf::editing_with(bytes, opts.password.as_deref())) + .then(|| opened.as_ref().ok().and_then(|o| o.editing())) .flatten() .map(|e| (e.intact, move || Some(e.data))); - restore_or_import(editing, || match super::pdfimport::import(bytes, opts, format.id != "pdf") { + let imported = || match &opened { + Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"), + Err(e) => Err(err(e)), + }; + let read = restore_or_import(editing, || match imported() { Ok(r) => { + // The editor's copy, read once the import is done with the pages. + let private = opened.as_ref().ok().and_then(|o| editing_copy(o, opts)); // Pages of text alone: the editing copy alone where it reads, as for a file // saved without its PDF part (#1387: else the page, which is the art). So too // pages that draw nothing at all: there is no page art to check the layers @@ -347,30 +377,35 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // decoded draws nothing either): its notes are at most the page's own. let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); let alone = (r.only_text || empty) - .then(|| from_editing_data_alone(bytes, opts)) + .then(|| private.as_deref().map(editing_copy_alone)) .flatten() .and_then(|read| read.ok()) .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)); let (doc, warnings, read) = match alone { Some((doc, warnings)) => (doc, warnings, true), - None => through_editing_data(bytes, opts, r.document, r.warnings, r.user_unit), + None => through_editing_data(private.as_deref(), opts, r.document, r.warnings, r.user_unit), }; editing_data = read; Ok((doc, warnings)) } // Saved without its PDF part: the editing copy is all the file has (`pages` that // name every page read it as the whole file). - Err(e) if is_placeholder(&e) => { - let whole = LoadOptions { pages: None, ..opts.clone() }; - from_editing_data_alone(bytes, if every_page(bytes, opts) { &whole } else { opts }) - .unwrap_or(Err(e)) - .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) - .inspect(|_| editing_data = true) - } + Err(e) if is_placeholder(&e) => opened + .as_ref() + .ok() + .and_then(|o| from_editing_data_alone(o, opts)) + .unwrap_or(Err(e)) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) + .inspect(|_| editing_data = true), // A PDF part that can't be read (a stream the import refuses): the editing copy // alone where it reads, else the error. Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), - })? + })?; + // The File Info of a file read from its pages or its editing copy. + if !read.2 { + file_info = opened.as_ref().ok().map(|o| o.file_info()); + } + read } "dxf" => { let (doc, warnings) = super::dxfimport::import(bytes, &opts.dxf)?; @@ -392,7 +427,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result // it carries, opens with the File Info it gives (a PostScript `.ai` gives none). if matches!(format.id, "pdf" | "ai" | "ait") && !restored - && let Some(info) = vectorcraft_pdf::file_info(bytes, opts.password.as_deref()) + && let Some(info) = file_info { super::super::fileinfo::read_pdf(&mut doc.metadata, info); } diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index e646c43f89..5d2663910b 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -108,15 +108,12 @@ impl LoadOptions { /// The PDF import options: `pages` resolved against the file's page count. A PDF-compatible /// `.ai`, or a PDF saved with its editing data, asked for its crop box opens on its trim boxes, /// its editor's artboards, with the bleed round them (its crop box takes the bleed in). - fn import_options(&self, bytes: &[u8], editor_document: bool) -> Result { + fn import_options(&self, opened: &vectorcraft_pdf::Opened, editor_document: bool) -> Result { let pages = match &self.pages { None => None, - Some(range) => { - let count = vectorcraft_pdf::info(bytes, self.password.as_deref()).map_err(err)?.pages.len(); - Some(parse_range(range, count).map_err(|e| err(format!("pages: {e}")))?) - } + Some(range) => Some(parse_range(range, opened.page_count()).map_err(|e| err(format!("pages: {e}")))?), }; - let is_ai = self.crop == CropTo::Crop && vectorcraft_pdf::has_illustrator_data(bytes, self.password.as_deref()); + let is_ai = self.crop == CropTo::Crop && opened.has_illustrator_data(); Ok(ImportOptions { pages, crop: if is_ai { CropTo::Trim } else { self.crop }, @@ -140,24 +137,33 @@ fn choice(cmd: &str, key: &str, id: Option<&str>) -> Result .ok_or_else(|| bad(cmd, format!("{key} must be one of {}", T::IDS.join(", ")))) } -/// Import the pages `o` pick → the document, import notes and what else the import tells. +/// Import the pages `o` pick of `opened`, the PDF `bytes` already read +/// ([`vectorcraft_pdf::open_pdf`]) → the document, import notes and what else the import tells. /// `editor_document`: a `.ai` file. -pub(super) fn import(bytes: &[u8], o: &LoadOptions, editor_document: bool) -> Result { - vectorcraft_pdf::import_with_report(bytes, &o.import_options(bytes, editor_document)?).map_err(err) +pub(super) fn import( + bytes: &[u8], + opened: &vectorcraft_pdf::Opened, + o: &LoadOptions, + editor_document: bool, +) -> Result { + let options = o.import_options(opened, editor_document)?; + vectorcraft_pdf::import_opened(bytes, opened, &options).map_err(err) } /// Page `page` (0-based) of a PDF as a document of one artboard (its `o.crop` box) and one /// layer of what it shows, with the same text choice as Open, and the import notes. pub fn page_document(bytes: &[u8], page: usize, o: &LoadOptions) -> Result<(Document, Vec)> { - let opts = ImportOptions { - pages: Some(vec![page]), - crop: o.crop, - password: o.password.clone(), - text_as: o.text_as, - layers: false, - ..Default::default() - }; - vectorcraft_pdf::import_with_report(bytes, &opts).map(|r| (r.document, r.warnings)).map_err(err) + vectorcraft_pdf::import_with_report(bytes, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err) +} + +/// [`page_document`] of `opened`, the PDF `bytes` already read. +fn opened_page_document(bytes: &[u8], opened: &vectorcraft_pdf::Opened, page: usize, o: &LoadOptions) -> Result<(Document, Vec)> { + vectorcraft_pdf::import_opened(bytes, opened, &page_options(page, o)).map(|r| (r.document, r.warnings)).map_err(err) +} + +/// The import options of [`page_document`]. +fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { + ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } const INFO: &str = "document.pdfInfo"; @@ -170,13 +176,15 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result { if bytes.starts_with(b"%!") || vectorcraft_pdf::is_postscript(&bytes) { return postscript_info(&bytes, p); } - let info = match vectorcraft_pdf::info(&bytes, o.password.as_deref()) { - Ok(i) => i, + // The file is read once, for its pages and the thumbnail. + let opened = match vectorcraft_pdf::open_pdf(&bytes, o.password.as_deref()) { + Ok(opened) => opened, Err(e @ (PdfError::NeedsPassword | PdfError::WrongPassword)) => { return Ok(json!({"pages": 0, "needsPassword": true, "wrongPassword": e == PdfError::WrongPassword, "pageInfo": []})); } Err(e) => return Err(err(e)), }; + let info = opened.info(); let r4 = |r: vectorcraft_geom::Rect| json!([r.x0, r.y0, r.x1, r.y1]); let pages: Vec = info .pages @@ -188,7 +196,7 @@ pub(super) fn pdf_info(_: &mut Session, p: &Value) -> Result { .collect(); let mut out = json!({"pages": pages.len(), "needsPassword": false, "pageInfo": pages}); if let Some(page) = thumbnail_page(p, info.pages.len(), "PDF")? { - let (doc, _) = page_document(&bytes, page, &o)?; + let (doc, _) = opened_page_document(&bytes, &opened, page, &o)?; out["thumbnail"] = json!(thumbnail(&doc, p)?); } Ok(out) diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index e0f6600d95..66b6d01dff 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -82,6 +82,25 @@ fn an_illustrator_ai_file_opens_from_its_editing_data() { assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art", "Hidden"]); } +/// Opening a `.ai` or a PDF whose PDF part reads, or a `.ai` saved without PDF compatibility, +/// reads and checks the file once, on any thread, for the document it may carry, its pages, its +/// editing data and its File Info, with pages picked or not. +#[test] +fn an_ai_or_pdf_file_is_read_once_when_it_opens() { + let ai_file = ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()); + let pdf_file = pdf_with(&[PdfPage::new(100.0, 100.0, "0 0 1 rg 10 10 50 50 re f")], &[], None); + let placeholder = ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER); + for (name, file) in [("art.ai", &ai_file), ("art.pdf", &pdf_file), ("placeholder.ai", &placeholder)] { + for opts in [LoadOptions::default(), LoadOptions { pages: Some("1".into()), ..Default::default() }] { + let before = vectorcraft_pdf::reads_of(file); + let loaded = load_with(name, file, &opts).unwrap(); + assert_eq!(vectorcraft_pdf::reads_of(file) - before, 1, "{name}, pages {:?}", opts.pages); + let editing_data = name == "placeholder.ai" || (name == "art.ai" && opts.pages.is_none()); + assert_eq!(loaded.editing_data, editing_data, "{name}, pages {:?}", opts.pages); + } + } +} + #[test] fn an_ai_file_opens_with_its_artboard_options_raster_settings_and_author() { let document = "%_/Document :\n%_/Dictionary :\n%_/Dictionary :\n%_150 /Int (dpi.) ,\n%_1 /Bool (mask) ,\n%_; (AI Auto Rasterize) ,\n\ diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index f56aecf728..6bd298a078 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -8,6 +8,10 @@ description = "VectorCraft PDF export and import" [lints] workspace = true +[features] +# `vectorcraft_pdf::reads_of` for other crates' tests (dev-dependencies only). +read-count = [] + [dependencies] vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index b045931010..ff04da781d 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -40,7 +40,7 @@ mod state; pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; pub use entry::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, - import, import_with_report, is_glyph_outlines, is_outlines_note, + import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; #[cfg(test)] pub(crate) use entry::{TEST_MAX_OBJECTS, import_with_reader_options, read}; diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index bc4996d58d..3f521c0265 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -200,6 +200,12 @@ pub fn import_with_report(bytes: &[u8], opts: &ImportOptions) -> Result Result { + vectorcraft_doc::depth::with_deep_stack(|| read_opened(bytes, opts, &crate::pages::open_options(), &opened.pdf)) +} + /// [`import_with_report`] on the thread that asks. pub(crate) fn read(bytes: &[u8], opts: &ImportOptions) -> Result { read_with_reader_options(bytes, opts, &crate::pages::open_options()) @@ -212,10 +218,21 @@ pub(crate) fn import_with_reader_options(bytes: &[u8], opts: &ImportOptions, rea fn read_with_reader_options(bytes: &[u8], opts: &ImportOptions, reader: &craft_pdf::OpenOptions) -> Result { let original = crate::pages::open_with_options(bytes, opts.password.as_deref(), reader)?; + read_opened(bytes, opts, reader, &original) +} + +/// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`. +fn read_opened( + bytes: &[u8], + opts: &ImportOptions, + reader: &craft_pdf::OpenOptions, + original: &craft_pdf::syntax::Pdf, +) -> Result { let picked = crate::pages::picked(opts, original.pages().len())?; - let mut ocgs = Ocgs::read(&original); + let mut ocgs = Ocgs::read(original); let route = opts.layers && !ocgs.list.is_empty(); - let (pdf, all_on, notes) = reopen_with_groups_on(bytes, opts, reader, original, &picked, &mut ocgs, route)?; + let (turned_on, all_on, notes) = reopen_with_groups_on(bytes, opts, reader, original, &picked, &mut ocgs, route)?; + let pdf = turned_on.as_ref().unwrap_or(original); let pages = pdf.pages(); let sink: Arc>> = Arc::default(); @@ -227,7 +244,7 @@ fn read_with_reader_options(bytes: &[u8], opts: &ImportOptions, reader: &craft_p doc.artboards.clear(); doc.layers.clear(); let taken: Vec = doc.swatches_iter().map(|s| s.name.clone()).chain(doc.swatch_groups.iter().map(|g| g.name.clone())).collect(); - let mut b = Builder::new(doc.peek_next_id(), Colors::new(&pdf, taken.clone()), opts.text_as, route); + let mut b = Builder::new(doc.peek_next_id(), Colors::new(pdf, taken.clone()), opts.text_as, route); // The art of a group that is off (drawn as `all_on` turned it on) or doesn't print mustn't // show or print on its page's layer. b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print); @@ -440,7 +457,7 @@ fn read_with_reader_options(bytes: &[u8], opts: &ImportOptions, reader: &craft_p } warnings.extend(depth_notes); let user_unit = picked.first().and_then(|&n| pages.get(n)).map_or(1.0, |page| f64::from(page.user_unit())); - Ok(ImportReport { document: doc, warnings, native: crate::editing::editing_in(&pdf), only_text, user_unit }) + Ok(ImportReport { document: doc, warnings, native: crate::editing::editing_in(pdf), only_text, user_unit }) } /// The page a PDF-compatible `.ai` paints under its layers is the editor's page, not art: an opaque @@ -487,17 +504,17 @@ fn is_only_text(nodes: &[Arc]) -> bool { } /// Opens the file again with every layer group turned on when the pages hide art in groups that are -/// off, and tells whether it did. Gives the file to read, whether it is the turned-on copy, and the -/// notes for the import's report. +/// off, and tells whether it did. Gives the turned-on copy (`None`: read `original`), whether there +/// is one, and the notes for the import's report. fn reopen_with_groups_on( bytes: &[u8], opts: &ImportOptions, reader: &craft_pdf::OpenOptions, - original: craft_pdf::syntax::Pdf, + original: &craft_pdf::syntax::Pdf, picked: &[usize], ocgs: &mut Ocgs, route: bool, -) -> Result<(craft_pdf::syntax::Pdf, bool, Vec), PdfError> { +) -> Result<(Option, bool, Vec), PdfError> { // Content that is off imports as hidden layers: an update of the file turns every group on // (unless a form is hidden by its own group: its art couldn't be told apart). let hide = route && ocgs.skips_any(); @@ -511,7 +528,7 @@ fn reopen_with_groups_on( } } let turned_on = (hide && !hidden_form) - .then(|| all_on(bytes, &original)) + .then(|| all_on(bytes, original)) .flatten() .and_then(|b| crate::pages::open_with_options(&b, opts.password.as_deref(), reader).ok()) .filter(|p| Ocgs::read(p).list.is_empty()); @@ -520,7 +537,7 @@ fn reopen_with_groups_on( notes.push("the art of hidden layers couldn't be read and was left out".to_string()); } let all_on = turned_on.is_some(); - Ok((turned_on.unwrap_or(original), all_on, notes)) + Ok((turned_on, all_on, notes)) } /// The interpreter's settings, its warnings noted once each in `sink` (truncated content in `incomplete`). diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 9c52e19992..d39fc0b95d 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -78,9 +78,14 @@ pub use export::{export, export_with_report, page_areas}; pub use file_info::{FileInfo, file_info}; pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, - import, import_with_report, is_glyph_outlines, is_outlines_note, + import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, +}; +#[cfg(any(test, feature = "read-count"))] +pub use pages::reads_of; +pub use pages::{ + IllustratorData, Opened, PageInfo, PdfInfo, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, is_postscript, + open_pdf, }; -pub use pages::{IllustratorData, PageInfo, PdfInfo, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, is_postscript}; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; pub use presets::*; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 1468d6d8db..b5cee4b1bc 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -234,6 +234,54 @@ pub(crate) fn open(bytes: &[u8], password: Option<&str>) -> Result) -> Result { + vectorcraft_doc::depth::with_deep_stack(|| open(bytes, password)).map(|pdf| Opened { pdf }) +} + +impl Opened { + /// The pages and their boxes, as [`info`] lists them. + pub fn info(&self) -> PdfInfo { + info_in(&self.pdf) + } + + /// The native document the PDF carries, as [`editing`](crate::editing) reads it. + pub fn editing(&self) -> Option { + crate::editing::editing_in(&self.pdf) + } + + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. + pub fn illustrator_data(&self) -> Option> { + private_data(&self.pdf) + } + + /// Does the first page carry an editor's copy of the art, as [`has_illustrator_data`] says? + pub fn has_illustrator_data(&self) -> bool { + has_private_data_keys(&self.pdf) + } + + /// The File Info, as [`crate::file_info`] reads it. + pub fn file_info(&self) -> crate::FileInfo { + crate::file_info::file_info_in(&self.pdf) + } + + /// How many pages the PDF has, as [`info`] lists them. + pub fn page_count(&self) -> usize { + self.pdf.pages().len() + } +} + /// Preserve the application's existing accepted file sizes. Ordinary stream decoding still /// uses the shared reader's immutable per-document limits, and its input copy is fallible. pub(crate) fn open_options() -> craft_pdf::OpenOptions { @@ -249,10 +297,25 @@ pub(crate) fn open_with_options(bytes: &[u8], password: Option<&str>, options: & }) } +/// How many times each buffer has been read as a PDF, by its address (tests). +#[cfg(any(test, feature = "read-count"))] +static READS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// How many times `bytes`, at its address, has been read as a PDF on any thread (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn reads_of(bytes: &[u8]) -> usize { + READS.lock().ok().and_then(|r| r.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) +} + /// [`open_with_options`] without looking at the file's objects ([`hostile`]): the reader builds its /// table of objects and its page tree, and nothing on a page is read. For reading one object that /// is checked on its own ([`illustrator_data_without_pdf_part`]), never for importing a page. fn open_structural_with_options(bytes: &[u8], password: Option<&str>, options: &craft_pdf::OpenOptions) -> Result { + #[cfg(any(test, feature = "read-count"))] + if let Ok(mut reads) = READS.lock() { + let n = reads.entry(bytes.as_ptr() as usize).or_default(); + *n = n.saturating_add(1); + } if is_postscript(bytes) { return Err(PdfError::PostScript); } @@ -282,7 +345,11 @@ fn open_structural_with_options(bytes: &[u8], password: Option<&str>, options: & /// The pages and their boxes. An encrypted PDF needs its `password` /// ([`PdfError::NeedsPassword`] / [`PdfError::WrongPassword`]). pub fn info(bytes: &[u8], password: Option<&str>) -> Result { - let pdf = open(bytes, password)?; + Ok(info_in(&open(bytes, password)?)) +} + +/// [`info`] of a parsed PDF. +fn info_in(pdf: &Pdf) -> PdfInfo { let pages = pdf .pages() .iter() @@ -299,7 +366,7 @@ pub fn info(bytes: &[u8], password: Option<&str>) -> Result { PageInfo { width: w as f64, height: h as f64, rotation, boxes } }) .collect(); - Ok(PdfInfo { pages }) + PdfInfo { pages } } /// The 0-based pages `opts` pick out of `count`. @@ -419,7 +486,12 @@ fn private_data(pdf: &Pdf) -> Option> { /// (`AIPrivateData` keys) or a PDF saved with its editing data (`AIPDFPrivateData`, #1345)? Without /// reading the data. Either's trim boxes are its editor's artboards. pub fn has_illustrator_data(bytes: &[u8], password: Option<&str>) -> bool { - open(bytes, password).is_ok_and(|pdf| pdf.pages().first().is_some_and(|p| piece_info_has(p, &[b"AIPrivateData", b"AIPDFPrivateData"]))) + open(bytes, password).is_ok_and(|pdf| has_private_data_keys(&pdf)) +} + +/// [`has_illustrator_data`] of a parsed PDF. +fn has_private_data_keys(pdf: &Pdf) -> bool { + pdf.pages().first().is_some_and(|p| piece_info_has(p, &[b"AIPrivateData", b"AIPDFPrivateData"])) } /// `stream` decoded, up to `most` bytes: the decoder is run here rather than by the PDF reader's diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index eb30028b09..9a2223744d 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -122,11 +122,13 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option 1 => (i.pages.len(), false), + let (pages, locked) = match opened.map(|o| o.page_count()) { + Ok(count) if count > 1 => (count, false), Err(PdfError::NeedsPassword) => (0, true), _ => return false, }; From f4469e16d6b4e0f13205464d865e56716632d3e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:59:25 -0800 Subject: [PATCH 008/482] Control bar: the Global Edit Options dropdown shows while Start Global Edit can run While Select > Start Global Edit can run, the Control bar shows a Global Edit Options dropdown after Recolor Artwork. It opens the Properties panel's Global Edit Options (Match: Appearance, Size; On Artboards; Include Objects On Canvas; Result(s)), so both set the same options, and it is off while Global Edit is on, as the Properties dropdown is. The bar leaves it out when no room is left for it. Public reference: https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html The dropdown takes room ahead of the inline X/Y/W/H fields, so the ruler-origin tests that read X/Y from the Control bar draw it 1700 px wide. --- crates/ui-egui/src/chrome/control_bar.rs | 22 +++++++ crates/ui-egui/src/chrome/tests.rs | 78 ++++++++++++++++++++++++ crates/ui-egui/src/panels/properties.rs | 5 +- crates/ui-egui/src/tests/ruler_origin.rs | 2 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 6 files changed, 106 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 924a644067..a40d88dfe5 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -135,6 +135,27 @@ fn isolation_button(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The size of the Control bar's Global Edit Options button. +const GLOBAL_EDIT_OPTIONS_WIDTH: f32 = 24.0; + +/// The Control bar's Global Edit Options dropdown, shown while `select.globalEdit` can run. The help +/// page places the options in the Control panel as well as in Properties +/// (). +/// It opens the Properties panel's Global Edit Options, which set the same session options, and is +/// off while Global Edit is on, as that panel's dropdown is. It sits after Recolor Artwork, ahead of +/// the X/Y/W/H fields that the bar leaves out when it runs short of room, and is left out only when +/// no room is left for it. +fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { + if !crate::menus::enabled(app, "select.globalEdit") || ui.available_width() < GLOBAL_EDIT_OPTIONS_WIDTH { + return; + } + let on = app.session.active().is_some_and(|d| d.global_edit.is_some()); + let options = widgets::icon_button_enabled(ui, "chevron-down", tl!("Global Edit Options"), false, !on, GLOBAL_EDIT_OPTIONS_WIDTH); + egui::Popup::menu(&options) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| crate::panels::properties::global_edit_options(app, ui)); +} + /// The room the Control bar's inline X/Y/W/H fields need; with less, only the Transform link shows. const INLINE_TRANSFORM_WIDTH: f32 = 440.0; @@ -237,6 +258,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { if colored && widgets::icon_button(ui, "palette", tl!("Recolor Artwork"), false, 24.0).clicked() { crate::menus::invoke(app, "ui.recolorDialog", json!({})); } + global_edit_options(app, ui); } ui.separator(); crate::panels::character::control_bar(app, ui); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index a2773f5f7b..00c56ff67a 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1803,3 +1803,81 @@ fn the_control_bar_shows_the_distribute_buttons_for_two_or_more_objects() { }; assert_eq!((left(&app, &a), left(&app, &b), left(&app, &c)), (10.0, 105.0, 200.0), "{}", app.ui.status); } + +/// The Control bar shows the Global Edit Options dropdown while Start Global Edit can run. Its +/// options are the session's, which the Properties panel's dropdown also sets: Match Size from +/// the Control bar narrows the Results and the objects Start Global Edit takes. The dropdown is off +/// while Global Edit is on, and absent when the selection cannot start it. +#[test] +fn the_control_bar_shows_the_global_edit_options() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let rect = |app: &mut crate::VectorcraftApp, x: f64, size: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 20, "width": size, "height": size})).unwrap()["id"].clone() + }; + let a = rect(&mut app, 20.0, 40.0); + rect(&mut app, 100.0, 40.0); + rect(&mut app, 200.0, 80.0); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 300.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + let find = |nodes: &Nodes, name: &str| nodes.iter().find(|(_, n)| n.label() == Some(name) || n.value() == Some(name)).map(|(_, n)| n.clone()); + let center = |n: &egui::accesskit::Node| { + let b = n.bounds().unwrap_or_else(|| panic!("{n:?}")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + let click = |app: &mut crate::VectorcraftApp, at: egui::Pos2| { + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at), press(true)]); + frame(app, vec![press(false)]); + frame(app, vec![]); + frame(app, vec![]) + }; + app.run("select.set", json!({"ids": []})).unwrap(); + frame(&mut app, vec![]); + assert!(find(&frame(&mut app, vec![]), "Global Edit Options").is_none(), "nothing selected: no dropdown"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + frame(&mut app, vec![]); + let nodes = frame(&mut app, vec![]); + let button = find(&nodes, "Global Edit Options").unwrap_or_else(|| panic!("one rectangle: the dropdown shows")); + let nodes = click(&mut app, center(&button)); + assert!(find(&nodes, "Results: 3").is_some(), "the options open with their Results"); + let size = find(&nodes, "Size").unwrap_or_else(|| panic!("the Size check")); + let nodes = click(&mut app, center(&size)); + assert!(app.session.global_edit_options.size, "Match Size is the session's option, shared with Properties"); + assert!(find(&nodes, "Results: 2").is_some(), "Size narrows the Results"); + app.run("select.globalEdit", json!({})).unwrap(); + let ge = app.session.active().unwrap().global_edit.as_ref().map(|g| g.members.len()); + assert_eq!(ge, Some(2), "Start Global Edit takes the two rectangles of the same size"); + let nodes = frame(&mut app, vec![]); + let button = find(&nodes, "Global Edit Options").unwrap_or_else(|| panic!("Global Edit on: the dropdown still shows")); + assert!(button.is_disabled(), "the options are off while Global Edit is on"); + // At any width the button either fits inside the bar or is left out, and a wider bar never + // leaves it out once a narrower one showed it. + app.run("select.globalEdit", json!({})).unwrap(); + let mut seen = false; + for width in (600..=2400).step_by(10) { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); + let mut nodes = Vec::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(&mut app, ui)); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + let shown = find(&nodes, "Global Edit Options").and_then(|n| n.bounds()); + if let Some(b) = shown { + assert!(b.x1 <= f64::from(width), "{width}: {b:?}"); + } + assert!(!seen || shown.is_some(), "{width}: left out after a narrower bar showed it"); + seen |= shown.is_some(); + } + assert!(seen, "a wide bar has room for it"); +} diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index c94b6e4ab7..f236c6a738 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -245,8 +245,9 @@ fn global_edit_row(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The Global Edit Options: what else similar objects must share (Match), where they may lie (On -/// Artboards) and how many objects that takes now. -fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { +/// Artboards) and how many objects that takes now. The Control bar's Global Edit Options dropdown +/// shows them too. +pub(crate) fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { ui.set_min_width(220.0); let o = app.session.global_edit_options.clone(); let set = |app: &mut VectorcraftApp, p: serde_json::Value| crate::menus::invoke(app, "select.globalEditOptions", p); diff --git a/crates/ui-egui/src/tests/ruler_origin.rs b/crates/ui-egui/src/tests/ruler_origin.rs index dd5a1fcc87..de4a0501e6 100644 --- a/crates/ui-egui/src/tests/ruler_origin.rs +++ b/crates/ui-egui/src/tests/ruler_origin.rs @@ -24,7 +24,7 @@ fn context() -> egui::Context { fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, draw: fn(&mut VectorcraftApp, &mut Ui)) -> Vec<(String, Rect)> { let raw = egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 900.0))), + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1700.0, 900.0))), time: Some(ctx.input(|i| i.time) + 0.05), events, ..Default::default() diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bf40ee19a9..6d10c3994a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -498,6 +498,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. 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`. - **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. - **Escape in more tool drags:** Escape during an Anchor Point drag, a Mesh tool drag, a Direct Selection drag of a mesh point, a corner widget or the brackets of type on a path, or a Shape Builder drag cancels it: the art goes back to how the press found it, no undo step is added, the release does nothing, and the tool stays chosen. Escape during a Measure tool drag brings back the measurement before it. Regression tests: `escape_cancels_*` in `draw2/anchor/tests.rs`, `meshedit.rs`, `direct/tests.rs`, `builder/tests.rs` and `xform/measure.rs`, and `escape_cancels_an_anchor_point_mesh_shape_builder_or_measure_drag` in `tests/toolescape.rs`. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 843ca66c75..b1f034cdaa 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -325,7 +325,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Actions panel: Delete Selection (bottom bar) deletes the selected set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.delete`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: deleting a set asks first (a selected action is still deleted at once), Shift-click on a set's name selects a range of sets, ≡ › Delete does the same as the button, and Default Actions and the last set can be deleted. Undo does not restore a deleted set, and recorded commands cannot be selected or deleted | | Actions panel: ≡ › Duplicate copies the selected action or set ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.actionSet.duplicate`; `panels/actions.rs` tests. VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected, and a copied set holds copies of all its actions. Undo does not remove the copy, and recorded commands cannot be duplicated | | Properties panel per context (every selection type's Quick Actions) | partial | one clip group: Edit Clipping Path and Edit Contents, at the top of the panel rather than in Quick Actions (G1); the overview's additional controls ([Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html)): Blend Options (one blend selected, with any tool, #4817) and Merge Live Paint (a Live Paint group with more) in Quick Actions, the Width Profile list (Width tool or a variable-width stroke) and an applied effect's Delete icon in Appearance, Corner and Corner Radius for corners selected with Direct Selection; Variable Font was already there | -| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control panel's copy of the options, rotated copies and highlighting matches before the start remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | +| Select › Start Global Edit / Stop Global Edit; Properties › Quick Actions with the Global Edit Options popover (Match: Appearance, Size; On Artboards: All Artboards or a range, Include Objects On Canvas; Result(s)); Escape stops it; the matched objects are highlighted in their layer colour while it runs; a Shift-click on a highlighted match leaves it out | partial | #3521, `select.globalEdit` / `select.globalEditOptions` / `select.globalEditExclude`, `crates/engine/src/tests/globaledit.rs`; paths, compound paths, symbol instances and groups of them (similar groups, #4939: edits inside one group reach the same object in the others; [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-groups-with-similar-objects.html)); Shift-click to leave a match out ([public source](https://helpx.adobe.com/ph_fil/illustrator/how-to/global-editing-sensei.html)); the Control bar's Global Edit Options dropdown opens the same options; rotated copies and highlighting matches before the start remain ([public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-similar-objects.html)) | | Contextual task bar | done | | | Control bar with Transform and Stroke popovers | done | | | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | From 322f1c24db16f135e23983bdf6cc43d86e7bc122 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 15:41:24 +0700 Subject: [PATCH 009/482] .ai import: brushes come in from the editing data Squashed from #5046 onto main. --- crates/engine/tests/import_fuzz.rs | 38 +++ crates/eps/src/import/ai.rs | 3 +- crates/eps/src/import/ai/brush.rs | 341 ++++++++++++++++++++ crates/eps/src/import/ai/read.rs | 25 +- crates/eps/src/import/ai/read/directives.rs | 139 +++++++- crates/eps/src/import/ai/read/document.rs | 142 +++++++- crates/eps/src/import/ai/tests.rs | 180 +++++++++++ crates/eps/src/import/native/layers.rs | 41 ++- crates/eps/src/import/tests_native.rs | 94 ++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 1 + 37 files changed, 1016 insertions(+), 16 deletions(-) create mode 100644 crates/eps/src/import/ai/brush.rs diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index fda4ad8903..2e7d90aa61 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3427,6 +3427,44 @@ proptest! { survive("hostile Objects on Path", || Some(vectorcraft_eps::layered_ai(&private, Document::new(200.0, 100.0), vec![], false, true, 1.0).0))?; } } + + /// Brush objects of every kind with any parameters, the brush manager's order with any names, + /// and brush art sections nested or cut short: read with the layers, or as a library without + /// them, the brushes kept within their ranges. + #[test] + fn ai_brushes_never_panic( + kind in 0usize..7, + params in prop::collection::vec(prop_oneof![arb_num(), Just("/".to_string()), Just(" / ".to_string()), Just("nan".to_string()), Just("inf".to_string()), "[A-Za-z ]{0,6}"], 0..40), + order in "[ -~]{0,80}", + nest in 0usize..6, + cut in any::(), + layers in any::(), + ) { + use vectorcraft_testkit::ai; + let kinds = ["Adobe Calligraphic Brush Tool", "Adobe Scatter Brush Tool", "Adobe ArtOnPath Brush Tool", "Adobe PatternOnPath Brush Tool", "Adobe dBrush Brush Tool", "Adobe Brush Manager Order", "Other"]; + let object = |k: &str, name: &str, p: &str| { + let chars: Vec = p.chars().collect(); + let lines: String = chars.chunks(12).map(|c| format!("({}) -\n", c.iter().collect::())).collect(); + format!("%AI8_BeginPluginObject\n({k})\n({name})\n{lines}() .\n%AI8_EndPluginObject\n") + }; + let p = params.join(" "); + let mut art = String::new(); + for _ in 0..nest { + art.push_str("%AI8_BeginBrushPattern\n(A)\n"); + } + art.push_str("0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"); + for _ in 0..nest.saturating_sub(usize::from(cut)) { + art.push_str("%AI8_EndBrushPattern\n"); + } + let records = format!("{art}{}{}", object(kinds[kind], "B", &p), object(kinds[5], kinds[5], &order.replace(['(', ')', '\\'], ""))); + let body = if layers { format!("{records}{}", ai::layer("L", "0 g\n10 10 m\n20 20 L\nS\n")) } else { records }; + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&ai::editing_data(100.0, 100.0, &body))].concat(); + survive("hostile .ai brushes", || { + let d = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0; + let _ = vectorcraft_brush::library(&d); + Some(d) + })?; + } } /// The data [`ai_objects_on_path_never_panics`] damages, as it is, opens with its Objects on Path group. diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index ea437a4d13..75a9debf2b 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -18,6 +18,7 @@ //! did before (the printed page, or the PDF), with a warning saying why. mod blend; +mod brush; mod envelope; mod frames; mod lex; @@ -35,7 +36,7 @@ use crate::ps; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use frames::text_frames; -pub use read::{IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, palette, read, read_beside, variables}; +pub use read::{Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, brushes, palette, read, read_beside, variables}; pub(crate) use read::{join_and, slot_frame, slot_of}; pub(crate) use read::is_look_slot; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs new file mode 100644 index 0000000000..f7e1f8893d --- /dev/null +++ b/crates/eps/src/import/ai/brush.rs @@ -0,0 +1,341 @@ +//! Brush definitions (not publicly documented): plug-in objects in the setup, as written in files +//! that users own and sent us, brush library files among them (not presets installed with any +//! other app). +//! +//! - Each object is a `%AI8_BeginPluginObject` section of strings: the plug-in's name, the brush's +//! name, then its parameters, split into strings that `-` continues and `.` ends. +//! - One object, the brush manager's order, has the order of the Brushes panel: its parameters +//! are the plug-in name and brush name of each brush, each one after a `/` and a space. +//! - A Calligraphic brush's parameters are 11 numbers: the first is 1; the diameter, roundness and +//! angle as (low, high) pairs; how the diameter, roundness and angle vary (0 Fixed, 1 Random, 2 +//! Pressure, other codes the pen's other channels); a last number. +//! - A Scatter, Art or Pattern brush's parameters are fields split by `/`: a number, the art's +//! section names (one for Scatter, five for Art and Pattern, empty where there is none, each +//! after a space for Art and Pattern), more fields, and last 15 numbers. +//! - Scatter: the size (2, 3), spacing (5, 6) and scatter (8, 9) as (low, high) factors of the +//! art, the rotation in degrees (11, 12), how each varies (4, 7, 10, 13) and whether the +//! rotation follows the path (14). +//! - Pattern: its scale as a factor (3). +//! - A Bristle brush's parameters start with 8 numbers: two codes, then the stiffness, bristle +//! thickness, density, paint opacity and bristle length as fractions and the size in +//! millimeters. +//! - The art is a `%AI8_BeginBrushPattern` section: its name as a string, then the art (read by +//! [`super::read`]). +//! +//! What isn't read keeps its default: the Art brush's options, the pattern brush's tiles (which +//! slot is which tile isn't known) and every brush's colorization, which is left at None so the +//! art keeps its own colors. + +use std::collections::HashMap; + +use vectorcraft_brush::{ArtBrush, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; +use vectorcraft_doc::Node; + +use super::lex::{Lexer, Tok}; +use super::obj; + +/// The brush manager's order: the plug-in name of its object. +pub(super) const MANAGER: &str = "Adobe Brush Manager Order"; // brand-ok: the plug-in name the files use + +/// The plug-in names of the brush kinds. +const TOOLS: [(&str, Tool); 5] = [ + ("Adobe Calligraphic Brush Tool", Tool::Calligraphic), // brand-ok: the plug-in name the files use + ("Adobe Scatter Brush Tool", Tool::Scatter), // brand-ok: the plug-in name the files use + ("Adobe ArtOnPath Brush Tool", Tool::Art), // brand-ok: the plug-in name the files use + ("Adobe PatternOnPath Brush Tool", Tool::Pattern), // brand-ok: the plug-in name the files use + ("Adobe dBrush Brush Tool", Tool::Bristle), // brand-ok: the plug-in name the files use +]; + +/// Most brushes read from one file. +pub(super) const MAX_BRUSHES: usize = 4096; +/// Most brush art sections read from one file (a pattern brush has up to five). +pub(super) const MAX_BRUSH_ART: usize = 5 * MAX_BRUSHES; +/// Most [`art_weight`] copied into the brushes of one file, each brush counting its own copy. +const MAX_BRUSH_ART_NODES: usize = 250_000; + +/// Most bytes of a plug-in object's parameters read (the brush manager's order of [`MAX_BRUSHES`] +/// brushes with long names fits): the rest is left out. +const MAX_PARAMS: usize = 1 << 20; + +/// Millimeters → points. +const MM: f64 = 72.0 / 25.4; + +/// A brush's kind, as its plug-in name gives it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Tool { + Calligraphic, + Scatter, + Art, + Pattern, + Bristle, +} + +/// The kind of a brush whose object's plug-in name is `name`. +pub(super) fn tool(name: &str) -> Option { + TOOLS.iter().find(|(n, _)| *n == name).map(|(_, t)| *t) +} + +/// A brush as its object gives it: its definition, and the names of the art sections it needs. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct BrushDraft { + pub name: String, + pub kind: DraftKind, +} + +#[derive(Clone, Debug, PartialEq)] +pub(super) enum DraftKind { + Calligraphic(Calligraphic), + /// The art is the section named `art`. + Scatter { + brush: Scatter, + art: String, + }, + /// The art is the section named `art`. + Art { + brush: ArtBrush, + art: String, + }, + /// The five art sections the brush names, in its order (which is which tile isn't known), and + /// its scale (%). + Pattern { + tiles: [Option; 5], + scale: f64, + }, + Bristle(Bristle), +} + +impl DraftKind { + pub(super) fn tool(&self) -> Tool { + match self { + DraftKind::Calligraphic(_) => Tool::Calligraphic, + DraftKind::Scatter { .. } => Tool::Scatter, + DraftKind::Art { .. } => Tool::Art, + DraftKind::Pattern { .. } => Tool::Pattern, + DraftKind::Bristle(_) => Tool::Bristle, + } + } +} + +/// Why a brush's object isn't read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum BrushError { + /// Fewer values than the kind has, or one that isn't a finite number. + Values, + /// No art section named. + NoArt, +} + +/// The strings of a plug-in object's section (`section`: what follows `%AI8_BeginPluginObject`): +/// its plug-in name, its name and its parameters, joined. `None` with fewer than two strings. +pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, String, String)> { + let mut lex = Lexer::new(section); + let mut strings = vec![]; + let mut params = vec![]; + while let Some(t) = lex.next_token() { + if let Tok::Str(s) | Tok::Hex(s) = t.tok { + if strings.len() < 2 { + strings.push(obj::text(&s)); + } else { + // Joined before they are text: a string may end inside a character. + let room = MAX_PARAMS.saturating_sub(params.len()); + params.extend_from_slice(s.get(..room.min(s.len())).unwrap_or_default()); + } + } + } + let [kind, name]: [String; 2] = strings.try_into().ok()?; + Some((kind, name, obj::text(¶ms))) +} + +/// The brush manager's order (`params`: its parameters): the kind and name of each brush. Pairs +/// whose plug-in name isn't a brush kind's are left out; `None` when there are none. +pub(super) fn parse_brush_manager(params: &str) -> Option> { + let fields: Vec<&str> = params.split('/').take(2 * MAX_BRUSHES).map(|f| f.strip_prefix(' ').unwrap_or(f)).collect(); + let mut out = vec![]; + for [kind, name] in fields.as_chunks::<2>().0 { + if let Some(t) = tool(kind) + && out.len() < MAX_BRUSHES + { + out.push((t, (*name).to_string())); + } + } + (!out.is_empty()).then_some(out) +} + +/// The numbers of `s` (split by white space): `None` when one isn't a finite number. +fn numbers(s: &str) -> Option> { + s.split_whitespace().map(|w| w.parse::().ok().filter(|v| v.is_finite())).collect() +} + +/// How a value varies, by its code: `None` for a code that isn't Fixed, Random or Pressure. +fn variation(code: f64) -> Option { + match code { + 0.0 => Some(Variation::Fixed), + 1.0 => Some(Variation::Random), + 2.0 => Some(Variation::Pressure), + _ => None, + } +} + +/// [`variation`], or for another code, Random when the value varies and Fixed when it doesn't. +fn mode(code: f64, varies: bool) -> Variation { + variation(code).unwrap_or(if varies { Variation::Random } else { Variation::Fixed }) +} + +/// The brush named `name` of kind `kind` from its parameters `params`. +pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result { + let kind = match kind { + Tool::Calligraphic => { + let n = numbers(params).ok_or(BrushError::Values)?; + let [_, d0, d1, r0, r1, a0, a1, dm, rm, am, ..] = n.as_slice() else { return Err(BrushError::Values) }; + let mid = |a: f64, b: f64| (a + b) / 2.0; + let half = |a: f64, b: f64| (b - a).abs() / 2.0; + let variation = [half(*a0, *a1), half(*r0, *r1), half(*d0, *d1)]; + let modes = [mode(*am, variation[0] != 0.0), mode(*rm, variation[1] != 0.0), mode(*dm, variation[2] != 0.0)]; + DraftKind::Calligraphic(Calligraphic { + angle: mid(*a0, *a1), + roundness: mid(*r0, *r1), + size: mid(*d0, *d1), + variation, + modes: Some(modes), + }) + } + Tool::Scatter | Tool::Art | Tool::Pattern => { + let fields: Vec<&str> = params.split('/').collect(); + let slots = if kind == Tool::Scatter { 1 } else { 5 }; + if fields.len() < slots + 2 { + return Err(BrushError::Values); + } + let tiles: Vec> = fields + .iter() + .skip(1) + .take(slots) + .map(|f| { + let f = f.strip_prefix(' ').unwrap_or(f); + (!f.is_empty()).then(|| f.to_string()) + }) + .collect(); + let n = fields.last().and_then(|f| numbers(f)).ok_or(BrushError::Values)?; + let [_, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, _] = n.as_slice() else { return Err(BrushError::Values) }; + let art = || tiles.first().cloned().flatten().ok_or(BrushError::NoArt); + match kind { + Tool::Scatter => { + let pct = |a: f64, b: f64| (a * 100.0, b * 100.0); + let values = [pct(*p2, *p3), pct(*p5, *p6), pct(*p8, *p9), (*p11, *p12)]; + let codes = [*p4, *p7, *p10, *p13]; + let modes = [0, 1, 2, 3].map(|i| mode(codes[i], values[i].0 != values[i].1)); + let [size, spacing, scatter, rotation] = values; + let brush = Scatter { + size, + spacing, + scatter, + rotation, + rotation_relative_to_path: *p14 == 1.0, + colorization: Colorization::None, + modes: Some(modes), + ..Scatter::default() + }; + DraftKind::Scatter { brush, art: art()? } + } + Tool::Art => DraftKind::Art { brush: ArtBrush { colorization: Colorization::None, ..ArtBrush::default() }, art: art()? }, + _ => { + let tiles: [Option; 5] = tiles.try_into().map_err(|_| BrushError::Values)?; + DraftKind::Pattern { tiles, scale: p3 * 100.0 } + } + } + } + Tool::Bristle => { + let words: Vec<&str> = params.split_whitespace().take(8).collect(); + let n = numbers(&words.join(" ")).ok_or(BrushError::Values)?; + let [_, _, stiffness, thickness, density, opacity, length, size] = n.as_slice() else { return Err(BrushError::Values) }; + DraftKind::Bristle(Bristle { + stiffness: stiffness * 100.0, + thickness: thickness * 100.0, + density: density * 100.0, + opacity: opacity * 100.0, + length: length * 100.0, + size: size * MM, + ..Bristle::default() + }) + } + }; + Ok(BrushDraft { name: name.to_string(), kind }) +} + +/// The brushes of `drafts`, their art from the sections `art` (by name), in the brush manager's +/// `order` (brushes it doesn't list after those it does, in the order of their objects), each +/// kept within its ranges → the brushes and how many were left out: those whose art isn't read, +/// pattern brushes (which slot holds which tile isn't known), a second brush of the same name, and +/// brushes whose copies of art go past [`MAX_BRUSH_ART_NODES`]. +pub(super) fn finish_brushes(drafts: Vec, art: &HashMap, order: Option<&[(Tool, String)]>) -> (Vec, usize) { + finish_brushes_within(drafts, art, order, MAX_BRUSH_ART_NODES) +} + +/// What copying `art` costs: its nodes, the art of their opacity masks, and the anchors of their paths. +pub(super) fn art_weight(art: &Node) -> usize { + let mut weight = 0usize; + art.walk(&mut |n| { + weight = weight.saturating_add(1 + n.path_data().map_or(0, |p| p.anchor_count())); + if let Some(m) = &n.extras().mask { + weight = weight.saturating_add(art_weight(&m.art)); + } + }); + weight +} + +/// [`finish_brushes`] with at most `budget` of [`art_weight`] copied into the brushes (each brush +/// that uses a section holds its own copy): a brush whose art would go past it is left out. +pub(super) fn finish_brushes_within( + drafts: Vec, + art: &HashMap, + order: Option<&[(Tool, String)]>, + budget: usize, +) -> (Vec, usize) { + let mut left_out = 0; + let mut copied = 0usize; + let mut weights: HashMap<&str, usize> = HashMap::new(); + let mut copy = |name: &str| -> Option { + let (key, a) = art.get_key_value(name)?; + let weight = *weights.entry(key.as_str()).or_insert_with(|| art_weight(a)); + let total = copied.saturating_add(weight); + (total <= budget).then(|| { + copied = total; + a.clone() + }) + }; + let mut made: Vec> = vec![]; + for d in drafts { + let tool = d.kind.tool(); + let repeated = made.iter().flatten().any(|(_, b)| b.name == d.name); + let kind = match d.kind { + _ if repeated => None, + DraftKind::Calligraphic(c) => Some(BrushKind::Calligraphic(c)), + DraftKind::Scatter { brush, art: name } => copy(&name).map(|a| BrushKind::Scatter(Scatter { art: a, ..brush })), + DraftKind::Art { brush, art: name } => copy(&name).map(|a| BrushKind::Art(ArtBrush { art: a, ..brush })), + DraftKind::Pattern { .. } => None, + DraftKind::Bristle(b) => Some(BrushKind::Bristle(b)), + }; + match kind { + Some(kind) => { + let mut b = Brush { name: d.name, kind }; + b.sanitize(); + made.push(Some((tool, b))); + } + _ => left_out += 1, + } + } + let mut out = Vec::with_capacity(made.len()); + for (tool, name) in order.unwrap_or_default() { + if let Some(slot) = made.iter_mut().find(|m| m.as_ref().is_some_and(|(t, b)| t == tool && &b.name == name)) + && let Some((_, b)) = slot.take() + { + out.push(b); + } + } + out.extend(made.into_iter().flatten().map(|(_, b)| b)); + (out, left_out) +} + +/// The note for brushes [`finish_brushes`] left out. +pub(super) fn left_out_note(n: usize) -> String { + format!("brushes VectorCraft can't read yet were left out of the Brushes panel ({n})") +} diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 53555528c8..885cc6a7c2 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -70,6 +70,9 @@ //! - Swatches: the palette (`%AI5_BeginPalette`), read by [`super::palette`], replaces the //! default swatches. //! +//! - Brushes: the brush plug-in objects and their art sections (`%AI8_BeginBrushPattern`), read by +//! [`super::brush`], replace the default brushes when the file has any. +//! //! - Graphic styles: the style list (`%AI9_BeginArtStyleList`), one `(name)` per style in the //! panel's order, each the name of an art style. The listed styles whose appearance reads //! ([`appearance_from_art_style`](ops::appearance_from_art_style)) replace the default graphic @@ -77,7 +80,7 @@ //! style's appearance and transparency is linked to it. A `1` naming a style the list doesn't //! have is the object's own appearance, not a link. //! -//! Sections the reader doesn't need (brushes, symbols, styles, filters) are skipped; +//! Sections the reader doesn't need (symbols, styles, filters) are skipped; //! type, symbols, fills with a pattern it can't read, placed files without a preview and operators //! it doesn't know are errors. So is data that ends inside a layer, a group or a compound path. @@ -114,7 +117,7 @@ mod types; pub(crate) use art::join_and; use art::preview_png; -pub use document::{PaletteSwatches, VariableRead, artboards, palette, variables}; +pub use document::{Brushes, PaletteSwatches, VariableRead, artboards, brushes, palette, variables}; pub(crate) use document::{slot_frame, slot_of}; pub use types::IMAGE_TOO_LARGE; use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster}; @@ -341,6 +344,18 @@ struct Reader<'a> { /// The legacy text object being read (`To` … `TO`), and the modal type attributes. text: Option, type_state: legacy_text::TypeState, + /// The file has brush objects (the brush manager's order or a brush). + brush_objects: bool, + /// The brush manager's order. + brush_order: Option>, + /// The brushes read, in the order of their objects. + brush_drafts: Vec, + /// The art of the brushes (`%AI8_BeginBrushPattern`), by name. + brush_art: HashMap, + /// The brush art sections read so far, repeated names included. + brush_art_sections: usize, + /// Brush objects that weren't read. + brushes_unread: usize, /// The graph being read (see [`Reader::graph_record`]). graph: Option, /// The multi-layer mask being read (`Mb` … `MB`), which goes on past a layer's end. @@ -451,6 +466,12 @@ impl<'a> Reader<'a> { v7_patterns: HashSet::new(), text: None, type_state: legacy_text::TypeState::default(), + brush_objects: false, + brush_order: None, + brush_drafts: Vec::new(), + brush_art: HashMap::new(), + brush_art_sections: 0, + brushes_unread: 0, graph: None, multi_mask: None, } diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index cf047363a8..e2c9df048b 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -1,9 +1,10 @@ +use super::super::brush; use super::art::{four, sane, two}; use super::types::{ FLIP, GState, Kind, MAX_HEX, MAX_NOTE, MAX_PATTERNS, MAX_PLACED_FOLDER, MAX_STACK, MAX_SUBREADERS, PatternHead, Place, Raster, SKIPPED, VERSIONED_UNENDED, }; -use super::{Arc, Node, PatternDef, Reader, Rect, Tok, V, marker}; +use super::{Arc, Lexer, Node, PatternDef, Reader, Rect, Tok, V, marker, obj}; impl<'a> Reader<'a> { pub(super) fn push(&mut self, v: V) -> Result<(), String> { @@ -98,6 +99,17 @@ impl<'a> Reader<'a> { self.symbol_bounds(section); return Ok(()); } + // Brushes and their art (those in a pattern's or a brush's art aren't read). + if m == "BeginPluginObject" && self.pattern.is_none() { + let section = self.section("EndPluginObject")?; + self.plugin_object(section); + return Ok(()); + } + if m == "BeginBrushPattern" && self.pattern.is_none() { + let section = self.section("EndBrushPattern")?; + self.define_brush_art(section); + return Ok(()); + } if m == "BeginArtStyles" { let section = self.section("EndArtStyles")?; self.styles = crate::import::ai::style::art_styles(section); @@ -505,6 +517,71 @@ impl<'a> Reader<'a> { } } + /// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's + /// order or a brush ([`brush`]); other objects are left alone. + fn plugin_object(&mut self, section: &[u8]) { + let Some((kind, name, params)) = brush::plugin_strings(section) else { return }; + if kind == brush::MANAGER { + self.brush_objects = true; + self.brush_order = brush::parse_brush_manager(¶ms); + return; + } + let Some(tool) = brush::tool(&kind) else { return }; + self.brush_objects = true; + if self.brush_drafts.len() >= brush::MAX_BRUSHES { + self.brushes_unread += 1; + return; + } + match brush::parse_tool_object(tool, &name, ¶ms) { + Ok(d) => self.brush_drafts.push(d), + Err(_) => self.brushes_unread += 1, + } + } + + /// A brush's art (`section`: what follows `%AI8_BeginBrushPattern`, its name as a string, then + /// the art), read by a reader of its own as a pattern's is, in a space with y down. Art it can't + /// read whole isn't kept: the brushes that use it aren't read. + fn define_brush_art(&mut self, section: &[u8]) { + if self.brush_art_sections >= brush::MAX_BRUSH_ART || self.subreader_depth >= MAX_SUBREADERS { + return; + } + self.brush_art_sections += 1; + let mut lex = Lexer::new(section); + let Some(Tok::Str(name) | Tok::Hex(name)) = lex.next_token().map(|t| t.tok) else { return }; + let name = obj::text(&name); + let mut sub = Reader::new(lex.slice(lex.offset(), section.len())); + // In a space of its own (y down), with no head to take. + sub.pattern = Some(PatternHead { taken: true, ..PatternHead::default() }); + sub.subreader_depth = self.subreader_depth + 1; + // The gradients and patterns defined so far, lent. + sub.gradients = std::mem::take(&mut self.gradients); + sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); + sub.nodes = self.nodes; + sub.template = self.template; + let read = sub.open(Kind::Group, false).and_then(|()| sub.run()); + self.nodes = sub.nodes; + self.gradients = std::mem::take(&mut sub.gradients); + self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); + // Images aren't kept: the document's images don't count a brush's art among their users. Art + // read with a note (something left out of it) isn't kept either. + let whole = read.is_ok() + && sub.unsupported.is_empty() + && sub.unknown.is_empty() + && sub.unread.is_empty() + && sub.hidden_unread.is_empty() + && sub.warnings.is_empty() + && sub.frames.len() == 1 + && sub.doc.images.is_empty(); + let Some(frame) = sub.frames.pop().filter(|f| whole && !f.children.is_empty()) else { return }; + let mut art: Vec> = frame.children.iter().map(|n| Arc::new(self.doc.reid(n))).collect(); + let node = match art.len() { + 1 => art.pop().map(Arc::unwrap_or_clone), + _ => Some(Node::group(self.doc.alloc_id(), art)), + }; + let Some(node) = node else { return }; + self.brush_art.insert(name, node); + } + /// In a pattern's definition, the operands of its first operator start with its head, /// `(name) llx lly urx ury`: taken off them. pub(super) fn take_head(&mut self, mut vals: Vec) -> Vec { @@ -717,4 +794,64 @@ mod tests { reader.symbol_bounds(definition.as_bytes()); assert!(reader.symbol_bounds.is_empty()); } + + #[test] + fn brush_art_stops_at_subreader_limit() { + let art = b"(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"; + let mut reader = Reader::new(b""); + reader.define_brush_art(art); + assert_eq!(reader.brush_art.len(), 1); + let mut reader = Reader::new(b""); + reader.subreader_depth = MAX_SUBREADERS; + reader.define_brush_art(art); + assert!(reader.brush_art.is_empty()); + } + + #[test] + fn brush_art_sections_stop_at_their_limit_with_repeated_names() { + let mut reader = Reader::new(b""); + reader.brush_art_sections = brush::MAX_BRUSH_ART - 1; + reader.define_brush_art(b"(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"); + let first = reader.brush_art.get("A").map(|n| n.id); + assert!(first.is_some()); + // The same name again is past the limit: the first art stays. + reader.define_brush_art(b"(A)\n0 g\n0 0 m\n8 0 L\n8 8 L\nf\n"); + assert_eq!(reader.brush_art.get("A").map(|n| n.id), first); + } + + #[test] + fn brushes_sharing_art_stop_at_the_budget_of_copied_nodes() { + let mut reader = Reader::new(b""); + reader.define_brush_art(b"(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n"); + let nodes = reader.brush_art.get("A").map(brush::art_weight).unwrap_or_default(); + assert!(nodes > 0); + let draft = |i: usize| brush::BrushDraft { + name: format!("Brush {i}"), + kind: brush::DraftKind::Art { brush: vectorcraft_brush::ArtBrush::default(), art: "A".to_string() }, + }; + let drafts: Vec<_> = (0..5).map(draft).collect(); + let (kept, left_out) = brush::finish_brushes_within(drafts.clone(), &reader.brush_art, None, 3 * nodes); + assert_eq!((kept.len(), left_out), (3, 2)); + let (kept, left_out) = brush::finish_brushes_within(drafts, &reader.brush_art, None, 5 * nodes); + assert_eq!((kept.len(), left_out), (5, 0)); + // A second brush of the same name is left out without using the budget. + let mut repeated: Vec<_> = (0..2).map(draft).collect(); + repeated.insert(1, draft(0)); + let (kept, left_out) = brush::finish_brushes_within(repeated, &reader.brush_art, None, 2 * nodes); + assert_eq!((kept.len(), left_out), (2, 1)); + } + + #[test] + fn brush_art_with_an_unread_object_is_not_kept() { + // A placed file the data keeps no preview of, shown and hidden. + let placed = + "%AI5_BeginPlace\n%%FileType: 1\n[5 0 0 -5 0 200] 10 20 14 22 4 4 0\n(missing.png)`\n%%IncludeFile:missing.png\n~\n%AI5_EndPlace\n"; + let hidden: String = placed.lines().map(|l| format!("%_{l}\n")).collect(); + for placed in [placed, hidden.as_str()] { + let art = format!("(A)\n0 g\n0 0 m\n4 0 L\n4 4 L\nf\n{placed}"); + let mut reader = Reader::new(b""); + reader.define_brush_art(art.as_bytes()); + assert!(reader.brush_art.is_empty(), "{placed:?}"); + } + } } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 63dc189687..c5a05b9152 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1,3 +1,4 @@ +use super::super::brush; use super::art::{element_name, join_and, sane}; use super::containers::drop_commented_copies; use super::ops::appearance_from_art_style; @@ -171,29 +172,85 @@ fn artboard_array(data: &[u8]) -> Option<&[u8]> { pub struct PaletteSwatches { pub swatches: Vec, pub groups: Vec, - /// The patterns the editing data defines that the given patterns lack and a swatch paints with. + /// The patterns the editing data defines that a swatch paints with, named apart from the given + /// patterns ([`beside`]). pub patterns: Vec, /// The image blobs the art of `patterns` shows, by key. pub images: std::collections::BTreeMap, } +/// The editing data's patterns `defined`, for a document that has the patterns `have` (those of a +/// file's PDF part or page): each keeps its name, except one whose name a pattern of `have` already +/// has (the PDF part names its tilings `Pattern 1`, `Pattern 2` and so on), which takes a free +/// variant (`Pattern 1 2`). The art of each pattern paints with the names they got. Also the names +/// changed, old to new. The same `defined` and `have` always give the same names. +fn beside(mut defined: Vec, have: &[PatternDef]) -> (Vec, std::collections::BTreeMap) { + let mut renamed = std::collections::BTreeMap::new(); + let mut taken: std::collections::BTreeSet = have.iter().chain(&defined).map(|p| p.name.clone()).collect(); + let tries = taken.len() + 2; + for d in &mut defined { + if !have.iter().any(|p| p.name == d.name) { + continue; + } + let Some(name) = (2..=tries).map(|i| format!("{} {i}", d.name)).find(|n| !taken.contains(n)) else { continue }; + taken.insert(name.clone()); + renamed.insert(std::mem::replace(&mut d.name, name.clone()), name); + } + if !renamed.is_empty() { + for d in &mut defined { + for a in &mut d.art { + repoint(Arc::make_mut(a), &renamed); + } + } + } + (defined, renamed) +} + +/// `n` and what it holds painting with the patterns `renamed` renames (old to new) by their new names. +fn repoint(n: &mut Node, renamed: &std::collections::BTreeMap) { + for p in vectorcraft_doc::swatches::node_paints_mut(n) { + if let Paint::Pattern { pattern, .. } = p + && let Some(new) = renamed.get(pattern) + { + pattern.clone_from(new); + } + } + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_mut()) { + repoint(Arc::make_mut(&mut mask.art), renamed); + } + if let Some(children) = n.children_mut() { + for c in children { + repoint(Arc::make_mut(c), renamed); + } + } +} + /// The swatches and color groups of the palette of the editing data `data`, for a file whose /// layers aren't read: the swatches its PDF part has are the defaults (#4036). They come as /// [`read`] makes them, with pattern swatches only for the patterns in `patterns` and those the -/// editing data defines; `None` when the palette is empty or reading stops before it. +/// editing data defines, which are named apart from `patterns` ([`beside`]); `None` when the +/// palette is empty or reading stops before it. pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option { let mut r = Reader::new(data); // The palette, the gradients and the patterns it names come before the art, so an error in the // art leaves them read. let _ = r.run(); + let (defined, renamed) = beside(std::mem::take(&mut r.doc.patterns), patterns); let mut known = patterns.to_vec(); - let defined = std::mem::take(&mut r.doc.patterns); - known.extend(defined.iter().filter(|d| !patterns.iter().any(|p| p.name == d.name)).cloned()); - let (swatches, groups) = r.palette_swatches(&known)?; + known.extend(defined.iter().cloned()); + let (mut swatches, mut groups) = r.palette_swatches(&known)?; + // A swatch of a pattern the editing data defines paints with that pattern, under the name it got. + for s in swatches.iter_mut().chain(groups.iter_mut().flat_map(|g| &mut g.swatches)) { + if let Paint::Pattern { pattern, .. } = &mut s.paint + && let Some(new) = renamed.get(pattern) + { + pattern.clone_from(new); + } + } let painted = |name: &str| { swatches.iter().chain(groups.iter().flat_map(|g| &g.swatches)).any(|s| matches!(&s.paint, Paint::Pattern { pattern, .. } if pattern == name)) }; - let added: Vec = defined.into_iter().filter(|d| !patterns.iter().any(|p| p.name == d.name) && painted(&d.name)).collect(); + let added: Vec = defined.into_iter().filter(|d| painted(&d.name)).collect(); let mut shown = Document::new(1.0, 1.0); shown.patterns.clone_from(&added); let mut images = std::collections::BTreeMap::new(); @@ -205,6 +262,61 @@ pub fn palette(data: &[u8], patterns: &[PatternDef]) -> Option Some(PaletteSwatches { swatches, groups, patterns: added, images }) } +/// The brushes of a `.ai` file's editing data, as [`brushes`] reads them. +pub struct Brushes { + pub brushes: Vec, + /// The patterns the editing data defines that the brushes' art paints with, named apart from + /// the given patterns ([`beside`]). + pub patterns: Vec, + /// The image blobs the art of `patterns` shows, by key. + pub images: std::collections::BTreeMap, + /// The note for the brushes left out. + pub note: Option, +} + +/// The brushes of the editing data `data`, for a file whose layers aren't read (a brush library +/// has none), as [`read`] makes them, with the patterns of the editing data their art paints with, +/// named apart from `patterns` ([`beside`]) as [`palette`] names them. `None` when the file has no +/// brush objects or reading stops before them. +pub fn brushes(data: &[u8], patterns: &[PatternDef]) -> Option { + // Brush objects are plug-in objects: data without one isn't read again. + memchr::memmem::find(data, b"BeginPluginObject")?; + let mut r = Reader::new(data); + // The brushes come before the art, so an error in the art leaves them read. + let _ = r.run(); + let (mut lib, unread) = r.brush_library()?; + let (defined, renamed) = beside(std::mem::take(&mut r.doc.patterns), patterns); + if !renamed.is_empty() { + for a in lib.iter_mut().flat_map(|b| b.art_mut()) { + repoint(a, &renamed); + } + } + // The patterns the brushes' art paints with, and those their art paints with, and so on. + let mut stack: Vec<&vectorcraft_doc::Node> = lib.iter().flat_map(|b| b.art()).collect(); + let mut used = std::collections::BTreeSet::new(); + while let Some(n) = stack.pop() { + stack.extend(n.children().into_iter().flatten().chain(n.extras().mask.as_ref().map(|m| &m.art)).map(|c| &**c)); + for p in vectorcraft_doc::swatches::node_paints(n) { + if let Paint::Pattern { pattern, .. } = p + && used.insert(pattern.clone()) + && let Some(d) = defined.iter().find(|d| &d.name == pattern) + { + stack.extend(d.art.iter().map(|a| &**a)); + } + } + } + let added: Vec = defined.into_iter().filter(|d| used.contains(&d.name)).collect(); + let mut shown = Document::new(1.0, 1.0); + shown.patterns.clone_from(&added); + let mut images = std::collections::BTreeMap::new(); + shown.visit_images(|_, im| { + if let Some(blob) = r.doc.images.get(&im.key) { + images.insert(im.key.clone(), blob.clone()); + } + }); + Some(Brushes { brushes: lib, patterns: added, images, note: (unread > 0).then(|| brush::left_out_note(unread)) }) +} + /// [`artboards`] as far as reading `data` from its start gets: those read before an error, and /// those of a `/Document` still open when it stopped (its art can be what stopped it). fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { @@ -538,6 +650,17 @@ impl<'a> Reader<'a> { Some((swatches, groups)) } + /// The brushes read ([`brush::finish_brushes`]) and how many weren't; `None` when the file has + /// no brush objects (the document keeps the default brushes). + fn brush_library(&mut self) -> Option<(Vec, usize)> { + if !self.brush_objects { + return None; + } + let drafts = std::mem::take(&mut self.brush_drafts); + let (lib, left_out) = brush::finish_brushes(drafts, &self.brush_art, self.brush_order.as_deref()); + Some((lib, left_out + self.brushes_unread)) + } + /// The graphic styles of the style list, in its order: each listed name the art styles define with /// an appearance [`appearance_from_art_style`] reads, once (a name listed again, empty or not /// defined is left out), with ids from 1. Also the id of each kept name. @@ -691,6 +814,7 @@ impl<'a> Reader<'a> { doc.swatches.push(Swatch { paint: Paint::Pattern { pattern: name.clone(), xf: Affine::IDENTITY }, name, global: false, spot: false }); } } + let brushes = self.brush_library(); // The file's graphic styles in place of the defaults, and the objects linked to them. let (styles, ids) = self.graphic_styles(); let styles_read = !styles.is_empty(); @@ -702,6 +826,12 @@ impl<'a> Reader<'a> { doc.graphic_styles = styles.into(); } let mut warnings = self.warnings; + if let Some((lib, unread)) = brushes { + vectorcraft_brush::store(&mut doc, &lib); + if unread > 0 { + warnings.push(brush::left_out_note(unread)); + } + } if self.drawn_looks > 0 { warnings.push(format!( "objects with several fills or strokes, effects or brushes came in as their drawn look ({}): their appearance isn't editable yet", diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 152f6afa87..cbe7966e7f 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -4959,6 +4959,186 @@ fn an_objects_on_path_group_in_versioned_content_opens_once() { assert!(kids[0].extras().objects_on_path.is_some()); } +// ---- brushes ------------------------------------------------------------------------------ + +const CALLIGRAPHIC: &str = "Adobe Calligraphic Brush Tool"; +const SCATTER: &str = "Adobe Scatter Brush Tool"; +const ART_BRUSH: &str = "Adobe ArtOnPath Brush Tool"; +const PATTERN_BRUSH: &str = "Adobe PatternOnPath Brush Tool"; +const BRISTLE: &str = "Adobe dBrush Brush Tool"; + +/// A plug-in object of plug-in `kind` named `name`, its parameters `params` split into strings of +/// 16 characters at most (`-` after each but the last, `.` after that). +fn plugin_object(kind: &str, name: &str, params: &str) -> String { + let chars: Vec = params.chars().collect(); + let chunks: Vec = chars.chunks(16).map(|c| c.iter().collect()).collect(); + let n = chunks.len(); + let lines: String = chunks.iter().enumerate().map(|(i, c)| format!("({c}) {}\n", if i + 1 == n { "." } else { "-" })).collect(); + format!("%AI5_Begin_NonPrinting\nNp\n%AI8_BeginPluginObject\n({kind})\n({name})\n{lines}%AI8_EndPluginObject\n%AI5_End_NonPrinting--\n") +} + +/// The brush manager's order of the brushes `brushes` (plug-in, name). +fn brush_order(brushes: &[(&str, &str)]) -> String { + let params: String = brushes.iter().map(|(k, n)| format!(" {k}/ {n}/")).collect(); + plugin_object(brush::MANAGER, brush::MANAGER, ¶ms) +} + +/// A brush's art named `name`: a filled square of side `side`. +fn brush_art(name: &str, side: f64) -> String { + format!("%AI8_BeginBrushPattern\n({name})\n0 A\n0 g\n{}f\n%AI8_EndBrushPattern\n", rect_path(0.0, 0.0, side, side)) +} + +/// A Calligraphic brush with diameter 2 to 6, roundness 40 to 60 and angle -30 to 10, the diameter +/// varying at random, the roundness fixed and the angle with the pen's pressure. +const NIB: &str = "1 2 6 40 60 -30 10 1 0 2 0"; +/// A Scatter brush of the art `Dot art`: size 50% to 150% at random, spacing 120% to 200% fixed, +/// scatter -25% to 25% with the pressure, rotation -45° to 30° at random and following the path. +const SPRAY: &str = "2 /Dot art/ 5 1 0 0 / 0 0.5 1.5 1 1.2 2 0 -0.25 0.25 2 -45 30 1 1 0"; +/// An Art brush of the art `Ribbon art`. +const RIBBON: &str = "2 / Ribbon art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"; +/// A Pattern brush of four tiles (the fourth slot empty) at 80%. +const FENCE: &str = "2 / Tile one/ Tile two/ Tile three/ / Tile five/ 0 0/ 0 1 / 1 1 0.8 0 4 0 0 0 0.8 0.8 0 0 0 0 0"; +/// A Bristle brush: stiffness 60%, thickness 40%, density 30%, opacity 80%, length 150%, size 2 mm. +const MOP: &str = "0 4 0.6 0.4 0.3 0.8 1.5 2 library shape"; + +/// The brushes of the five kinds, their art and the manager's order (the Bristle brush first). +fn five_brushes() -> String { + let order = brush_order(&[(BRISTLE, "Mop"), (CALLIGRAPHIC, "Nib"), (SCATTER, "Spray"), (ART_BRUSH, "Ribbon"), (PATTERN_BRUSH, "Fence")]); + let art: String = ["Dot art", "Ribbon art", "Tile one", "Tile two", "Tile three", "Tile five"].iter().map(|n| brush_art(n, 4.0)).collect(); + let objects = [ + (CALLIGRAPHIC, "Nib", NIB), + (SCATTER, "Spray", SPRAY), + (ART_BRUSH, "Ribbon", RIBBON), + (PATTERN_BRUSH, "Fence", FENCE), + (BRISTLE, "Mop", MOP), + ]; + let objects: String = objects.iter().map(|(k, n, p)| plugin_object(k, n, p)).collect(); + format!("{art}{order}{objects}") +} + +fn brush_named<'a>(lib: &'a [vectorcraft_brush::Brush], name: &str) -> &'a vectorcraft_brush::BrushKind { + match lib.iter().find(|b| b.name == name) { + Some(b) => &b.kind, + None => panic!("no brush {name} in {:?}", lib.iter().map(|b| &b.name).collect::>()), + } +} + +/// The brush manager's order gives the kind and name of each brush, in the panel's order. +#[test] +fn the_brush_managers_order_gives_each_brushs_kind_in_order() { + let params = format!(" {BRISTLE}/ Mop/ {CALLIGRAPHIC}/ Nib/ {SCATTER}/ Spray/ {ART_BRUSH}/ Ribbon/ {PATTERN_BRUSH}/ Fence /"); + let order = brush::parse_brush_manager(¶ms).unwrap(); + use brush::Tool; + let want = [(Tool::Bristle, "Mop"), (Tool::Calligraphic, "Nib"), (Tool::Scatter, "Spray"), (Tool::Art, "Ribbon"), (Tool::Pattern, "Fence ")]; + assert_eq!(order, want.map(|(t, n)| (t, n.to_string())), "a name keeps its trailing spaces"); + assert_eq!(brush::parse_brush_manager(" Some Other Plugin/ Thing/"), None); +} + +/// A file's brushes replace the default ones, in the manager's order, with their values. A pattern +/// brush is left out (which slot holds which tile isn't known), with a note. +#[test] +fn a_files_brushes_come_in_with_their_values_in_the_panels_order() { + let r = read_ok(&format!("{}{}", five_brushes(), layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Mop", "Nib", "Spray", "Ribbon"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w == "brushes VectorCraft can't read yet were left out of the Brushes panel (1)"), "{:?}", r.warnings); + use vectorcraft_brush::{BrushKind, Variation}; + let BrushKind::Calligraphic(c) = brush_named(&lib, "Nib") else { panic!("calligraphic") }; + assert_eq!((c.angle, c.roundness, c.size), (-10.0, 50.0, 4.0)); + assert_eq!(c.variation, [20.0, 10.0, 2.0]); + assert_eq!(c.modes, Some([Variation::Pressure, Variation::Fixed, Variation::Random])); + let BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + assert_eq!((s.size, s.spacing, s.scatter, s.rotation), ((50.0, 150.0), (120.0, 200.0), (-25.0, 25.0), (-45.0, 30.0))); + assert_eq!(s.modes, Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random])); + assert!(s.rotation_relative_to_path); + assert_eq!(s.art.geometric_bounds().map(|b| (b.width(), b.height())), Some((4.0, 4.0)), "the art of its section"); + let BrushKind::Art(a) = brush_named(&lib, "Ribbon") else { panic!("art") }; + assert!(a.art.geometric_bounds().is_some(), "the art of its section"); + assert_eq!(a.colorization, vectorcraft_brush::Colorization::None, "the art keeps its colors"); + let BrushKind::Bristle(b) = brush_named(&lib, "Mop") else { panic!("bristle") }; + let got = [b.stiffness, b.thickness, b.density, b.opacity, b.length, b.size]; + let want = [60.0, 40.0, 30.0, 80.0, 150.0, 2.0 * 72.0 / 25.4]; + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-9), "{got:?}"); +} + +/// A Pattern brush's five slots name its art sections, in its order, an empty slot naming none; +/// its scale comes in as a percentage. +#[test] +fn a_pattern_brushs_five_slots_are_kept() { + let d = brush::parse_tool_object(brush::Tool::Pattern, "Fence", FENCE).unwrap(); + let brush::DraftKind::Pattern { tiles, scale } = d.kind else { panic!("{d:?}") }; + let s = |n: &str| Some(n.to_string()); + assert_eq!(tiles, [s("Tile one"), s("Tile two"), s("Tile three"), None, s("Tile five")]); + assert!((scale - 80.0).abs() < 1e-9); + let d = brush::parse_tool_object(brush::Tool::Scatter, "Spray", SPRAY).unwrap(); + assert!(matches!(d.kind, brush::DraftKind::Scatter { ref art, .. } if art == "Dot art"), "{d:?}"); + let d = brush::parse_tool_object(brush::Tool::Art, "Ribbon", RIBBON).unwrap(); + assert!(matches!(d.kind, brush::DraftKind::Art { ref art, .. } if art == "Ribbon art"), "{d:?}"); +} + +/// A brush's art filled with a pattern the file defines before it is read, with that pattern. +#[test] +fn a_brushs_art_takes_the_patterns_defined_before_it() { + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let art_ = format!( + "%AI8_BeginBrushPattern\n(Dot art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 4.0, 4.0) + ); + let r = read_ok(&format!("{dots}{art_}{}{}", plugin_object(SCATTER, "Spray", SPRAY), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + let vectorcraft_brush::BrushKind::Scatter(s) = brush_named(&lib, "Spray") else { panic!("scatter") }; + assert!(matches!(fill(&s.art), Paint::Pattern { ref pattern, .. } if pattern == "Dots"), "{:?}", r.warnings); +} + +/// A file without brush objects keeps the default brushes. +#[test] +fn a_file_without_brushes_keeps_the_default_ones() { + let r = read_ok(&layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n"))); + assert!(!r.doc.unknown.contains_key(vectorcraft_brush::DOC_KEY)); +} + +/// A brush whose object can't be read, or whose art is missing or can't be read, is left out with a +/// note; the layers and the other brushes still come in. +#[test] +fn a_brush_that_cant_be_read_leaves_the_layers_and_other_brushes() { + let bad_art = "%AI8_BeginBrushPattern\n(Odd art)\n0 g\n0 0 m\n1 1 L\nnotanoperator\nf\n%AI8_EndBrushPattern\n"; + let objects = [ + plugin_object(CALLIGRAPHIC, "Nib", NIB), + plugin_object(CALLIGRAPHIC, "Short", "1 2 3"), + plugin_object(CALLIGRAPHIC, "Huge", "1 2 inf 40 60 -30 10 1 0 2 0"), + plugin_object(SCATTER, "Odd", &SPRAY.replace("Dot art", "Odd art")), + plugin_object(SCATTER, "Lost", &SPRAY.replace("Dot art", "Nowhere")), + plugin_object(ART_BRUSH, "Bare", "2 / / / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"), + plugin_object(BRISTLE, "Nib", MOP), + ] + .concat(); + let r = read_ok(&format!("{bad_art}{objects}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + assert_eq!(art(&r.doc).len(), 1, "the layer's art"); + let lib = vectorcraft_brush::library(&r.doc); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Nib"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (6)")), "{:?}", r.warnings); +} + +/// Files with brush objects and no brushes VectorCraft reads get an empty list, not the defaults. +#[test] +fn a_file_whose_brushes_are_all_left_out_has_none() { + let r = read_ok(&format!("{}{}", plugin_object(PATTERN_BRUSH, "Fence", FENCE), layer(""))); + assert!(vectorcraft_brush::library(&r.doc).is_empty()); +} + +/// A gradient's `Br` (a stop's ramp) isn't a brush: the gradient keeps its stops. +#[test] +fn a_gradients_br_is_not_a_brush() { + let gradient = + "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n0 0 0 0 1 1 1 2 1 6 50 0 Bs\n0 0 0 1 0 0 0 2 0.5 6 50 100 Bs\n0 Br\nBD\n%AI5_EndGradient\n"; + let art_ = format!("{}Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n10 0 0 10 100 50 Xm\nf\n0 BB\n", rect_path(0.0, 0.0, 20.0, 20.0)); + let r = read_ok(&format!("{gradient}{}", layer(&art_))); + assert!(!r.doc.unknown.contains_key(vectorcraft_brush::DOC_KEY)); + let Paint::Gradient(g) = fill(&art(&r.doc)[0]) else { panic!("a gradient: {:?}", r.warnings) }; + assert_eq!(g.gradient.stops.len(), 2); +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; /// Editing data in the legacy format (version 7 specification, chapter 2): `%AI5_FileFormat 2.0`, diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index a8bbd08373..f5f7693801 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -37,7 +37,9 @@ pub(in super::super) fn layered(ps: &[u8], visible: Imported, trust: bool, illus Err(why) => { let mut v = visible; if let Ok(data) = &data { + let have = v.document.patterns.len(); use_palette(data, &mut v.document); + use_brushes(data, &mut v.document, have, &mut v.warnings); use_variables(data, &mut v.document, &mut v.warnings); } if tree.is_empty() { @@ -97,8 +99,9 @@ fn layer_tree(nodes: &[Arc]) -> Vec> { /// notes, or a note saying why the layers weren't read when the editing data can't be decompressed /// or its layers can't be read. The flag returned is `true` when the document is the one read from /// the layers; else the document is `visible`, its pages moved by `place_pages` when the editing -/// data was decompressed but its layers can't be read, and its swatches and variables those of the -/// editing data's palette ([`use_palette`]) and variable library ([`use_variables`]) when it was +/// data was decompressed but its layers can't be read, and its swatches, brushes and variables those +/// of the editing data's palette ([`use_palette`]), brushes ([`use_brushes`]) and variable library +/// ([`use_variables`]) when it was /// decompressed. `outlined`: the PDF part's type was read as /// outlines (a file whose type shows then comes in as its PDF part). /// `trust`: layers that draw differently from the PDF part are used all the same, with a warning. @@ -117,15 +120,19 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl }; if !has_layers(&data) { let (mut visible, mut warnings) = (visible, warnings); + let have = visible.patterns.len(); use_palette(&data, &mut visible); + use_brushes(&data, &mut visible, have, &mut warnings); use_variables(&data, &mut visible, &mut warnings); return (visible, warnings, false); } // The PDF part, its pages placed and named as the editing data's artboards are, when the // layers can't be used (`why`). - let from_pdf_part = |mut visible: Document, warnings: Vec, why: &str| { + let from_pdf_part = |mut visible: Document, mut warnings: Vec, why: &str| { place_pages(&ai::artboards(&data), &mut visible, unit); + let have = visible.patterns.len(); use_palette(&data, &mut visible); + use_brushes(&data, &mut visible, have, &mut warnings); let mut all = unread(warnings, why); use_variables(&data, &mut visible, &mut all); (visible, all, false) @@ -161,8 +168,9 @@ fn use_variables(data: &[u8], doc: &mut Document, warnings: &mut Vec) { /// `doc` (a `.ai` read as its PDF part, in place of its layers) with the swatches and color groups /// of the palette of its editing data `data` in place of the default ones, as [`build`] gives a /// document read from the layers. The spot and pattern swatches of the PDF part's art that the -/// palette doesn't have follow the palette's swatches. The patterns that the editing data defines and -/// the PDF part lacks come in for the palette's pattern swatches, with the images they show. Left as +/// palette doesn't have follow the palette's swatches. The patterns that the editing data defines come +/// in for the palette's pattern swatches, with the images they show; one whose name a pattern of +/// the PDF part already has takes a free variant of it ([`ai::palette`]). Left as /// it is when the palette is empty. fn use_palette(data: &[u8], doc: &mut Document) { let Some(ai::PaletteSwatches { swatches, groups, patterns, images }) = ai::palette(data, &doc.patterns) else { return }; @@ -181,6 +189,29 @@ fn use_palette(data: &[u8], doc: &mut Document) { (doc.swatches, doc.swatch_groups) = (swatches.into(), groups.into()); } +/// `doc` (a file read as its page or PDF part, in place of its layers) with the brushes of its +/// editing data `data` in place of the default ones, as [`build`] gives a document read from the +/// layers, the patterns of the editing data their art paints with (named apart from the first +/// `have` patterns of `doc`, those of the page or PDF part, as [`use_palette`] names them, which +/// may have added some of them already), and the note for the brushes left out added to +/// `warnings`. Left as it is when the editing data has no brushes. +fn use_brushes(data: &[u8], doc: &mut Document, have: usize, warnings: &mut Vec) { + let page = doc.patterns.get(..have).unwrap_or(&doc.patterns); + let Some(ai::Brushes { brushes, patterns, images, note }) = ai::brushes(data, page) else { return }; + for (key, blob) in images { + doc.images.entry(key).or_insert(blob); + } + for mut p in patterns { + if doc.pattern(&p.name).is_some() { + continue; + } + p.art = p.art.iter().map(|n| Arc::new(doc.reid(n))).collect(); + doc.patterns.push(p); + } + vectorcraft_brush::store(doc, &brushes); + warnings.extend(note.filter(|n| !warnings.contains(n))); +} + /// The pages of `doc` (a `.ai` read as its PDF part: a page per artboard, in a row) named as /// `boards` (the artboards of its editing data, in art space) name them, and moved, with the art on /// each, to where they are, so the artboards keep their names and layout when the layers can't be diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dd18482662..e553712e92 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -1344,6 +1344,100 @@ fn an_ai_file_without_layers_keeps_the_patterns_of_its_palette() { assert!(keys.iter().all(|k| d.images.contains_key(k)), "{keys:?}"); } +/// A brush library (brush objects and their art, no layers) comes in as its PDF part with the +/// library's brushes in place of the default ones: Other Library lists them. +#[test] +fn an_ai_brush_library_without_layers_keeps_its_brushes() { + let order = "%AI8_BeginPluginObject\n(Adobe Brush Manager Order)\n(Adobe Brush Manager Order)\n\ + ( Adobe Scatter Brush Tool/ Spray/ Adobe Calli) -\n(graphic Brush Tool/ Nib/) .\n%AI8_EndPluginObject\n"; + let nib = "%AI8_BeginPluginObject\n(Adobe Calligraphic Brush Tool)\n(Nib)\n(1 2 6 40 60 -30 10 1 0 2 0) .\n%AI8_EndPluginObject\n"; + let spray = "%AI8_BeginPluginObject\n(Adobe Scatter Brush Tool)\n(Spray)\n(2 /Dot art/ 5 1 0 0 / 0 0.5 1.5 1 ) -\n\ + (1.2 2 0 -0.25 0.25 2 -45 30 1 1 0) .\n%AI8_EndPluginObject\n"; + // The art is filled with a pattern no swatch paints with: it comes in with the brush. + let dots = "%AI3_BeginPattern: (Dots)\n(Dots) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let dot = "%AI8_BeginBrushPattern\n(Dot art)\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 0 m\n4 0 L\n4 4 L\nf\n%AI8_EndBrushPattern\n"; + let library = + format!("%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 0 0\n%%BeginSetup\n{dots}{dot}{order}{nib}{spray}%%EndSetup\n%%PageTrailer\n%%Trailer\n"); + let (d, warnings, read) = crate::layered_ai(&private(&library), pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(!read, "{warnings:?}"); + let lib = vectorcraft_brush::library(&d); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Spray", "Nib"], "{warnings:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); + assert!(d.pattern("Dots").is_some_and(|p| !p.art.is_empty()), "the pattern the brush's art paints with"); +} + +/// A PDF part whose tiling has the name of a pattern its editing data defines (the PDF part names +/// its tilings `Pattern 1`, `Pattern 2` and so on): the editing data's pattern comes in under a free +/// variant of the name, and the palette's swatch and the brush's art paint with it, not with the +/// tiling. +#[test] +fn an_ai_file_without_layers_keeps_its_patterns_apart_from_the_pdf_parts_tilings() { + let dots = "%AI3_BeginPattern: (Pattern 1)\n(Pattern 1) 0 0 4 4\n%_0 0 0 1 k\n%_1 1 m\n%_3 1 L\n%_3 3 L\n%_1 3 L\n%_f\nE\n%AI3_EndPattern\n"; + let palette = "%AI5_BeginPalette\n0 0 Pb\n(Pattern 1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n(Dots)\nPc\nPB\n%AI5_EndPalette\n"; + let order = "%AI8_BeginPluginObject\n(Adobe Brush Manager Order)\n(Adobe Brush Manager Order)\n( Adobe Scatter Brush Tool/ Spray/) .\n%AI8_EndPluginObject\n"; + let spray = "%AI8_BeginPluginObject\n(Adobe Scatter Brush Tool)\n(Spray)\n(2 /Dot art/ 5 1 0 0 / 0 0.5 1.5 1 ) -\n\ + (1.2 2 0 -0.25 0.25 2 -45 30 1 1 0) .\n%AI8_EndPluginObject\n"; + let dot = "%AI8_BeginBrushPattern\n(Dot art)\n(Pattern 1) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n0 0 m\n4 0 L\n4 4 L\nf\n%AI8_EndBrushPattern\n"; + let part = || { + let mut part = pdf_part(10.0, 86.0); + let id = part.alloc_id(); + let square = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 9.0, 9.0)); + let tiling = std::sync::Arc::new(Node::path(id, square, vectorcraft_doc::Appearance::default())); + let tile = vectorcraft_geom::Rect::new(0.0, 0.0, 9.0, 9.0); + part.patterns.push(vectorcraft_doc::PatternDef { tile, ..vectorcraft_doc::PatternDef::new("Pattern 1", vec![tiling]) }); + part + }; + let width = |d: &Document, name: &str| d.pattern(name).map(|p| p.tile.width()); + let swatch_pattern = |d: &Document| match d.swatch("Dots").map(|s| &s.paint) { + Some(vectorcraft_color::Paint::Pattern { pattern, .. }) => Some(pattern.clone()), + _ => None, + }; + fn painted(n: &Node, out: &mut Vec) { + for p in vectorcraft_doc::swatches::node_paints(n) { + if let vectorcraft_color::Paint::Pattern { pattern, .. } = p { + out.push(pattern.clone()); + } + } + for c in n.children().into_iter().flatten() { + painted(c, out); + } + } + let brushed = |d: &Document| { + let mut out = vec![]; + for b in vectorcraft_brush::library(d) { + for a in b.art() { + painted(a, &mut out); + } + } + out + }; + + // The palette alone. + let art = native(&format!("{dots}{palette}")); + let (d, warnings, read) = crate::layered_ai(&private(&art), part(), vec![], false, true, 1.0); + assert!(!read, "{warnings:?}"); + assert_eq!(width(&d, "Pattern 1"), Some(9.0), "the PDF part's tiling stays"); + assert_eq!(swatch_pattern(&d).as_deref(), Some("Pattern 1 2"), "{warnings:?}"); + assert_eq!(width(&d, "Pattern 1 2"), Some(4.0)); + + // A brush library: the brush's art paints with the editing data's pattern. + let library = format!("%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 0 0\n%%BeginSetup\n{dots}{dot}{order}{spray}%%EndSetup\n%%PageTrailer\n%%Trailer\n"); + let (d, warnings, read) = crate::layered_ai(&private(&library), part(), vec![], false, true, 1.0); + assert!(!read, "{warnings:?}"); + assert_eq!(brushed(&d), ["Pattern 1 2"], "{warnings:?}"); + assert_eq!(width(&d, "Pattern 1"), Some(9.0)); + assert_eq!(width(&d, "Pattern 1 2"), Some(4.0)); + + // Both: the palette's swatch and the brush paint with the one pattern, added once. + let both = + format!("%!PS-Adobe-3.0 \n%%BoundingBox: 0 0 0 0\n%%BeginSetup\n{dots}{palette}{dot}{order}{spray}%%EndSetup\n%%PageTrailer\n%%Trailer\n"); + let (d, warnings, _) = crate::layered_ai(&private(&both), part(), vec![], false, true, 1.0); + assert_eq!(swatch_pattern(&d).as_deref(), Some("Pattern 1 2"), "{warnings:?}"); + assert_eq!(brushed(&d), ["Pattern 1 2"], "{warnings:?}"); + let names: Vec<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["Pattern 1", "Pattern 1 2"]); +} + /// A `.ai` that comes in as its PDF part, whose layers can't be used or that has none, gets the /// variables, data sets, active data set and lock of its editing data's variable library, and so /// does an EPS that comes in as its page. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index a69bd4f0d7..fd683d3cec 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4500,6 +4500,7 @@ axis Both И двете @msg it has {_1}, which VectorCraft doesn't read from it yet той съдържа {_1}, който VectorCraft все още не може да разчете @msg its objects are nested too deeply обектите му са вложени твърде дълбоко @msg its section ending with `%{end}` doesn't end разделът му, завършващ на `%{end}`, няма край +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) четките, които VectorCraft все още не може да прочете, бяха пропуснати от панела „Четки“ ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet обектите с множество запълвания или щрихове, ефекти или четки се появиха във вид на изрисувания си изглед ({_1}): тяхната поява все още не подлежи на редактиране @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it градиентът „{name}“ не е дефиниран във файла: заменен е с обикновен цвят @msg an image VectorCraft can't read was left out изображение, което VectorCraft не може да разчете, беше пропуснато diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 212e28f2bb..c785d37ddb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4899,6 +4899,7 @@ imageTrace Outline Obris @msg it has {_1}, which VectorCraft doesn't read from it yet sadrži {_1}, što VectorCraft još ne čita iz nje @msg its objects are nested too deeply njeni objekti su previše duboko ugniježđeni @msg its section ending with `%{end}` doesn't end njen odjeljak koji završava s `%{end}` ne završava +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) četkice koje VectorCraft još ne može pročitati izostavljene su iz panela Četkice ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objekti s više ispuna ili poteza, efekata ili četkica stigli su kao njihov iscrtani izgled ({_1}): njihov izgled se još ne može uređivati @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradijent „{name}” nije definisan u datoteci: umjesto njega koristi se obična boja @msg an image VectorCraft can't read was left out izostavljena je slika koju VectorCraft ne može pročitati diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 552b0b8ac1..5a591d27f3 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5351,6 +5351,7 @@ digits Malayalam Malaiàlam @msg object {id} is not a selected top-level object l’objecte {id} no és un objecte de nivell superior seleccionat @msg objects can't be nested more than 32 deep els objectes no es poden niar més de 32 nivells @msg objects inside a blend, envelope, repeat or Intertwine group can't be attached to a path els objectes dins d’una fusió, un embolcall, una repetició o un grup Intertwine no es poden adjuntar a un traçat +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) els pinzells que VectorCraft encara no pot llegir s'han deixat fora del tauler Pinzells ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet els objectes amb diversos farciments o traços, efectes o pinzells han arribat amb el seu aspecte dibuixat ({_1}): la seva aparença encara no és editable @msg Offset Path: select paths Desplaça el traçat: selecciona traçats @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) Desplaça el traçat: el desplaçament no deixa res dels traçats seleccionats (una retracció més gran que les formes) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index d96985198b..1472c0747a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4954,6 +4954,7 @@ imageTrace Outline Obrys @msg it has {_1}, which VectorCraft doesn't read from it yet obsahuje {_1}, což z něj VectorCraft zatím nečte @msg its objects are nested too deeply jeho objekty jsou vnořené příliš hluboko @msg its section ending with `%{end}` doesn't end jeho oddíl končící `%{end}` nemá konec +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) štětce, které VectorCraft zatím neumí načíst, byly vynechány z panelu Štětce ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objekty s více výplněmi nebo tahy, efekty či štětci byly načteny jako vykreslený vzhled ({_1}): jejich vzhled zatím nelze upravovat @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it přechod „{name}“ není v souboru definován: zastupuje ho plná barva @msg an image VectorCraft can't read was left out obrázek, který VectorCraft neumí přečíst, byl vynechán diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b050dbb63d..73256a62b6 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4587,6 +4587,7 @@ imageTrace Outline Kontur @msg it has {_1}, which VectorCraft doesn't read from it yet den har {_1}, hvilket VectorCraft endnu ikke læser fra den @msg its objects are nested too deeply dens objekter er indlejret for dybt @msg its section ending with `%{end}` doesn't end dens sektion, der ender med `%{end}`, ender ikke +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) pensler, som VectorCraft endnu ikke kan læse, blev udeladt af panelet Pensler ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objekter med flere fyld eller streger, effekter eller pensler kom ind, som de er tegnet ({_1}): deres udseende er endnu ikke redigerbart @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradienten »{name}« er ikke defineret i filen: der bruges en flad farve i stedet @msg an image VectorCraft can't read was left out et billede, som VectorCraft ikke kan læse, blev udeladt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index a26cc0c1af..c380e4a07f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4564,6 +4564,7 @@ theme Appearance Erscheinungsbild @msg it has {_1}, which VectorCraft doesn't read from it yet es enthält {_1}, was VectorCraft daraus noch nicht liest @msg its objects are nested too deeply seine Objekte sind zu tief verschachtelt @msg its section ending with `%{end}` doesn't end sein Abschnitt, der mit `%{end}` enden soll, endet nicht +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) Pinsel, die VectorCraft noch nicht lesen kann, wurden im Bedienfeld „Pinsel“ ausgelassen ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet Objekte mit mehreren Flächen oder Konturen, Effekten oder Pinseln wurden so übernommen, wie sie gezeichnet aussehen ({_1}): Ihr Aussehen ist noch nicht bearbeitbar @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it der Verlauf „{name}“ ist in der Datei nicht definiert: Eine einfache Farbe steht an seiner Stelle @msg an image VectorCraft can't read was left out ein Bild, das VectorCraft nicht lesen kann, wurde ausgelassen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 78bc64257b..c763a01f2b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4597,6 +4597,7 @@ digits Malayalam Μαλαγιάλαμ @msg it has {_1}, which VectorCraft doesn't read from it yet περιέχει {_1}, τα οποία το VectorCraft δεν μπορεί ακόμη να διαβάσει @msg its objects are nested too deeply τα αντικείμενά του έχουν υπερβολικά βαθιά ένθεση @msg its section ending with `%{end}` doesn't end η ενότητά του που τελειώνει σε `%{end}` δεν τερματίζεται +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) τα πινέλα που το VectorCraft δεν μπορεί ακόμη να διαβάσει παραλείφθηκαν από τον πίνακα Πινέλα ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet τα αντικείμενα με πολλαπλά γεμίσματα, περιγράμματα, εφέ ή πινέλα εισήχθησαν ως απεικονίσεις ({_1}): η εμφάνισή τους δεν είναι ακόμη επεξεργάσιμη @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it το ντεγκραντέ «{name}» δεν ορίζεται στο αρχείο: χρησιμοποιείται στη θέση του ένα συμπαγές χρώμα @msg an image VectorCraft can't read was left out παραλείφθηκε εικόνα που δεν μπορεί να διαβάσει το VectorCraft diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4c49048ae8..d71d23b18f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4648,6 +4648,7 @@ axis Both Ambos @msg it has {_1}, which VectorCraft doesn't read from it yet tienen {_1}, que VectorCraft aún no lee de ellos @msg its objects are nested too deeply sus objetos están anidados a demasiada profundidad @msg its section ending with `%{end}` doesn't end su sección que termina con `%{end}` no termina +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) los pinceles que VectorCraft aún no puede leer se omitieron del panel Pinceles ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet los objetos con varios rellenos o trazos, efectos o pinceles se importaron con su aspecto dibujado ({_1}): su aspecto aún no se puede editar @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it el degradado “{name}” no está definido en el archivo: lo sustituye un color sólido @msg an image VectorCraft can't read was left out se omitió una imagen que VectorCraft no puede leer diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 363c388db4..102ef7c3bf 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4856,6 +4856,7 @@ imageTrace Outline Ääriviiva @msg it has {_1}, which VectorCraft doesn't read from it yet siinä on {_1}, jota VectorCraft ei vielä lue siitä @msg its objects are nested too deeply sen objektit ovat liian syvällä sisäkkäin @msg its section ending with `%{end}` doesn't end sen `%{end}`-merkintään päättyvä osio ei pääty +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) siveltimet, joita VectorCraft ei vielä osaa lukea, jätettiin pois Siveltimet-paneelista ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objektit, joilla on useita täyttöjä tai viivoja, tehosteita tai siveltimiä, tuotiin piirretyn näköisinä ({_1}): niiden ulkoasua ei voi vielä muokata @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it liukuväriä “{name}” ei ole määritetty tiedostossa: sen tilalla on tasaväri @msg an image VectorCraft can't read was left out kuva, jota VectorCraft ei voi lukea, jätettiin pois diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 2fc442dab5..b1ddc5f4fd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4636,6 +4636,7 @@ axis Both Les deux @msg it has {_1}, which VectorCraft doesn't read from it yet elles contiennent {_1}, que VectorCraft n’y lit pas encore @msg its objects are nested too deeply leurs objets sont imbriqués trop profondément @msg its section ending with `%{end}` doesn't end leur section qui se termine par `%{end}` ne se termine pas +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) les formes que VectorCraft ne sait pas encore lire ont été omises du panneau Formes ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet les objets à plusieurs fonds ou contours, effets ou formes ont été importés tels qu’ils sont dessinés ({_1}) : leur aspect n’est pas encore modifiable @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it le dégradé « {name} » n’est pas défini dans le fichier : une couleur unie le remplace @msg an image VectorCraft can't read was left out une image que VectorCraft ne peut pas lire a été ignorée diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f5be6e413b..7da6af288c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5035,6 +5035,7 @@ imageTrace Outline Körvonal @msg object {0} cannot have children ennek az objektumnak nem lehetnek gyermekei: {0} @msg object {id} is not a path az objektum nem útvonal: {id} @msg object {id} is not a selected top-level object az objektum nem kijelölt legfelső szintű objektum: {id} +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) a VectorCraft által még nem olvasható ecsetek kimaradtak az Ecsetek panelről ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet a több kitöltésű vagy körvonalú, effektusos vagy ecsetes objektumok a megrajzolt kinézetükkel kerültek be ({_1}): a megjelenésük még nem szerkeszthető @msg Offset Path: select paths Útvonal eltolása: jelölj ki útvonalakat @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) Útvonal eltolása: az eltolás után semmi sem marad a kijelölt útvonalakból (a befelé eltolás nagyobb az alakzatoknál) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0c4be65a60..4e32a3d8aa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4587,6 +4587,7 @@ imageTrace Outline Kontur @msg it has {_1}, which VectorCraft doesn't read from it yet memiliki {_1}, yang belum dibaca VectorCraft dari berkas tersebut @msg its objects are nested too deeply objeknya bersarang terlalu dalam @msg its section ending with `%{end}` doesn't end bagian yang berakhir dengan `%{end}` tidak berakhir +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) kuas yang belum dapat dibaca VectorCraft tidak dimasukkan ke panel Kuas ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objek dengan beberapa isian atau goresan, efek, atau kuas masuk sebagai tampilan gambarnya ({_1}): penampilannya belum dapat diedit @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradien “{name}” tidak didefinisikan dalam berkas: warna polos dipakai sebagai pengganti @msg an image VectorCraft can't read was left out gambar yang tidak dapat dibaca VectorCraft tidak disertakan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 12da089477..56235fef13 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4690,6 +4690,7 @@ axis Both Entrambi @msg it has {_1}, which VectorCraft doesn't read from it yet contengono {_1}, che VectorCraft non vi legge ancora @msg its objects are nested too deeply i loro oggetti sono annidati troppo in profondità @msg its section ending with `%{end}` doesn't end la loro sezione che termina con `%{end}` non termina +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) i pennelli che VectorCraft non sa ancora leggere sono stati esclusi dal pannello Pennelli ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet gli oggetti con più riempimenti o tratti, effetti o pennelli sono stati importati come appaiono disegnati ({_1}): il loro aspetto non è ancora modificabile @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it la sfumatura “{name}” non è definita nel file: la sostituisce un colore pieno @msg an image VectorCraft can't read was left out un'immagine che VectorCraft non può leggere è stata omessa diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f68f17fc55..cc48dc8bb1 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4386,6 +4386,7 @@ swatch Bright Violet ビビッドバイオレット @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel リンク画像は、元のファイルが見つかるまで、ファイルに保存された低解像度のプレビューで表示されます:リンクパネルで再リンクしてください @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 表示に使われるフォントの 1 行に対して低すぎるフレーム内のエリア内文字は、フレームを高くしました ({_1}): そうしないと文字が表示されません @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it グラデーション「{name}」はファイル内で定義されていません: 代わりに単色を使用しています +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft がまだ読み込めないブラシ {_1} 個はブラシパネルに追加されませんでした @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet 塗りや線が複数ある、または効果やブラシを適用したオブジェクト {_1} 個は見た目のまま読み込まれました: アピアランスはまだ編集できません @msg patterns nested too deeply are filled with mid-grey 入れ子が深すぎるパターンは中間のグレーで塗りつぶされています @msg shadings of an unknown type were left out 種類が不明なシェーディングは除外されました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f329a90f86..02470e035f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4385,6 +4385,7 @@ font-technology Variable ცვლადი @msg it has {_1}, which VectorCraft doesn't read from it yet მას აქვს {_1}, რასაც VectorCraft მისგან ჯერ ვერ კითხულობს @msg its objects are nested too deeply მისი ობიექტები ზედმეტად ღრმადაა ჩადგმული @msg its section ending with `%{end}` doesn't end მისი სექცია, რომელიც `%{end}`-ით მთავრდება, არ სრულდება +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) ფუნჯები, რომლებსაც VectorCraft ჯერ ვერ კითხულობს, ფუნჯების პანელში არ დაემატა ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet რამდენიმე შევსების ან კონტურის, ეფექტის ან ფუნჯის მქონე ობიექტები შემოვიდა დახატული სახით ({_1}): მათი იერსახე ჯერ არ რედაქტირდება @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it გრადიენტი „{name}“ ფაილში განსაზღვრული არ არის: მის ნაცვლად ერთგვაროვანი ფერია @msg an image VectorCraft can't read was left out გამოსახულება, რომელსაც VectorCraft ვერ კითხულობს, გამოტოვებულია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index abdcb7cf63..fc30c96d3a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4313,6 +4313,7 @@ theme Appearance 외관 @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 연결된 그림은 해당 파일을 찾을 때까지 파일에 저장된 저해상도 미리 보기로 표시됩니다: 링크 패널에서 다시 연결하세요 @msg area type in frames too short for a line of the font it shows in got taller frames ({_1}): their type wouldn't show otherwise 표시되는 글꼴의 한 줄보다 낮은 프레임의 영역 문자는 프레임을 더 높였습니다({_1}). 그렇지 않으면 문자가 표시되지 않습니다 @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it 그레이디언트 “{name}”이(가) 파일에 정의되어 있지 않아 단색으로 대체했습니다 +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft에서 아직 읽을 수 없는 브러시는 브러시 패널에서 제외되었습니다({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet 칠이나 선이 여러 개인 개체, 효과, 브러시가 있는 개체는 그려진 모양({_1})으로 가져왔습니다: 모양새는 아직 편집할 수 없습니다 @msg patterns nested too deeply are filled with mid-grey 너무 깊게 중첩된 패턴은 중간 회색으로 채웁니다 @msg shadings of an unknown type were left out 알 수 없는 종류의 셰이딩은 제외했습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index fb2ebeb99f..cd7a559d27 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4599,6 +4599,7 @@ imageTrace Outline Contour @msg it has {_1}, which VectorCraft doesn't read from it yet het bevat {_1}, wat VectorCraft er nog niet uit leest @msg its objects are nested too deeply de objecten ervan zijn te diep genest @msg its section ending with `%{end}` doesn't end zijn sectie die op `%{end}` eindigt, eindigt niet +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) penselen die VectorCraft nog niet kan lezen, zijn weggelaten uit het deelvenster Penselen ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objecten met meerdere vullingen of lijnen, effecten of penselen zijn als hun getekende uiterlijk binnengekomen ({_1}): hun vormgeving is nog niet bewerkbaar @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it verloop „{name}” is niet gedefinieerd in het bestand: er is een effen kleur voor gebruikt @msg an image VectorCraft can't read was left out een afbeelding die VectorCraft niet kan lezen, is weggelaten diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index f329a539a8..d61832b344 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4780,6 +4780,7 @@ imageTrace Outline Kontur @msg it has {_1}, which VectorCraft doesn't read from it yet zawiera {_1}, czego VectorCraft jeszcze z niego nie odczytuje @msg its objects are nested too deeply jego obiekty są zagnieżdżone zbyt głęboko @msg its section ending with `%{end}` doesn't end jego sekcja kończąca się na `%{end}` nie ma końca +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) pędzle, których VectorCraft jeszcze nie odczytuje, pominięto w panelu Pędzle ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet obiekty z kilkoma wypełnieniami lub obrysami, efektami albo pędzlami wczytano jako ich narysowany wygląd ({_1}): ich wyglądu nie można jeszcze edytować @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradient „{name}” nie jest zdefiniowany w pliku: zastąpiono go jednolitym kolorem @msg an image VectorCraft can't read was left out pominięto obraz, którego VectorCraft nie potrafi odczytać diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 726c16d448..31b2c5b933 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4230,6 +4230,7 @@ axis Both Ambos @msg it has {_1}, which VectorCraft doesn't read from it yet tem {_1}, que o VectorCraft ainda não lê desse arquivo @msg its objects are nested too deeply seus objetos estão aninhados com profundidade excessiva @msg its section ending with `%{end}` doesn't end sua seção que termina com `%{end}` não termina +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) os pincéis que o VectorCraft ainda não consegue ler ficaram fora do painel Pincéis ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objetos com vários preenchimentos ou traços, efeitos ou pincéis entraram com a aparência desenhada ({_1}): sua aparência ainda não é editável @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it o gradiente “{name}” não está definido no arquivo: uma cor sólida o substitui @msg an image VectorCraft can't read was left out uma imagem que o VectorCraft não consegue ler foi omitida diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ba7a946899..7a77d759ba 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4685,6 +4685,7 @@ axis Both Оба @msg it has {_1}, which VectorCraft doesn't read from it yet в них есть {_1}, которые VectorCraft пока не читает @msg its objects are nested too deeply объекты в них вложены слишком глубоко @msg its section ending with `%{end}` doesn't end раздел, заканчивающийся на `%{end}`, не заканчивается +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) кисти, которые VectorCraft пока не умеет читать, не добавлены в панель «Кисти» ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet объекты с несколькими заливками или обводками, эффектами или кистями импортированы в нарисованном виде ({_1}): их оформление пока нельзя редактировать @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it градиент «{name}» не определён в файле: вместо него используется сплошной цвет @msg an image VectorCraft can't read was left out изображение, которое VectorCraft не может прочитать, пропущено diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 81942ced57..85e2cbb645 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4547,6 +4547,7 @@ axis Both Båda @msg it has {_1}, which VectorCraft doesn't read from it yet den innehåller {_1}, som VectorCraft inte kan läsa från den än @msg its objects are nested too deeply dess objekt är för djupt kapslade @msg its section ending with `%{end}` doesn't end dess avsnitt som slutar med `%{end}` avslutas aldrig +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) penslar som VectorCraft ännu inte kan läsa utelämnades från panelen Penslar ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet objekt med flera fyllningar eller konturer, effekter eller penslar importerades som sitt ritade utseende ({_1}): deras utseende går inte att redigera än @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradienten ”{name}” är inte definierad i filen: en enfärgad fyllning används i stället @msg an image VectorCraft can't read was left out en bild som VectorCraft inte kan läsa utelämnades diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index af1a87f89f..1e35746785 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4384,6 +4384,7 @@ axis Both Her İkisi @msg it has {_1}, which VectorCraft doesn't read from it yet VectorCraft'ın henüz okumadığı {_1} var @msg its objects are nested too deeply nesneleri çok derin bir şekilde iç içe geçmiş @msg its section ending with `%{end}` doesn't end `%{end}` ile biten bölümü bitmiyor +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft'ın henüz okuyamadığı fırçalar Fırçalar panelinin dışında bırakıldı ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet çeşitli dolgulara veya konturlara, efektlere veya fırçalara sahip nesneler çizilmiş görünümleri olarak geldi ({_1}): görünümleri henüz düzenlenemez @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it “{name}” degradesi dosyada tanımlı değil: onun yerine düz bir renk geliyor @msg an image VectorCraft can't read was left out VectorCraft'ın okuyamadığı bir resim dışarıda bırakıldı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 07e5d8db94..f0ba143cca 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4674,6 +4674,7 @@ axis Both Обидві @msg it has {_1}, which VectorCraft doesn't read from it yet у них є {_1}, які VectorCraft поки не читає @msg its objects are nested too deeply об’єкти в них вкладені надто глибоко @msg its section ending with `%{end}` doesn't end розділ, що закінчується на `%{end}`, не закінчується +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) пензлі, які VectorCraft поки не вміє читати, не додано до панелі «Пензлі» ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet об’єкти з кількома заливками або обведеннями, ефектами або пензлями імпортовані в намальованому вигляді ({_1}): їх оформлення поки що не можна редагувати @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it градієнт «{name}» не визначено у файлі: замість нього використовується суцільний колір @msg an image VectorCraft can't read was left out зображення, яке VectorCraft не може прочитати, пропущено diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e0844fb251..436fe20d0e 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4689,6 +4689,7 @@ theme Appearance Giao diện @msg object {0} cannot have children đối tượng {0} không thể có phần tử con @msg object {id} is not a path đối tượng {id} không phải là đường dẫn @msg object {id} is not a selected top-level object đối tượng {id} không phải là đối tượng cấp cao nhất đã chọn +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) các cọ mà VectorCraft chưa đọc được đã bị bỏ khỏi bảng Cọ ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet đối tượng có nhiều tô hoặc nét, hiệu ứng hoặc cọ đã vào dưới dạng bề ngoài ({_1}): diện mạo chưa thể chỉnh sửa @msg Offset Path: select paths Đường dẫn độ lệch: hãy chọn đường dẫn @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) Đường dẫn độ lệch: độ lệch không để lại gì từ các đường dẫn đã chọn (độ lệch vào trong lớn hơn hình) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 1ea4703928..2131de9822 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4108,6 +4108,7 @@ imageTrace Outline 轮廓 @msg graphs come in as plain art, without their data or settings 图表作为普通图稿导入,不保留其数据和设置 @msg an image whose data is cut short was left out 已略去数据不完整的图像 @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it 文件中未定义渐变“{name}”:已改用纯色代替 +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft 尚无法读取的画笔未加入“画笔”面板 ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet 带有多个填色或描边、效果或画笔的对象已按其绘制外观导入 ({_1}):其外观尚不可编辑 @msg patterns nested too deeply are filled with mid-grey 嵌套过深的图案以中灰色填充 @msg shadings of an unknown type were left out 已略去未知类型的着色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 8d7d0ff587..d2ce0501e5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2003,6 +2003,7 @@ file-filter Templates 範本 @msg graphs come in as plain art, without their data or settings 圖表以一般圖稿匯入,不保留其資料與設定 @msg an image whose data is cut short was left out 已略過資料不完整的影像 @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it 檔案中未定義漸層「{name}」:已改用單色替代 +@msg brushes VectorCraft can't read yet were left out of the Brushes panel ({_1}) VectorCraft 尚無法讀取的筆刷未加入「筆刷」面板 ({_1}) @msg objects with several fills or strokes, effects or brushes came in as their drawn look ({_1}): their appearance isn't editable yet 具有多個填色或筆畫、效果或筆刷的物件已依其繪製外觀匯入 ({_1}):其外觀目前尚無法編輯 @msg patterns nested too deeply are filled with mid-grey 巢狀層級過深的圖樣以中灰色填滿 @msg shadings of an unknown type were left out 已略過類型未知的著色 diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 7a90a0d53c..65e6de0bf8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -118,7 +118,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 6d10c3994a..200dc5c634 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1150,6 +1150,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai` or PDF whose editing data holds a readable variable library opens with its variable definitions, data-set rows, text, visibility and linked-file values, active row and lock in the Variables panel, whether its layers are read or it comes in as its PDF part; graph values and malformed entries are skipped with a note, and objects aren't bound yet (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data keeps each artboard's center mark, cross hairs, video safe areas and video ruler pixel aspect ratio, and the file's Document Raster Effects Settings; the author comes from the header's `%%For` (the editing data's, else an EPS's own) when the file's File Info gives none, the header's custom colors that no swatch has come in as spot swatches, a named color the file defines takes the place of a default swatch of that name when the file has no palette, and an older file's `%%TemplateBox` places its artboard. A value of another type or out of range keeps its default (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` opened from its editing data opens its Objects on Path groups live, with their path, their objects in order along it, Pivot and Rotate, and their art where the file draws it; a group whose spacing has been dragged, or with options an Objects on Path group doesn't hold, opens as a plain group (`crates/eps/src/import/ai/tests.rs`). + A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art. A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. Pattern brushes and brushes that can't be read are left out with a note; brushed paths still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A PDF page whose `UserUnit` (PDF 1.6) is above 1 opens at its size in points, its numbers times the `UserUnit` (one above 75,000 counts as 75,000), and `document.pdfInfo` gives its size and boxes in points too. A `.ai` whose editing data has its artboards in the units of such a page opens from that data at the page's size, with its layers, and when the layers can't be read its pages still take the artboard layout of the data, scaled the same way (part of #1482). When the PDF content of a `.ai` has a page for each artboard, the layers are compared with every page on its artboard (until the pages compared take 8,388,608 pixels at the comparison's scale, about 67 letter-size pages, or number 128): art that only the layers or only a later page draws is handled as art that differs on the first page is, and a text object that a later page doesn't draw is left out unless its layer doesn't print (`crates/eps/src/import/tests_native.rs`). From 1e3553843d4deb3a4d9122eb2f7a19544b8f3328 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 4 Nov 2026 15:48:59 +0700 Subject: [PATCH 010/482] Single instance: the stale-endpoint test connects to no freed port The test bound a port, freed it and then connected to it as a gone app. Tests run in parallel, so another test's listener could take that port meanwhile and accept this connection in place of its own client's, whose connection was then reset when the listener closed: the cause of the intermittent tcp_connection_is_closed_after_junk failures on Windows. The gone app is now a listener that closes without a greeting. --- apps/vectorcraft/src/single_instance.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/single_instance.rs b/apps/vectorcraft/src/single_instance.rs index b8df2bb5a1..f7026131c9 100644 --- a/apps/vectorcraft/src/single_instance.rs +++ b/apps/vectorcraft/src/single_instance.rs @@ -329,10 +329,15 @@ mod tests { #[test] fn a_stale_endpoint_file_is_ignored_and_replaced() { let (path, dir, file) = folder("stale"); - // No listener on the recorded port any more. - let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap().local_addr().unwrap().port(); + // The recorded app is gone: whatever holds the port closes without a greeting. (A freed + // port can be taken by another test's listener meanwhile, which would then accept this + // connection in place of its own client's.) + let gone = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); + let port = gone.local_addr().unwrap().port(); write_endpoint(&path, &json!({ "port": port, "token": "t", "hello": "h" })).unwrap(); + let closed = std::thread::spawn(move || drop(gone.accept())); assert!(forward(&path, std::slice::from_ref(&file)).is_err()); + closed.join().unwrap(); // A listener that doesn't know the greeting gets neither the token nor the paths. let impostor = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); let port = impostor.local_addr().unwrap().port(); From c82a1eb0e82e4ef77c71e0b707acac9ccc8076c6 Mon Sep 17 00:00:00 2001 From: byoungyoon Date: Wed, 4 Nov 2026 17:53:54 +0900 Subject: [PATCH 011/482] Fix #5555: Cmd+V pastes once on the web eframe's web runner reports a Cmd+V press both as the key press and, with the clipboard's text, as a Paste event; the app pasted on each (egui's window integration sends only the Paste). The web shell now drops the paste key's press when a Paste is in the same frame's input; its release stays for PasteChord, and a Cmd+V with no text on the clipboard keeps its press. Co-Authored-By: Claude Opus 5.5 --- apps/vectorcraft-web/src/keys.rs | 40 ++++++++++++++++++++++++++++++++ apps/vectorcraft-web/src/web.rs | 2 ++ 2 files changed, 42 insertions(+) diff --git a/apps/vectorcraft-web/src/keys.rs b/apps/vectorcraft-web/src/keys.rs index 8cb27096b4..e2f3ea0b48 100644 --- a/apps/vectorcraft-web/src/keys.rs +++ b/apps/vectorcraft-web/src/keys.rs @@ -27,6 +27,19 @@ pub(crate) fn kept_from_browser(key: &str, code: &str, modifiers: Modifiers, alt vectorcraft_ui_egui::shortcuts::runs_a_shortcut(key, code, modifiers) } +/// Leave a paste to its Paste event (#5555). eframe's web runner reports a Cmd+V press both as the +/// key press and, with the clipboard's text, as a Paste event (the browser's `paste` comes in the +/// same task as the `keydown`, so both are in one frame's input); the app pastes on each, as egui's +/// window integration sends only the Paste. With a Paste in `events`, the paste key's press is +/// dropped; its release stays, so the paste chord is still followed (`PasteChord`). A Cmd+V without +/// a Paste (a clipboard with no text) keeps its press. +pub(crate) fn drop_paste_key_presses(events: &mut Vec) { + if !events.iter().any(|e| matches!(e, egui::Event::Paste(_))) { + return; + } + events.retain(|e| !matches!(e, egui::Event::Key { key: Key::V, pressed: true, modifiers, .. } if modifiers.command)); +} + /// The modifiers of a key event as eframe reports them to egui (its `modifiers_from_kb_event`). #[cfg(target_arch = "wasm32")] fn modifiers(e: &web_sys::KeyboardEvent) -> Modifiers { @@ -115,4 +128,31 @@ mod tests { assert!(!kept_from_browser("ż", "KeyZ", ctrl_alt, true)); assert!(!kept_from_browser("}", "Digit0", ctrl_alt, true)); } + + fn key(key: Key, pressed: bool, modifiers: Modifiers) -> egui::Event { + egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers } + } + + #[test] + fn a_paste_chord_pastes_once() { + // Cmd+V and Cmd+Shift+V (Paste in Place): the press goes, the Paste and the release stay. + for mods in [cmd(), cmd() | Modifiers::SHIFT] { + let mut events = vec![key(Key::V, true, mods), egui::Event::Paste("".into()), key(Key::V, false, mods)]; + drop_paste_key_presses(&mut events); + assert_eq!(events, vec![egui::Event::Paste("".into()), key(Key::V, false, mods)], "{mods:?}"); + } + } + + #[test] + fn keys_without_a_paste_stay() { + // No text on the clipboard: no Paste event, so the press is the paste chord's only report. + let mut events = vec![key(Key::V, true, cmd()), key(Key::V, false, cmd())]; + drop_paste_key_presses(&mut events); + assert_eq!(events.len(), 2); + // Typing V, and other chords, beside a paste. + let typed = vec![key(Key::V, true, Modifiers::NONE), key(Key::C, true, cmd()), egui::Event::Paste("a".into())]; + let mut events = typed.clone(); + drop_paste_key_presses(&mut events); + assert_eq!(events, typed); + } } diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 859d41ef79..75eb7b3082 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -378,6 +378,8 @@ impl eframe::App for WebShell { /// shared input hook before egui runs. fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { raw.events.extend(self.host.pointers.borrow_mut().take()); + // A Cmd+V comes as its key and as a Paste: one paste (#5555). + crate::keys::drop_paste_key_presses(&mut raw.events); if let Some(app) = &mut self.app { app.raw_input_hook(ctx, raw); } From a7acf43cb1317f1cea1e8b0a0c5ab3b02ef1ea16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 16:16:02 +0700 Subject: [PATCH 012/482] .ai import: objects come in bound to their variables Squashed from #5481 onto main. --- .../engine/src/cmd/fileio/tests_aiimport.rs | 39 ++-- crates/engine/tests/import_fuzz.rs | 36 ++++ crates/eps/src/import/ai.rs | 4 +- crates/eps/src/import/ai/read.rs | 36 +++- crates/eps/src/import/ai/read/document.rs | 108 +++++++++-- crates/eps/src/import/ai/tests.rs | 97 ++++++++++ crates/eps/src/import/native.rs | 2 +- crates/eps/src/import/native/build.rs | 171 +++++++++++++++++- crates/eps/src/import/native/layers.rs | 4 +- crates/eps/src/import/native/slots.rs | 59 +++++- crates/eps/src/import/tests_native.rs | 70 +++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 39 files changed, 617 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 66b6d01dff..16049850c0 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -675,21 +675,25 @@ fn what_the_reader_doesnt_read_opens_as_before_with_a_warning() { /// A `.ai` whose document data has a variable library opens with its variables, data sets, active /// data set and lock, whether its layers are read or it comes in as its PDF part: `variable.list` /// and `dataset.list` report them. A variable of unknown kind can't be bound. What of the library -/// can't be read is noted. +/// can't be read is noted. With its layers read, the object a variable is bound to comes in bound, +/// and selecting a data set changes it; the bindings to objects the file doesn't have are noted. #[test] fn an_ai_file_opens_its_variable_library() { let library = ai::variable_library_data(&ai::sample_variable_sets("variableAndTypes", &[])); - let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n", ai::rect(10.0, 50.0, 40.0, 90.0)); + let square = format!("0 1 1 0 1 0 0 Xa\n{}f\n{}", ai::rect(10.0, 50.0, 40.0, 90.0), ai::named("path_x5F_1")); let notes = |r: &Value| { r["warnings"].as_array().map_or(vec![], |w| w.iter().filter(|w| w.as_str().unwrap().contains("variable")).cloned().collect::>()) }; - let check = |s: &mut Session| { + let skipped = |n: usize| { + json!(format!("the file's variable bindings weren't all read (bindings skipped: {n}): those objects aren't bound to their variables")) + }; + let check = |s: &mut Session, bound: usize| { let r = s.execute("variable.list", &json!({})).unwrap(); assert_eq!( r, json!({"variables": [ {"name": "v_text", "kind": "text", "bindings": 0}, - {"name": "v_visible", "kind": "visibility", "bindings": 0}, + {"name": "v_visible", "kind": "visibility", "bindings": bound}, {"name": "v_file", "kind": "image", "bindings": 0}, {"name": "v_graph", "kind": "graph", "bindings": 0}, {"name": "v_unbound", "kind": "unknown", "bindings": 0}, @@ -709,23 +713,34 @@ fn an_ai_file_opens_its_variable_library() { let file = ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"); let r = open(&mut s, "variables.ai", &file, json!({})).unwrap(); assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); - assert!(notes(&r).is_empty(), "{r}"); - check(&mut s); - let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; - let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id]})).unwrap_err(); + // The library's text and image variables are bound to objects the file doesn't have. + assert_eq!(notes(&r), [skipped(2)], "{r}"); + check(&mut s, 1); + let id = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id; + assert_eq!(s.doc().unwrap().doc.variables.objects_of("v_visible"), [id]); + s.execute("dataset.select", &json!({"name": "ds_two"})).unwrap(); + assert!(!s.doc().unwrap().doc.node(id).unwrap().visible, "ds_two hides the square"); + s.execute("dataset.select", &json!({"name": "ds_one"})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().visible, "ds_one shows it"); + let e = s.execute("variable.bind", &json!({"variable": "v_unbound", "ids": [id.0]})).unwrap_err(); assert!(e.to_string().contains("a variable of unknown kind can't be bound to objects"), "{e}"); - // Its layers can't be read (a symbol): it comes in as its PDF part, with the library. + // Its layers can't be read (a symbol): it comes in as its PDF part, with the library and none + // of its bindings. let symbols = ai::editing_data(200.0, 100.0, &format!("{library}{}", ai::layer("Art", "/SymbolInstance :\n(Dot) /SymbolRef ,\n;\n"))); let r = open(&mut s, "symbols.ai", &ai::ai(&compressed(symbols.as_bytes()), ai::page_pdf()), json!({})).unwrap(); assert!(r["warnings"].to_string().contains("PDF part"), "{r}"); - assert!(notes(&r).is_empty(), "{r}"); - check(&mut s); + assert_eq!(notes(&r), [skipped(3)], "{r}"); + check(&mut s, 0); // A graph value isn't read: the note says how many entries were left out. let graph = ai::xml_element("v_graph", &[], &[ai::xml_text(ai::XmlValue::Str("a,b"))]); let partly = ai::variable_library_data(&ai::sample_variable_sets("none", &[graph])); let layered = ai::editing_data(200.0, 100.0, &format!("{partly}{}", ai::layer("Art", &square))); let r = open(&mut s, "graph.ai", &ai::ai(&compressed(layered.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap(); - assert_eq!(notes(&r), [json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest")], "{r}"); + assert_eq!( + notes(&r), + [json!("the file's variable library was partly read (entries skipped: 1): the Variables panel lists the rest"), skipped(2)], + "{r}" + ); // Without a library, no note and no variables. let plain = ai::editing_data(200.0, 100.0, &ai::layer("Art", &square)); let r = open(&mut s, "plain.ai", &ai::ai(&compressed(plain.as_bytes()), "1 0 0 rg 10 50 30 40 re f"), json!({})).unwrap(); diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 2e7d90aa61..4d1a328fda 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -3354,6 +3354,42 @@ proptest! { survive("hostile .ai variable library values", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?; } + /// A `.ai` whose variable library binds objects by XML ids that repeat, name nothing, are empty + /// or are shared by several objects (a group and its path), with traits of every kind, then is + /// damaged: every object bound is one of the opened document's. + #[test] + fn ai_variable_bindings_never_panic( + cut in 0usize..20_000, + edits in prop::collection::vec((0usize..20_000, prop::sample::select(vec!['0', '1', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'Z', 'u', 'U'])), 0..12), + refs in prop::collection::vec((0usize..5, 0usize..5), 0..40), + art in prop::collection::vec(0usize..5, 0..12), + ) { + use vectorcraft_testkit::ai::{self, XmlValue}; + let names = ["a", "b", "a_x5F_1", "", "missing"]; + let traits = ["textcontent", "visibility", "fileref", "graphdata", "other"]; + let declared: Vec = refs + .iter() + .map(|&(t, n)| { + let uid = format!("/XMLUIDREF : ({}) ;", names[n]); + let attributes = [("trait", XmlValue::Str(traits[t])), ("varName", XmlValue::Unicode(traits[t])), ("docRef", XmlValue::Raw(&uid))]; + ai::xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }) + .collect(); + let set = ai::xml_element("variableSet", &[], &[ai::xml_element("variables", &[], &declared)]); + let library = ai::variable_library_data(&ai::xml_element("variableSets", &[], &[set])); + let art: String = art.iter().map(|&n| format!("u\n0 g\n10 10 m\n20 20 L\nS\n{}U\n{}", ai::named(names[n]), ai::named(names[(n + 1) % 5]))).collect(); + let data = ai::editing_data(100.0, 100.0, &format!("{library}{}", ai::layer("L", &art))); + let text = mutate_text(&data, cut, &edits); + let private = [b"%AI24_ZStandard_Data".as_slice(), &zstd(&text)].concat(); + let mut bound = true; + survive("hostile .ai variable bindings", || { + let d = vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0; + bound = d.variables.bindings.keys().all(|id| d.node(*id).is_some()); + Some(d) + })?; + prop_assert!(bound, "a binding names an object the document doesn't have"); + } + /// A `.ai` whose Objects on Path record and group are damaged or hostile. #[test] fn ai_objects_on_path_never_panics(cut in 0usize..4_000, edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '1', '9', '-', '.', 'e', ' ', '\n', '(', ')', '/', ':', ';', ',', '%', '_', 'u', 'U'])), 0..12)) { diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 75a9debf2b..e413f6ec8e 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -36,7 +36,9 @@ use crate::ps; pub(crate) use envelope::DRAWN as ENVELOPE_DRAWN; pub(crate) use frames::text_frames; -pub use read::{Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, brushes, palette, read, read_beside, variables}; +pub use read::{ + BindingRef, Brushes, IMAGE_TOO_LARGE, PaletteSwatches, Structure, artboards, bindings_note, brushes, palette, read, read_beside, variables, +}; pub(crate) use read::{join_and, slot_frame, slot_of}; pub(crate) use read::is_look_slot; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 885cc6a7c2..6435c2dc69 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -117,7 +117,7 @@ mod types; pub(crate) use art::join_and; use art::preview_png; -pub use document::{Brushes, PaletteSwatches, VariableRead, artboards, brushes, palette, variables}; +pub use document::{BindingRef, Brushes, PaletteSwatches, VariableRead, artboards, bindings_note, brushes, palette, variables}; pub(crate) use document::{slot_frame, slot_of}; pub use types::IMAGE_TOO_LARGE; use types::{BLEND_BUDGET, FLIP, Frame, GState, Graph, Kind, PatternHead, PendingEnvelope, Place, Raster}; @@ -164,9 +164,37 @@ pub struct Structure { pub styles_read: bool, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, + /// The objects by their XML id (`AI10_ArtUID`), a text object by its slot's id: `None` for an + /// id two objects have. + pub xml_ids: HashMap>, + /// The objects the variable library binds to its variables, by their XML ids: the importer + /// binds those it keeps. + pub bindings: Vec, + /// How many objects the library binds that aren't in `bindings` ([`VariableRead::bindings_skipped`]). + pub bindings_skipped: usize, pub warnings: Vec, } +/// The most XML ids of objects ([`Structure::xml_ids`]) kept. +const MAX_XML_IDS: usize = 1_000_000; + +/// The most bytes of XML ids ([`Structure::xml_ids`]) kept, all ids together. +pub(super) const MAX_XML_ID_BYTES: usize = 16 << 20; + +/// Record that the object `id` has the XML id `uid` in `xml_ids`, whose ids take `bytes` bytes. Two +/// objects with one id are neither of them that id's. A new id is left out when `xml_ids` holds +/// [`MAX_XML_IDS`] ids or its bytes would pass [`MAX_XML_ID_BYTES`]. +pub(super) fn remember_xml_id(xml_ids: &mut HashMap>, bytes: &mut usize, uid: String, id: NodeId) { + if let Some(seen) = xml_ids.get_mut(&uid) { + if *seen != Some(id) { + *seen = None; + } + } else if xml_ids.len() < MAX_XML_IDS && bytes.saturating_add(uid.len()) <= MAX_XML_ID_BYTES { + *bytes += uid.len(); + xml_ids.insert(uid, Some(id)); + } +} + /// Read the structure of the editing data `data`, applying the file's `%AI24_LargeCanvasScale` only /// when `large_canvas` is set: an EPS's page is drawn at the full size, but a `.ai`'s PDF part may /// keep the reduced one, which the PDF import reads as it is (#2031). @@ -323,6 +351,10 @@ struct Reader<'a> { obj_hidden: bool, /// The names of text objects, by their slot's id. slot_names: HashMap, + /// [`Structure::xml_ids`]. + xml_ids: HashMap>, + /// The bytes of the ids in `xml_ids`. + xml_id_bytes: usize, /// The artboard's size and centre in files without artboards or crop marks. art_size: Option<(f64, f64)>, template_center: Option<(f64, f64)>, @@ -456,6 +488,8 @@ impl<'a> Reader<'a> { done: false, obj_hidden: false, slot_names: HashMap::new(), + xml_ids: HashMap::new(), + xml_id_bytes: 0, art_size: None, template_center: None, large_canvas: None, diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index c5a05b9152..5aebb94dda 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -331,17 +331,39 @@ fn artboards_read(data: &[u8]) -> Vec<(String, Rect)> { r.artboards.into_iter().map(|b| (b.name, b.rect)).collect() } +/// An object bound to a variable of the library: the variable's name, and the XML id of the object +/// (the `AI10_ArtUID` of its dictionary). The id is `None` when the reference can't be read. +#[derive(Clone, Debug, PartialEq)] +pub struct BindingRef { + pub variable: String, + pub target: Option, +} + /// The variable library of the editing data, as [`variable_library`] reads it. #[derive(Clone, Debug, Default, PartialEq)] pub struct VariableRead { /// Its variables, data sets, active data set and lock, without bindings. pub variables: Variables, + /// The objects bound to its variables, in the order the library declares them. + pub bindings: Vec, + /// How many objects its declarations bind that aren't in `bindings`: those of a declaration + /// left out, and those past [`MAX_LIBRARY_BINDINGS`]. + pub bindings_skipped: usize, /// How many of its declarations, data sets, values and settings were left out. pub skipped: usize, /// Whether the editing data has a variable library (a `variableSets` element). pub present: bool, } +/// The import's note about the library's bindings when `skipped` of them weren't made: nothing +/// when all of them were. +pub fn bindings_note(skipped: usize) -> Option { + // A count after a colon needs no plural, so every language can translate the note whole. + (skipped > 0).then(|| { + format!("the file's variable bindings weren't all read (bindings skipped: {skipped}): those objects aren't bound to their variables") + }) +} + impl VariableRead { /// The import's note about what of the library wasn't read: nothing when all of it was. pub fn note(&self) -> Option { @@ -521,6 +543,12 @@ impl<'a> Reader<'a> { { n.extras_mut().wrap = Some(wrap); } + // The object's XML id, which the variable library's bindings name it by. + if let Some(uid) = o.obj("AI10_ArtUID").and_then(Obj::content_text).filter(|u| !u.is_empty()) + && let Some(id) = self.last_object().filter(|n| !matches!(n.kind, NodeKind::Layer { .. })).map(|n| n.id) + { + super::remember_xml_id(&mut self.xml_ids, &mut self.xml_id_bytes, uid, id); + } let name = match o.text("AIArtName") { Some(name) => name, None => match o.obj("AI10_ArtUID").and_then(Obj::content_text) { @@ -843,6 +871,7 @@ impl<'a> Reader<'a> { if variables.present { doc.variables = variables.variables.into(); } + let (bindings, bindings_skipped) = (variables.bindings, variables.bindings_skipped); Ok(Structure { doc, to_doc, @@ -858,6 +887,9 @@ impl<'a> Reader<'a> { envelopes_drawn: self.envelopes_drawn, styles_read, canvas_scale: self.canvas_scale, + xml_ids: self.xml_ids, + bindings, + bindings_skipped, warnings, }) } @@ -959,9 +991,10 @@ pub(super) fn find_entry<'o>(o: &'o Obj, key: &str, depth: usize) -> Option<&'o /// Caps on the variable library of the editing data, as Load Variable Library has them: the XML /// nodes read, the variables and data sets kept, the characters of a name, and the bytes of the -/// names and values kept. +/// names and values kept. Past those, the objects bound to the variables. const MAX_LIBRARY_NODES: usize = 2_000_000; const MAX_LIBRARY_VARIABLES: usize = 256; +const MAX_LIBRARY_BINDINGS: usize = 100_000; const MAX_LIBRARY_DATASETS: usize = 1_000; const MAX_LIBRARY_NAME: usize = 255; const MAX_LIBRARY_BYTES: usize = 8 << 20; @@ -974,11 +1007,13 @@ const MAX_LIBRARY_BYTES: usize = 8 << 20; /// are locked), with a `variables` element of `variable` elements (`varName`, and `trait`: /// `textcontent`, `visibility`, `fileref` or `graphdata`; another trait or none is a variable of /// unknown kind), and a `sampleDataSets` element (`activeDataSet`, the data set shown) of -/// `sampleDataSet` elements (`dataSetName`). In a data set, the element named after a variable holds -/// its value: `p` elements of text, one paragraph each; a `/Bool` text, whether its objects show; a -/// linked file's URL (`file://`) or path. Graph values aren't read. What is malformed, repeated or -/// past the caps (a declaration, a data set, a value, a setting, a second `variableSet`) is left out -/// and counted; a library past [`MAX_LIBRARY_NODES`] isn't read. Bindings aren't read. +/// `sampleDataSet` elements (`dataSetName`). A `variable` bound to an object has a `docRef` attribute +/// whose value is the object's XML id (`/XMLUIDREF`); a variable bound to several objects is +/// declared once for each, with the same name and trait. In a data set, the element named after a +/// variable holds its value: `p` elements of text, one paragraph each; a `/Bool` text, whether its +/// objects show; a linked file's URL (`file://`) or path. Graph values aren't read. What is +/// malformed, repeated or past the caps (a declaration, a data set, a value, a setting, a second +/// `variableSet`) is left out and counted; a library past [`MAX_LIBRARY_NODES`] isn't read. fn variable_library(o: &Obj) -> VariableRead { find_variable_sets(o, 0).map_or_else(VariableRead::default, read_variable_sets) } @@ -1113,11 +1148,23 @@ fn percent_decoded(s: &str) -> String { String::from_utf8(out).unwrap_or_else(|_| s.to_string()) } -/// The walk through a variable library: the nodes read, the bytes kept, and what was left out. +/// The object an element's `docRef` attribute names: `None` without one, `Some(None)` when its +/// value isn't an XML id (`/XMLUIDREF`) of at most [`MAX_LIBRARY_NAME`] characters. +fn doc_ref(o: &Obj) -> Option> { + let attributes = o.obj("xmlnode-attributes").filter(|a| a.ty == "Dictionary")?; + let node = attributes.items().find(|a| is_node(a, 2.0) && node_name(a).is_some_and(|n| n.rsplit(':').next() == Some("docRef")))?; + let id = node.obj("xmlnode-nodevalue").filter(|v| v.ty == "XMLUIDREF").and_then(Obj::content_text); + Some(id.filter(|id| !id.is_empty() && id.chars().count() <= MAX_LIBRARY_NAME)) +} + +/// The walk through a variable library: the nodes read, the bytes kept, the bindings, and what was +/// left out. #[derive(Default)] struct LibraryWalk { nodes: usize, bytes: usize, + bindings: Vec, + bindings_skipped: usize, skipped: usize, } @@ -1167,7 +1214,8 @@ impl LibraryWalk { } } - /// The `variable` elements of the `variables` element `list`, into `vars`. + /// The `variable` elements of the `variables` element `list`, into `vars`, and the objects they + /// bind. A second declaration of a variable binds one more object to it. fn declarations(&mut self, list: &Obj, vars: &mut Variables) { let Some(children) = self.children(list) else { self.skipped += 1; @@ -1175,10 +1223,6 @@ impl LibraryWalk { }; for v in children.into_iter().filter(|c| !is_node(c, 3.0)) { let name = is_element(v, "variable").then(|| library_name(xml_attribute(v, "varName"))).flatten(); - let Some(name) = name.filter(|n| vars.variable(n).is_none() && vars.variables.len() < MAX_LIBRARY_VARIABLES && self.keep(n.len())) else { - self.skipped += 1; - continue; - }; let kind = match xml_attribute(v, "trait").as_deref() { Some("textcontent") => VariableKind::Text, Some("visibility") => VariableKind::Visibility, @@ -1186,7 +1230,41 @@ impl LibraryWalk { Some("graphdata") => VariableKind::Graph, _ => VariableKind::Unknown, }; - vars.variables.push(Variable { name, kind }); + let target = doc_ref(v); + // A declaration left out, and the object it binds. + let left_out = |walk: &mut Self| { + walk.skipped += 1; + walk.bindings_skipped += usize::from(target.is_some()); + }; + let Some(name) = name else { + left_out(self); + continue; + }; + match vars.variable(&name) { + // Another object bound to the variable. + Some(declared) if declared.kind == kind => {} + // A second variable of that name, of another kind. + Some(_) => { + left_out(self); + continue; + } + None if vars.variables.len() < MAX_LIBRARY_VARIABLES && self.keep(name.len()) => { + vars.variables.push(Variable { name: name.clone(), kind }); + } + None => { + left_out(self); + continue; + } + } + if let Some(target) = target { + // The binding keeps its own copy of the name, and its target. + let len = name.len().saturating_add(target.as_ref().map_or(0, String::len)); + if self.bindings.len() < MAX_LIBRARY_BINDINGS && self.keep(len) { + self.bindings.push(BindingRef { variable: name, target }); + } else { + self.bindings_skipped += 1; + } + } } } @@ -1316,7 +1394,7 @@ fn read_variable_sets(sets: &Obj) -> VariableRead { None => walk.skipped += 1, } if walk.nodes > MAX_LIBRARY_NODES { - return VariableRead { variables: Variables::default(), skipped: 1, present: true }; + return VariableRead { variables: Variables::default(), bindings: vec![], bindings_skipped: 0, skipped: 1, present: true }; } - VariableRead { variables: vars, skipped: walk.skipped, present: true } + VariableRead { variables: vars, bindings: walk.bindings, bindings_skipped: walk.bindings_skipped, skipped: walk.skipped, present: true } } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index cbe7966e7f..eb46288c42 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -1429,6 +1429,75 @@ fn ai_variable_library_definitions() { assert!(!r.warnings.iter().any(|w| w.contains("variable")), "{:?}", r.warnings); } +/// The objects a variable is bound to come with the library, each by the XML id its `docRef` gives, +/// in the order the library declares them: a variable bound to two objects is declared twice and +/// comes in once. A `docRef` that isn't an XML id is kept as unreadable, a declaration without one +/// binds nothing, and a second variable of the same name and another kind is left out with a note, +/// its binding counted as left out. +/// The objects read keep their XML ids; an id two objects have names neither of them. +#[test] +fn ai_variable_library_bindings() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: &str, art: Option| { + let mut attributes = vec![("trait", XmlValue::Str(t)), ("varName", XmlValue::Unicode(name))]; + attributes.extend(art.map(|a| ("docRef", a))); + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let declared = vec![ + declare("v_shown", "visibility", Some(XmlValue::Raw("/XMLUIDREF : (one) ;"))), + declare("v_text", "textcontent", Some(XmlValue::Str("one"))), + declare("v_shown", "visibility", Some(XmlValue::Raw("/XMLUIDREF : (two) ;"))), + declare("v_shown", "textcontent", Some(XmlValue::Raw("/XMLUIDREF : (two) ;"))), + declare("v_free", "visibility", None), + ]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let square = |x: f64, id: &str| format!("{RED}{}f\n{}", rect_path(x, 0.0, x + 10.0, 10.0), named(id)); + let squares = layer(&[square(0.0, "one"), square(20.0, "two"), square(40.0, "twice"), square(60.0, "twice")].concat()); + let r = read_ok(&format!("{library}{squares}")); + let names: Vec<&str> = r.doc.variables.variables.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, ["v_shown", "v_text", "v_free"]); + let refs: Vec<(&str, Option<&str>)> = r.bindings.iter().map(|b| (b.variable.as_str(), b.target.as_deref())).collect(); + assert_eq!(refs, [("v_shown", Some("one")), ("v_text", None), ("v_shown", Some("two"))]); + assert!(r.warnings.contains(&partly_read(1)), "{:?}", r.warnings); + // The object the declaration left out binds is counted for the bindings' note. + assert_eq!(r.bindings_skipped, 1); + // The reader doesn't bind them: the importer does, with the objects it keeps. + assert!(r.doc.variables.bindings.is_empty()); + let ids: Vec = art(&r.doc).iter().map(|n| n.id).collect(); + assert_eq!(r.xml_ids.get("one"), Some(&Some(ids[0]))); + assert_eq!(r.xml_ids.get("two"), Some(&Some(ids[1]))); + assert_eq!(r.xml_ids.get("twice"), Some(&None)); +} + +/// The bindings count against the library's 8 MB of names and values: each one keeps its +/// variable's name and its target. The declarations past that bind nothing and are counted as left +/// out. +#[test] +fn ai_variable_library_bindings_stay_within_the_byte_budget() { + use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node}; + let (name, id) = ("é".repeat(255), "a".repeat(255)); + let target = format!("/XMLUIDREF : ({id}) ;"); + let declare = || { + xml_node( + 1, + "variable", + XmlValue::Str(""), + &[("trait", XmlValue::Str("visibility")), ("varName", XmlValue::Unicode(&name)), ("docRef", XmlValue::Raw(&target))], + &[], + ) + }; + let declared: Vec<_> = (0..11_500).map(|_| declare()).collect(); + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let square = layer(&format!("{RED}{}f\n", rect_path(0.0, 0.0, 10.0, 10.0))); + let r = read_ok(&format!("{}{square}", variable_library_data(&xml_element("variableSets", &[], &[set])))); + assert_eq!(r.doc.variables.variables.len(), 1); + // The variable's name, then each binding's name and target. + let kept = ((8 << 20) - name.len()) / (name.len() + id.len()); + assert_eq!(r.bindings.len(), kept); + assert_eq!(r.bindings_skipped, 11_500 - kept); +} + /// The data sets come in in order with their values: text of one paragraph per `p` element (`&`, /// `<` and accented letters as they are), whether the objects show, and a linked file's path from /// its URL, kept when it names no file. A variable of unknown kind has no value. @@ -2164,6 +2233,34 @@ fn previewless_placement_placeholder_inherits_lock() { assert!(node.visible); } +/// A placed file's XML id names the linked image it comes in as, for the variable library's +/// bindings. +#[test] +fn a_placed_files_xml_id_names_its_image() { + let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat(); + let name = "%_/ArtDictionary :\r%_/XMLUID : (photo_x5F_1) ; (AI10_ArtUID) ,\r%_;\r"; + let r = read(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", Some(&preview), name)).unwrap(); + let a = art(&r.doc); + assert!(matches!(a[0].kind, NodeKind::Image(_)), "{:?}", a[0].kind); + assert_eq!(r.xml_ids.get("photo_x5F_1"), Some(&Some(a[0].id))); +} + +/// The XML ids kept stay within `MAX_XML_ID_BYTES` in all: an id that would pass it is left out, +/// and a shorter one after it still fits. +#[test] +fn xml_ids_stay_within_their_byte_budget() { + use vectorcraft_doc::NodeId; + let (mut ids, mut bytes) = (std::collections::HashMap::new(), 0); + super::read::remember_xml_id(&mut ids, &mut bytes, "a".repeat(super::read::MAX_XML_ID_BYTES - 4), NodeId(1)); + super::read::remember_xml_id(&mut ids, &mut bytes, "long_id".into(), NodeId(2)); + super::read::remember_xml_id(&mut ids, &mut bytes, "id_2".into(), NodeId(3)); + super::read::remember_xml_id(&mut ids, &mut bytes, "id_2".into(), NodeId(4)); + assert_eq!(ids.len(), 2); + assert!(!ids.contains_key("long_id")); + assert_eq!(ids.get("id_2"), Some(&None), "two objects with one id are neither of them that id's"); + assert_eq!(bytes, super::read::MAX_XML_ID_BYTES); +} + #[test] fn placed_files_are_linked_images_showing_their_preview() { // A 2×1 preview (premultiplied ARGB, a padded row) of a file of 4×2 pixels. diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 916451a380..354196555d 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -32,7 +32,7 @@ use std::collections::BTreeSet; use std::sync::Arc; use vectorcraft_color::BlendMode; -use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, Scaling, TextKind, Unit}; +use vectorcraft_doc::{AppearanceItem, Document, Node, NodeId, NodeKind, Scaling, TextKind, Unit, VariableKind}; use vectorcraft_geom::{Affine, PathData, Point, Rect, Vec2}; use super::Imported; diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 4226ccaacf..31be3af5a8 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -3,10 +3,12 @@ use super::compare::{ }; use super::plan::{made_only, make_slots, plan, readable_all}; use super::slots::{ - ART_LEFT_OUT, Content, DREW_DIFFERENTLY, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, collect_slots, - extent, few, fill_slots, letters, text_objects, words, + ART_LEFT_OUT, Content, DREW_DIFFERENTLY, Filled, MAX_PAIRS, MAX_SLOTS, MAX_TEXT, OUTLINE_REACH, SlotInfo, TEXT_LEFT_OUT, TYPE_LEFT_OUT, + collect_slots, extent, few, fill_slots, letters, text_objects, words, +}; +use super::{ + Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, VariableKind, Vec2, ai, }; -use super::{Affine, Arc, BTreeSet, Document, Node, NodeId, NodeKind, PathData, Rect, Scaling, Story, Structure, Texts, Unit, Vec2, ai}; /// Which box of the editing copy is the page. #[derive(Clone, Copy)] @@ -107,6 +109,9 @@ pub(super) fn build_from( envelopes_drawn, styles_read, canvas_scale, + xml_ids, + bindings, + bindings_skipped, warnings, } = structure; // Editing data in the units of the page's user space ([`in_units`]), or at its declared large @@ -282,7 +287,8 @@ pub(super) fn build_from( let mut empty = 0; let mut layers = std::mem::take(&mut doc.layers); let mut made = vec![]; - fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![]); + let mut filled = std::collections::HashMap::new(); + fill_slots(&mut doc, &mut layers, &mut content.into_iter(), &slot_names, &mut empty, &mut made, &mut vec![], &mut filled); doc.layers = layers; made.sort(); let threaded_frames: BTreeSet = @@ -378,6 +384,7 @@ pub(super) fn build_from( None => unmark(&mut doc.layers, true, true, &mut vec![]), } doc.limit_depth_noting(&mut notes); + bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes); if small.is_some() { scale_document(&mut doc, unit, styles_read); relayout_wrapped(&mut doc); @@ -385,6 +392,66 @@ pub(super) fn build_from( Ok((doc, notes)) } +/// Bind the objects of `doc` to the variables of its library that `bindings` binds them to, each +/// object named by its XML id (`ids`: the object read with that id, or what `filled` made of a text +/// object's slot: for a visibility variable every object that took the slot's place, for a text +/// variable the one text object among them). An object is bound when it is of the variable's kind: +/// type for a text variable, a linked image for an image variable, any object for a visibility +/// variable. Locked and hidden objects, objects in locked or hidden layers and groups, and objects +/// on locked artboards keep their bindings. Graph variables and +/// variables of unknown kind bind nothing. The note counts the bindings that weren't made, with +/// `skipped` more that the reader left out. +fn bind_variables( + doc: &mut Document, + bindings: &[ai::BindingRef], + skipped: usize, + ids: &std::collections::HashMap>, + filled: &std::collections::HashMap, + notes: &mut Vec, +) { + let mut skipped = skipped; + if bindings.is_empty() { + notes.extend(ai::bindings_note(skipped)); + return; + } + let mut bound = vec![]; + for b in bindings { + let kind = doc.variables.variable(&b.variable).map(|v| v.kind); + let targets = match (b.target.as_ref().and_then(|t| ids.get(t).copied().flatten()), kind) { + (Some(id), Some(kind)) => match filled.get(&id) { + Some(f) if kind == VariableKind::Visibility => f.objects.clone(), + Some(f) => match f.text.as_slice() { + [one] => vec![*one], + _ => vec![], + }, + None => vec![id], + }, + _ => vec![], + }; + // Those still in the document: a part of a slot can have been taken out since. + let targets: Vec = targets.into_iter().filter(|id| doc.node(*id).is_some()).collect(); + let fits = |id: &NodeId| { + doc.node(*id).is_some_and(|n| match (kind, &n.kind) { + (Some(VariableKind::Visibility), _) => true, + (Some(VariableKind::Text), NodeKind::Text(_)) => true, + (Some(VariableKind::Image), NodeKind::Image(im)) => im.link.is_some(), + _ => false, + }) + }; + if !targets.is_empty() && targets.iter().all(fits) { + bound.push((targets, b.variable.as_str())); + } else { + skipped += 1; + } + } + for (targets, variable) in bound { + for id in targets { + doc.variables.bind(id, variable); + } + } + notes.extend(ai::bindings_note(skipped)); +} + /// Most anchors copied into the wrap shapes of a file's area type ([`vectorcraft_doc::text::wrap_work`]). const MAX_WRAP_WORK: usize = 2_000_000; @@ -1537,6 +1604,102 @@ mod candidate_tests { assert_eq!(wrap_shapes(&doc, text), 0); } + /// An image variable binds the linked image its XML id names, and not an embedded image or a + /// path; a text variable binds the type a slot became, and not a slot that became two text + /// objects; a visibility variable binds every object that took a slot's place and is still in + /// the document; a graph variable + /// binds nothing. A locked object, one in a hidden group and objects on a locked artboard are + /// bound too. Every binding left out, and those the reader left out, are counted in one note. + #[test] + fn variable_bindings_take_objects_of_their_kind() { + use vectorcraft_doc::{LinkInfo, Variable, Variables}; + let mut doc = Document::new(100.0, 100.0); + let made = insert_area(&mut doc, 0, Rect::new(0.0, 0.0, 50.0, 50.0)); + let (one, two) = (insert_area(&mut doc, 1, Rect::new(50.0, 0.0, 60.0, 10.0)), insert_area(&mut doc, 2, Rect::new(60.0, 0.0, 70.0, 10.0))); + let path = insert_wrap(&mut doc, Rect::new(0.0, 60.0, 10.0, 70.0), 4); + let locked = insert_wrap(&mut doc, Rect::new(20.0, 60.0, 30.0, 70.0), 4); + let image = |doc: &mut Document, link: Option| { + let id = doc.alloc_id(); + let im = ImageObject { key: "k".into(), width: 1, height: 1, xf: Affine::IDENTITY, link, placement: Default::default(), pixels: None }; + doc.insert(Some(doc.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap(); + id + }; + let (linked, embedded) = (image(&mut doc, Some(LinkInfo::new("/a.png"))), image(&mut doc, None)); + doc.node_mut(locked).unwrap().locked = true; + let hidden = doc.alloc_id(); + let inside = doc.alloc_id(); + let mut group = Node::group( + hidden, + vec![Arc::new(Node::new( + inside, + NodeKind::Image(Box::new(ImageObject { + key: "k".into(), + width: 1, + height: 1, + xf: Affine::IDENTITY, + link: Some(LinkInfo::new("/b.png")), + placement: Default::default(), + pixels: None, + })), + ))], + ); + group.visible = false; + doc.insert(Some(doc.layers[0].id), 0, group).unwrap(); + doc.artboards[0].locked = true; + let var = |name: &str, kind| Variable { name: name.into(), kind }; + doc.variables = Variables { + variables: vec![ + var("v_image", VariableKind::Image), + var("v_text", VariableKind::Text), + var("v_shown", VariableKind::Visibility), + var("v_graph", VariableKind::Graph), + ], + ..Default::default() + } + .into(); + // The slots the text objects came from are gone; their ids are the ones the reader gave. + let (slot, split) = (NodeId(9000), NodeId(9001)); + let ids: std::collections::HashMap> = [ + ("linked", Some(linked)), + ("embedded", Some(embedded)), + ("path", Some(path)), + ("locked", Some(locked)), + ("inside", Some(inside)), + ("slot", Some(slot)), + ("split", Some(split)), + ] + .map(|(k, v)| (k.to_string(), v)) + .into(); + let filled: std::collections::HashMap = [ + (slot, Filled { text: vec![made], objects: vec![made] }), + (split, Filled { text: vec![one, two], objects: vec![one, two, NodeId(9002)] }), + ] + .into(); + let bind = |variable: &str, target: &str| ai::BindingRef { variable: variable.into(), target: Some(target.into()) }; + let refs = [ + bind("v_image", "linked"), + bind("v_image", "embedded"), + bind("v_image", "path"), + bind("v_image", "inside"), + bind("v_text", "slot"), + bind("v_text", "split"), + bind("v_shown", "split"), + bind("v_shown", "locked"), + bind("v_graph", "path"), + ]; + let mut notes = vec![]; + bind_variables(&mut doc, &refs, 3, &ids, &filled, &mut notes); + let sorted = |mut v: Vec| { + v.sort(); + v + }; + assert_eq!(sorted(doc.variables.objects_of("v_image")), sorted(vec![linked, inside])); + assert_eq!(doc.variables.objects_of("v_text"), [made]); + assert_eq!(sorted(doc.variables.objects_of("v_shown")), sorted(vec![one, two, locked])); + assert!(doc.variables.objects_of("v_graph").is_empty()); + assert_eq!(notes, ai::bindings_note(4 + 3).into_iter().collect::>()); + } + /// Area type wrapped around a placed image flows around it at the image's other placement. #[test] fn wrap_shapes_follow_an_image_to_its_other_placement() { diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index f5f7693801..bb88aa1244 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -156,10 +156,12 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl /// `doc` (a file read as its page or PDF part, in place of its layers) with the variables, data /// sets, active data set and lock of the variable library of its editing data `data`, as [`build`] /// gives a document read from the layers, and the note about what of the library wasn't read -/// added to `warnings`. Left as it is when the editing data has no library. +/// added to `warnings`: its bindings aren't, as the objects they bind aren't the layers' objects. +/// Left as it is when the editing data has no library. fn use_variables(data: &[u8], doc: &mut Document, warnings: &mut Vec) { let read = ai::variables(data); warnings.extend(read.note()); + warnings.extend(ai::bindings_note(read.bindings.len() + read.bindings_skipped)); if read.present { doc.variables = read.variables.into(); } diff --git a/crates/eps/src/import/native/slots.rs b/crates/eps/src/import/native/slots.rs index ed5b4c5a14..4924c167aa 100644 --- a/crates/eps/src/import/native/slots.rs +++ b/crates/eps/src/import/native/slots.rs @@ -242,6 +242,25 @@ fn see_through(n: &Node) -> bool { n.opacity < 1.0 || n.blend != BlendMode::Normal || n.isolate } +/// What a text slot became in [`fill_slots`]: the text objects among it, those in groups included, +/// and the objects that took its place. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct Filled { + pub text: Vec, + pub objects: Vec, +} + +/// The ids of the text objects in `nodes` and in their groups, into `out`. +fn text_ids(nodes: &[Arc], out: &mut Vec) { + for n in nodes { + match n.children() { + _ if matches!(n.kind, NodeKind::Text(_)) => out.push(n.id), + Some(c) => text_ids(c, out), + None => {} + } + } +} + /// Replace the text slots in `nodes` with what `content` has for each, in order (a slot given none is /// left out): the page's type takes its place as it is, made type keeps the slot's name. Made type /// takes the slot's opacity, blend mode, isolation and knockout. The page's type takes them too when @@ -249,7 +268,9 @@ fn see_through(n: &Node) -> bool { /// combined with that of the objects around `nodes`; otherwise they keep their own. Where the slot has /// transparency and the type comes with other art that has none of its own, a group of them takes the /// slot's instead. `round` has the opacity and blend mode of each object around `nodes`, which the page -/// can have folded into its type. `empty` counts those left out. +/// can have folded into its type. `empty` counts those left out. `filled` gets what each slot +/// became, by the slot's id. +#[allow(clippy::too_many_arguments)] pub(super) fn fill_slots( doc: &mut Document, nodes: &mut Vec>, @@ -258,11 +279,13 @@ pub(super) fn fill_slots( empty: &mut usize, made: &mut Vec<(u32, usize, NodeId)>, round: &mut Vec<(f32, BlendMode)>, + filled: &mut std::collections::HashMap, ) { let mut i = 0; while i < nodes.len() { let Some(n) = nodes.get(i) else { break }; if let Some(story) = slot_of(n.name.as_deref()) { + let slot = n.id; let visible = n.visible; let name = names.get(&n.id); let frame = ai::slot_frame(n.name.as_deref()); @@ -290,6 +313,8 @@ pub(super) fn fill_slots( p }) .collect(); + let mut text = vec![]; + text_ids(&parts, &mut text); // When the page draws each of them with no transparency, the slot's, or the slot's // combined with that of the objects around it, the slot's takes its place: on the one // part, or on a group of several when the slot has transparency. Otherwise every part @@ -335,6 +360,7 @@ pub(super) fn fill_slots( { Arc::make_mut(p).extras_mut().graphic_style = linked; } + filled.insert(slot, Filled { text, objects: parts.iter().map(|p| p.id).collect() }); let n = parts.len(); nodes.splice(i..=i, parts); i += n; @@ -342,6 +368,7 @@ pub(super) fn fill_slots( } Some(Content::Made(mut text, _, seen)) => { text.id = doc.alloc_id(); + filled.insert(slot, Filled { text: vec![text.id], objects: vec![text.id] }); if let Some(story) = story { made.push((story, frame, text.id)); } @@ -392,7 +419,7 @@ pub(super) fn fill_slots( && let Some(c) = nodes.get_mut(i).map(Arc::make_mut).and_then(Node::children_mut) { round.push(state); - fill_slots(doc, c, content, names, empty, made, round); + fill_slots(doc, c, content, names, empty, made, round, filled); round.pop(); } i += 1; @@ -617,12 +644,36 @@ mod tests { let parts = vec![part(&mut doc, 10.0), part(&mut doc, 60.0)]; let mut nodes = vec![Arc::new(slot)]; let mut content = vec![Content::Page(parts)].into_iter(); - let (mut empty, mut made) = (0, vec![]); - fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![]); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + let slot = nodes[0].id; + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); assert_eq!(nodes.len(), 1); assert_eq!(nodes[0].extras().wrap, Some(wrap)); let NodeKind::Group { children, .. } = &nodes[0].kind else { panic!("a group: {:?}", nodes[0].kind) }; assert_eq!(children.len(), 2); assert!(children.iter().all(|c| c.extras().wrap.is_none() && matches!(c.kind, NodeKind::Text(_)))); + // The slot became the group, which holds its two text objects. + assert_eq!(filled.get(&slot), Some(&Filled { text: children.iter().map(|c| c.id).collect(), objects: vec![nodes[0].id] })); + } + + /// A slot filled with the page's type in a group and a stroke beside it became both of them, and + /// the text object in the group. + #[test] + fn a_slot_filled_from_the_page_records_its_objects_and_its_type() { + let mut doc = Document::new(100.0, 100.0); + let mut slot = Node::group(doc.alloc_id(), vec![]); + slot.name = Some("\u{0}text0:0".into()); + let t = vectorcraft_doc::TextObject::point(Point::new(10.0, 50.0), "Part", Default::default()); + let text = Arc::new(Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)))); + let group = Arc::new(Node::group(doc.alloc_id(), vec![text])); + let stroke = Arc::new(Node::path(doc.alloc_id(), PathData::default(), Default::default())); + let mut nodes = vec![Arc::new(slot)]; + let slot = nodes[0].id; + let mut content = vec![Content::Page(vec![group, stroke])].into_iter(); + let (mut empty, mut made, mut filled) = (0, vec![], std::collections::HashMap::new()); + fill_slots(&mut doc, &mut nodes, &mut content, &Default::default(), &mut empty, &mut made, &mut vec![], &mut filled); + assert_eq!(nodes.len(), 2); + let inner = nodes[0].children().unwrap()[0].id; + assert_eq!(filled.get(&slot), Some(&Filled { text: vec![inner], objects: vec![nodes[0].id, nodes[1].id] })); } } diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index e553712e92..a571774262 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -1476,6 +1476,76 @@ fn ai_variable_library_pdf_fallback() { assert!(warnings.contains(¬e), "{warnings:?}"); let r = import(&eps(&page_square(10, 10), &art)).unwrap(); assert!(r.warnings.contains(¬e), "{:?}", r.warnings); + // The objects the library binds aren't those of the page: none is bound, and the note counts + // the library's three bindings. + let bindings = "the file's variable bindings weren't all read (bindings skipped: 3): those objects aren't bound to their variables".to_string(); + assert!(r.warnings.contains(&bindings), "{:?}", r.warnings); + assert!(r.document.variables.bindings.is_empty()); + let (d, warnings, _) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec![], false, true, 1.0); + assert!(warnings.contains(&bindings), "{warnings:?}"); + assert!(d.variables.bindings.is_empty()); +} + +/// The objects the variable library binds come in bound to its variables: type (made from the text +/// document), an object in a group, and a second object of the same variable, each found by its XML +/// id. A binding whose object isn't in the file, whose object isn't of the variable's kind (type +/// for a text variable), whose variable is of unknown kind, or whose reference can't be read binds +/// nothing, and the note counts them. Another object with the same id as the group is left alone. +#[test] +fn ai_variable_bindings_bind_the_objects_they_name() { + use vectorcraft_testkit::ai::{XmlValue, named, variable_library_data, xml_element, xml_node}; + let declare = |name: &str, t: Option<&str>, art: Option| { + let mut attributes: Vec<(&str, XmlValue)> = t.map(|t| ("trait", XmlValue::Str(t))).into_iter().collect(); + attributes.push(("varName", XmlValue::Unicode(name))); + attributes.extend(art.map(|a| ("docRef", a))); + xml_node(1, "variable", XmlValue::Str(""), &attributes, &[]) + }; + let uid = |id: &str| format!("/XMLUIDREF : ({id}) ;"); + let declared = vec![ + declare("v_text", Some("textcontent"), Some(XmlValue::Raw(&uid("type_x5F_1")))), + declare("v_shown", Some("visibility"), Some(XmlValue::Raw(&uid("square_x5F_1")))), + declare("v_shown", Some("visibility"), Some(XmlValue::Raw(&uid("inner_x5F_1")))), + declare("v_wrong", Some("textcontent"), Some(XmlValue::Raw(&uid("square_x5F_1")))), + declare("v_gone", Some("visibility"), Some(XmlValue::Raw(&uid("nowhere")))), + declare("v_odd", None, Some(XmlValue::Raw(&uid("square_x5F_1")))), + declare("v_bad", Some("visibility"), Some(XmlValue::Str("square_x5F_1"))), + declare("v_twice", Some("visibility"), Some(XmlValue::Raw(&uid("twice")))), + declare("v_free", Some("visibility"), None), + ]; + let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]); + let library = variable_library_data(&xml_element("variableSets", &[], &[set])); + let back = format!( + "u\n{}\n{}U\n{}{}\n{}{}\n{}", + square(10, 10), + named("inner_x5F_1"), + named("twice"), + square(30, 10), + named("square_x5F_1"), + square(50, 10), + named("twice") + ); + let spare = format!("{}{}", text_object(0), named("type_x5F_1")); + let doc = text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]); + // The type is on a layer that shows and doesn't print (its fourth flag off), which the page + // doesn't draw: it is made from the text document. + let spare = layer("Spare", true, &spare).replace("1 1 1 1 0 0 1 0 79", "1 1 1 0 0 0 1 0 79"); + let art = native_with_text(&(library + &layer("Back", true, &back) + &spare), &doc); + let page = [10, 30, 50].map(|x| page_square(x, 10)).join("\n"); + let r = import(&eps(&page, &art)).unwrap(); + assert_eq!(names(&r.document), ["Back", "Spare"], "{:?}", r.warnings); + let back = r.document.layers[0].children().unwrap(); + let inner = back[0].children().unwrap()[0].id; + let (square_id, type_id) = (back[1].id, r.document.layers[1].children().unwrap()[0].id); + assert!(matches!(r.document.node(type_id).map(|n| &n.kind), Some(NodeKind::Text(_))), "{:?}", r.warnings); + let vars = &r.document.variables; + assert_eq!(vars.objects_of("v_text"), [type_id], "{:?}", r.warnings); + let mut shown = vec![square_id, inner]; + shown.sort_unstable(); + assert_eq!(vars.objects_of("v_shown"), shown); + assert_eq!(vars.bindings.len(), 3, "{:?}", vars.bindings); + let note = "the file's variable bindings weren't all read (bindings skipped: 5): those objects aren't bound to their variables".to_string(); + assert!(r.warnings.contains(¬e), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("variable library")), "{:?}", r.warnings); } /// An EPS whose editing data can't be used, a palette with no layers among others, comes in as its diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index fd683d3cec..cce9ebd4ef 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5561,6 +5561,7 @@ theme Appearance Външен вид Effect Gallery Галерия с ефекти Filters Филтри Select artwork to apply effects Изберете графика, за да приложите ефекти +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables не всички връзки на променливите във файла бяха прочетени (пропуснати връзки: {_1}): тези обекти не са свързани със своите променливи @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest библиотеката с променливи на файла беше прочетена частично (пропуснати записи: {_1}): панелът „Променливи“ показва останалите @msg the file's variable library couldn't be read: the Variables panel doesn't list it библиотеката с променливи на файла не можа да бъде прочетена: панелът „Променливи“ не я показва @msg a variable of unknown kind can't be bound to objects променлива от неизвестен вид не може да бъде свързана с обекти diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index c785d37ddb..098c02cd40 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5582,6 +5582,7 @@ mark-style Japanese Japanski Effect Gallery Galerija efekata Filters Filteri Select artwork to apply effects Odaberite crtež za primjenu efekata +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nisu pročitane sve veze varijabli datoteke (preskočene veze: {_1}): ti objekti nisu vezani za svoje varijable @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest biblioteka varijabli datoteke je djelimično pročitana (preskočeni unosi: {_1}): panel Varijable navodi ostalo @msg the file's variable library couldn't be read: the Variables panel doesn't list it biblioteku varijabli datoteke nije bilo moguće pročitati: panel Varijable je ne navodi @msg a variable of unknown kind can't be bound to objects varijabla nepoznate vrste ne može se povezati s objektima diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5a591d27f3..93fe3cb2b6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5556,6 +5556,7 @@ digits Malayalam Malaiàlam @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer no s’han llegit les capes del fitxer ({_1}): arriba com la seva pàgina, en una sola capa @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part no s’han llegit les capes del fitxer a partir de les seves dades d’edició ({_1}): provenen de la seva part PDF @msg the file's preview header points outside the file la capçalera de previsualització del fitxer apunta fora del fitxer +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables no s’han llegit totes les vinculacions de variables del fitxer (vinculacions omeses: {_1}): aquests objectes no estan vinculats a les seves variables @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest la biblioteca de variables del fitxer s’ha llegit només en part (entrades omeses: {_1}): el panell Variables llista la resta @msg the file's variable library couldn't be read: the Variables panel doesn't list it no s’ha pogut llegir la biblioteca de variables del fitxer: el panell Variables no la llista @msg a variable of unknown kind can't be bound to objects una variable de tipus desconegut no es pot vincular a objectes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1472c0747a..67d5709b77 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5670,6 +5670,7 @@ mark-style Japanese Japonské Effect Gallery Galerie efektů Filters Filtry Select artwork to apply effects Vyberte grafiku, na kterou chcete použít efekty +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nebyly načteny všechny vazby proměnných souboru (vynechané vazby: {_1}): tyto objekty nejsou vázány na své proměnné @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest knihovna proměnných souboru byla načtena jen částečně (vynechané položky: {_1}): panel Proměnné zobrazuje zbytek @msg the file's variable library couldn't be read: the Variables panel doesn't list it knihovnu proměnných souboru nebylo možné načíst: panel Proměnné ji nezobrazuje @msg a variable of unknown kind can't be bound to objects proměnnou neznámého druhu nelze svázat s objekty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 73256a62b6..e45c0a364c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5243,6 +5243,7 @@ mark-style Japanese Japansk Path Length Stilængde @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer filens lag blev ikke læst ({_1}): den kommer ind som sin side, i ét lag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part filens lag blev ikke læst fra dens redigeringsdata ({_1}): de kommer fra dens PDF-del +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables ikke alle filens variabelbindinger blev læst (udeladte bindinger: {_1}): de objekter er ikke bundet til deres variabler @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest filens variabelbibliotek blev kun delvist læst (udeladte poster: {_1}): variabelpanelet viser resten @msg the file's variable library couldn't be read: the Variables panel doesn't list it filens variabelbibliotek kunne ikke læses: variabelpanelet viser det ikke @msg a variable of unknown kind can't be bound to objects en variabel af ukendt type kan ikke bindes til objekter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c380e4a07f..8db779ee49 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5250,6 +5250,7 @@ effect Soft Weich Effect Gallery Effekt-Galerie Filters Filter Select artwork to apply effects Wählen Sie Grafik aus, um Effekte anzuwenden +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nicht alle Variablenbindungen der Datei wurden gelesen (übersprungene Bindungen: {_1}): Diese Objekte sind nicht an ihre Variablen gebunden @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest die Variablenbibliothek der Datei wurde nur teilweise gelesen (übersprungene Einträge: {_1}): Das Bedienfeld „Variablen“ listet den Rest auf @msg the file's variable library couldn't be read: the Variables panel doesn't list it die Variablenbibliothek der Datei konnte nicht gelesen werden: Das Bedienfeld „Variablen“ listet sie nicht auf @msg a variable of unknown kind can't be bound to objects eine Variable unbekannter Art kann nicht an Objekte gebunden werden diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index c763a01f2b..071628cc8c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5621,6 +5621,7 @@ effect Points Σημεία Effect Gallery Συλλογή εφέ Filters Φίλτρα Select artwork to apply effects Επιλέξτε γραφικά για να εφαρμόσετε εφέ +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables δεν διαβάστηκαν όλες οι συνδέσεις μεταβλητών του αρχείου (συνδέσεις που παραλείφθηκαν: {_1}): αυτά τα αντικείμενα δεν είναι συνδεδεμένα με τις μεταβλητές τους @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest η βιβλιοθήκη μεταβλητών του αρχείου διαβάστηκε μόνο εν μέρει (καταχωρίσεις που παραλείφθηκαν: {_1}): ο πίνακας Μεταβλητές εμφανίζει τις υπόλοιπες @msg the file's variable library couldn't be read: the Variables panel doesn't list it δεν ήταν δυνατή η ανάγνωση της βιβλιοθήκης μεταβλητών του αρχείου: ο πίνακας Μεταβλητές δεν την εμφανίζει @msg a variable of unknown kind can't be bound to objects μια μεταβλητή άγνωστου είδους δεν μπορεί να συνδεθεί με αντικείμενα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index d71d23b18f..c63c6a07bd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5611,6 +5611,7 @@ mark-style Japanese Japonesas Effect Gallery Galería de efectos Filters Filtros Select artwork to apply effects Seleccione gráficos para aplicar efectos +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables no se leyeron todos los vínculos de variables del archivo (vínculos omitidos: {_1}): esos objetos no están vinculados a sus variables @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest la biblioteca de variables del archivo se leyó solo en parte (entradas omitidas: {_1}): el panel Variables muestra el resto @msg the file's variable library couldn't be read: the Variables panel doesn't list it no se pudo leer la biblioteca de variables del archivo: el panel Variables no la muestra @msg a variable of unknown kind can't be bound to objects una variable de tipo desconocido no se puede vincular a objetos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 102ef7c3bf..03f290305b 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5633,6 +5633,7 @@ mark-style Japanese Japanilainen Effect Gallery Tehostegalleria Filters Suodattimet Select artwork to apply effects Valitse kuvitus, johon tehosteet lisätään +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables kaikkia tiedoston muuttujasidoksia ei luettu (ohitettuja sidoksia: {_1}): niitä objekteja ei ole sidottu muuttujiinsa @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest tiedoston muuttujakirjasto luettiin vain osittain (ohitettuja kohtia: {_1}): Muuttujat-paneeli näyttää loput @msg the file's variable library couldn't be read: the Variables panel doesn't list it tiedoston muuttujakirjastoa ei voitu lukea: Muuttujat-paneeli ei näytä sitä @msg a variable of unknown kind can't be bound to objects tuntemattoman tyyppistä muuttujaa ei voi sitoa objekteihin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index b1ddc5f4fd..a0f15e3ccd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5665,6 +5665,7 @@ theme Appearance Apparence Effect Gallery Galerie d'effets Filters Filtres Select artwork to apply effects Sélectionnez des éléments graphiques pour appliquer des effets +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables les liaisons de variables du fichier n’ont pas toutes été lues (liaisons ignorées : {_1}) : ces objets ne sont pas liés à leurs variables @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest la bibliothèque de variables du fichier n’a été lue qu’en partie (entrées ignorées : {_1}) : le panneau Variables affiche le reste @msg the file's variable library couldn't be read: the Variables panel doesn't list it la bibliothèque de variables du fichier n’a pas pu être lue : le panneau Variables ne l’affiche pas @msg a variable of unknown kind can't be bound to objects une variable de type inconnu ne peut pas être liée à des objets diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 7da6af288c..e727d6abac 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5653,6 +5653,7 @@ imageTrace Outline Körvonal Effect Gallery Effektusgaléria Filters Szűrők Select artwork to apply effects Válasszon ki grafikát az effektusok alkalmazásához +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables a fájl változókötései közül nem mindegyik lett beolvasva (kihagyott kötések: {_1}): ezek az objektumok nincsenek a változóikhoz kötve @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest a fájl változókönyvtára csak részben lett beolvasva (kihagyott bejegyzések: {_1}): a Változók panel a többit listázza @msg the file's variable library couldn't be read: the Variables panel doesn't list it a fájl változókönyvtárát nem sikerült beolvasni: a Változók panel nem listázza @msg a variable of unknown kind can't be bound to objects ismeretlen típusú változó nem köthető objektumokhoz diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4e32a3d8aa..a15eddbb0a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5243,6 +5243,7 @@ mark-style Japanese Jepang Path Length Panjang jalur @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer lapisan file tidak terbaca ({_1}): file masuk sebagai halamannya, dalam satu lapisan @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part lapisan file tidak terbaca dari data pengeditannya ({_1}): lapisannya berasal dari bagian PDF file +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables tidak semua ikatan variabel file terbaca (ikatan yang dilewati: {_1}): objek-objek itu tidak terikat ke variabelnya @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest pustaka variabel file hanya terbaca sebagian (entri yang dilewati: {_1}): panel Variabel menampilkan sisanya @msg the file's variable library couldn't be read: the Variables panel doesn't list it pustaka variabel file tidak dapat dibaca: panel Variabel tidak menampilkannya @msg a variable of unknown kind can't be bound to objects variabel bertipe tidak dikenal tidak dapat diikat ke objek diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 56235fef13..4f93e78961 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5284,6 +5284,7 @@ lighting Light Luce Effect Gallery Galleria effetti Filters Filtri Select artwork to apply effects Seleziona la grafica a cui applicare gli effetti +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables non tutti i collegamenti delle variabili del file sono stati letti (collegamenti saltati: {_1}): quegli oggetti non sono collegati alle loro variabili @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest la libreria di variabili del file è stata letta solo in parte (voci saltate: {_1}): il pannello Variabili elenca il resto @msg the file's variable library couldn't be read: the Variables panel doesn't list it impossibile leggere la libreria di variabili del file: il pannello Variabili non la elenca @msg a variable of unknown kind can't be bound to objects una variabile di tipo sconosciuto non può essere associata a oggetti diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index cc48dc8bb1..806f1bcc3f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5327,6 +5327,7 @@ lighting Light ライト Effect Gallery 効果ギャラリー Filters フィルター Select artwork to apply effects 効果を適用するグラフィックを選択してください +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables ファイルの変数のバインドの一部が読み込まれませんでした (スキップしたバインド: {_1})。それらのオブジェクトは変数にバインドされていません @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest ファイルの変数ライブラリは一部だけ読み込まれました (スキップした項目: {_1})。残りは変数パネルに表示されます @msg the file's variable library couldn't be read: the Variables panel doesn't list it ファイルの変数ライブラリを読み込めませんでした。変数パネルには表示されません @msg a variable of unknown kind can't be bound to objects 種類が不明な変数はオブジェクトにバインドできません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 02470e035f..855a8f6fc6 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5544,6 +5544,7 @@ imageTrace Outline კონტური @msg no history to clear გასასუფთავებელი ისტორია არ არის @msg {_1} files are written by file.saveAsTemplate {_1} ფაილებს წერს file.saveAsTemplate @msg aiVersion 7 writes legacy .ai files, not .ait templates aiVersion 7 წერს ძველი ფორმატის .ai ფაილებს და არა .ait შაბლონებს +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables ფაილის ცვლადების ყველა კავშირი არ იქნა წაკითხული (გამოტოვებული კავშირები: {_1}): ეს ობიექტები არ არის დაკავშირებული თავიანთ ცვლადებთან @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest ფაილის ცვლადების ბიბლიოთეკა მხოლოდ ნაწილობრივ იქნა წაკითხული (გამოტოვებული ჩანაწერები: {_1}): პანელი „ცვლადები“ დანარჩენს აჩვენებს @msg the file's variable library couldn't be read: the Variables panel doesn't list it ფაილის ცვლადების ბიბლიოთეკის წაკითხვა ვერ მოხერხდა: პანელი „ცვლადები“ მას არ აჩვენებს @msg a variable of unknown kind can't be bound to objects უცნობი სახის ცვლადის ობიექტებთან დაკავშირება შეუძლებელია diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fc30c96d3a..04006d209f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5245,6 +5245,7 @@ lighting Light 광원 Effect Gallery 효과 갤러리 Filters 필터 Select artwork to apply effects 효과를 적용할 그래픽을 선택하세요 +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables 파일의 변수 바인딩 일부를 읽지 못했습니다(건너뛴 바인딩: {_1}). 해당 오브젝트는 변수에 바인딩되지 않습니다 @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest 파일의 변수 라이브러리를 일부만 읽었습니다(건너뛴 항목: {_1}). 나머지는 변수 패널에 표시됩니다 @msg the file's variable library couldn't be read: the Variables panel doesn't list it 파일의 변수 라이브러리를 읽을 수 없습니다. 변수 패널에 표시되지 않습니다 @msg a variable of unknown kind can't be bound to objects 종류를 알 수 없는 변수는 개체에 바인딩할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index cd7a559d27..671f78da3d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5251,6 +5251,7 @@ mark-style Japanese Japans Path Length Padlengte @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer de lagen van het bestand zijn niet ingelezen ({_1}): het komt binnen als zijn pagina, in één laag @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part de lagen van het bestand zijn niet ingelezen uit de bewerkingsgegevens ({_1}): ze komen uit het PDF-gedeelte +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables niet alle variabelekoppelingen van het bestand zijn ingelezen (overgeslagen koppelingen: {_1}): die objecten zijn niet aan hun variabelen gekoppeld @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest de variabelenbibliotheek van het bestand is slechts gedeeltelijk ingelezen (overgeslagen items: {_1}): het Variabelen-paneel toont de rest @msg the file's variable library couldn't be read: the Variables panel doesn't list it de variabelenbibliotheek van het bestand kan niet worden ingelezen: het Variabelen-paneel toont die niet @msg a variable of unknown kind can't be bound to objects een variabele van onbekend type kan niet aan objecten worden gekoppeld diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index d61832b344..cf9c4edf82 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5523,6 +5523,7 @@ mark-style Japanese Japońskie Effect Gallery Galeria efektów Filters Filtry Select artwork to apply effects Wybierz grafikę, aby zastosować efekty +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nie wszystkie powiązania zmiennych pliku zostały wczytane (pominięte powiązania: {_1}): te obiekty nie są powiązane ze swoimi zmiennymi @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest biblioteka zmiennych pliku została wczytana tylko częściowo (pominięte wpisy: {_1}): panel Zmienne wyświetla resztę @msg the file's variable library couldn't be read: the Variables panel doesn't list it nie udało się wczytać biblioteki zmiennych pliku: panel Zmienne jej nie wyświetla @msg a variable of unknown kind can't be bound to objects zmiennej nieznanego rodzaju nie można powiązać z obiektami diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 31b2c5b933..d29cac871f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5585,6 +5585,7 @@ mark-style Japanese Japonesas Effect Gallery Galeria de Efeitos Filters Filtros Select artwork to apply effects Selecione a arte para aplicar efeitos +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nem todos os vínculos de variáveis do arquivo foram lidos (vínculos ignorados: {_1}): esses objetos não estão vinculados às suas variáveis @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest a biblioteca de variáveis do arquivo foi lida só em parte (entradas ignoradas: {_1}): o painel Variáveis lista o restante @msg the file's variable library couldn't be read: the Variables panel doesn't list it não foi possível ler a biblioteca de variáveis do arquivo: o painel Variáveis não a lista @msg a variable of unknown kind can't be bound to objects uma variável de tipo desconhecido não pode ser vinculada a objetos diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 7a77d759ba..13948efde2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5279,6 +5279,7 @@ lighting Light Свет Effect Gallery Галерея эффектов Filters Фильтры Select artwork to apply effects Выберите графику, чтобы применить эффекты +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables прочитаны не все привязки переменных файла (пропущено привязок: {_1}): эти объекты не привязаны к своим переменным @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest библиотека переменных файла прочитана только частично (пропущено записей: {_1}): панель «Переменные» показывает остальные @msg the file's variable library couldn't be read: the Variables panel doesn't list it не удалось прочитать библиотеку переменных файла: панель «Переменные» её не показывает @msg a variable of unknown kind can't be bound to objects переменную неизвестного вида нельзя связать с объектами diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 85e2cbb645..babde2822c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5692,6 +5692,7 @@ swatch Yellow Green Gulgrön Effect Gallery Effektgalleri Filters Filter Select artwork to apply effects Välj grafik för att tillämpa effekter +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables alla filens variabelbindningar lästes inte (överhoppade bindningar: {_1}): de objekten är inte bundna till sina variabler @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest filens variabelbibliotek lästes bara delvis (överhoppade poster: {_1}): panelen Variabler visar resten @msg the file's variable library couldn't be read: the Variables panel doesn't list it filens variabelbibliotek kunde inte läsas: panelen Variabler visar det inte @msg a variable of unknown kind can't be bound to objects en variabel av okänd typ kan inte kopplas till objekt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 1e35746785..f2850ce927 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5436,6 +5436,7 @@ theme Appearance Görünüm @msg its zlib compression is damaged zlib sıkıştırması hasarlı @msg its Zstandard compression is damaged Zstandard sıkıştırması hasarlı @msg it decompresses to more than {_1} MB açıldığında {_1} MB'tan fazla alan kaplıyor +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables dosyanın değişken bağlantılarının tümü okunmadı (atlanan bağlantılar: {_1}): bu nesneler değişkenlerine bağlı değil @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest dosyanın değişken kitaplığı yalnızca kısmen okundu (atlanan girdiler: {_1}): Değişkenler paneli kalanları listeliyor @msg the file's variable library couldn't be read: the Variables panel doesn't list it dosyanın değişken kitaplığı okunamadı: Değişkenler paneli onu listelemiyor @msg a variable of unknown kind can't be bound to objects türü bilinmeyen bir değişken nesnelere bağlanamaz diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f0ba143cca..21b77da4be 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5264,6 +5264,7 @@ lighting Light Світло Effect Gallery Галерея ефектів Filters Фільтри Select artwork to apply effects Виберіть графіку, щоб застосувати ефекти +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables прочитано не всі прив’язки змінних файлу (пропущено прив’язок: {_1}): ці об’єкти не прив’язано до їхніх змінних @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest бібліотеку змінних файлу прочитано лише частково (пропущено записів: {_1}): панель «Змінні» показує решту @msg the file's variable library couldn't be read: the Variables panel doesn't list it не вдалося прочитати бібліотеку змінних файлу: панель «Змінні» її не показує @msg a variable of unknown kind can't be bound to objects змінну невідомого виду не можна прив’язати до об’єктів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 436fe20d0e..c456663aa1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5265,6 +5265,7 @@ theme Appearance Giao diện Effect Gallery Thư viện hiệu ứng Filters Bộ lọc Select artwork to apply effects Chọn đồ họa để áp dụng hiệu ứng +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables không phải mọi liên kết biến số của tệp đều được đọc (liên kết đã bỏ qua: {_1}): các đối tượng đó không được liên kết với biến số của chúng @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest thư viện biến số của tệp chỉ được đọc một phần (mục đã bỏ qua: {_1}): bảng Biến liệt kê phần còn lại @msg the file's variable library couldn't be read: the Variables panel doesn't list it không thể đọc thư viện biến số của tệp: bảng Biến không liệt kê nó @msg a variable of unknown kind can't be bound to objects không thể liên kết biến thuộc loại không xác định với đối tượng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2131de9822..a55c343f25 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5507,6 +5507,7 @@ lighting Light 光源 Effect Gallery 效果库 Filters 滤镜 Select artwork to apply effects 选择要应用效果的图稿 +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables 未读取文件的全部变量绑定(跳过的绑定:{_1}):这些对象未绑定到其变量 @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest 文件的变量库只读取了一部分(跳过的条目:{_1}):“变量”面板列出其余部分 @msg the file's variable library couldn't be read: the Variables panel doesn't list it 无法读取文件的变量库:“变量”面板不会列出它 @msg a variable of unknown kind can't be bound to objects 类型未知的变量不能绑定到对象 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d2ce0501e5..3eab26ac64 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2050,6 +2050,7 @@ file-filter Templates 範本 @msg the art on them differs from the page's in {_1}% of it: they come from its editing data all the same 其上的圖稿與頁面的圖稿有 {_1}% 不同:仍從其編輯資料匯入 @msg the file's layers weren't read ({_1}): it comes in as its page, in one layer 未讀取檔案的圖層 ({_1}):檔案以其頁面匯入,位於單一圖層中 @msg the file's layers weren't read from its editing data ({_1}): they come from its PDF part 未從檔案的編輯資料讀取圖層 ({_1}):圖層來自其 PDF 部分 +@msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables 未讀取檔案的全部變數繫結 (略過的繫結:{_1}):這些物件未繫結至其變數 @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest 只讀取了檔案的部分變數資料庫 (略過的項目:{_1}):「變數」面板會列出其餘部分 @msg the file's variable library couldn't be read: the Variables panel doesn't list it 無法讀取檔案的變數資料庫:「變數」面板不會列出它 @msg a variable of unknown kind can't be bound to objects 種類不明的變數無法繫結至物件 diff --git a/docs/mcp.md b/docs/mcp.md index 53a1b552d2..398e0fdbdc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1705,7 +1705,9 @@ already walks Image Trace. Short agent entry points: `variable.bind`, `variable.unbind` and the `dataset.*` commands still run (except a `dataset.import` whose header would define a variable, below), and `variable.list` reports `locked`. A variable that an opened `.ai` declares without a kind VectorCraft reads is listed with `kind: "unknown"`: it takes no values, and `variable.bind` - refuses it. + refuses it. When an opened `.ai`'s layers are read, the objects it binds to its text, visibility and image + variables come in bound when they are of the variable's kind, locked and hidden objects included, and + `variable.list` counts them in `bindings`. - Data sets: `dataset.list`, `dataset.new {name, values?}`, `dataset.set {name, newName?, values?}` (`newName` also renames the row, in the same undo step; Edit Data Set's Name field sends it), `dataset.rename`, `dataset.delete`, `dataset.capture`, `dataset.update`, `dataset.select {name}`, `dataset.next` / diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 200dc5c634..57e3defab3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1147,7 +1147,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` or EPS opened from its editing data, where a layer's or group's drawn look (an effect can be attached to a group or a layer, [Vector and raster effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/vector-and-raster-effects.html)) draws a copy of art with type, the import puts the page's type that lies over the copy's other art into the copy's group, instead of giving it to other text objects by painting order. Type beside the copy's art, and every copy's type in a file past the import's text-object limits, still goes by painting order. Without a page, such a copy has no type, and no warning counts it as left out. How the page's type is matched with a copy is VectorCraft's own rule (`crates/eps/src/import/tests_native.rs`). A `.ai` opened from its editing data keeps Effect › Pathfinder on a group with no fills or strokes of its own as a live effect, with the group's members editable: Add, shown or hidden, in its order among the group's effects. The other operations, Pathfinder Options values other than the ones the reader accepts, and the effect on a path, on type, or on a fill or stroke open as the drawn look (`crates/eps/src/import/ai/style.rs`, `pathfinder_effect`). PDF text opens with every glyph where the file draws it (#722): the font's kerning or none, whichever the file followed, word and character spacing, `TJ` adjustments and horizontal scaling kept per character as tracking, text rise as baseline shift within its line, vertical glyphs narrower than an em centred on their column (`/W2`, `/W`, `/DW`), justified text boxes with word spacing back as justified area type (`tests_text_placement`, fixtures written from ISO 32000-1 §9). - A `.ai` or PDF whose editing data holds a readable variable library opens with its variable definitions, data-set rows, text, visibility and linked-file values, active row and lock in the Variables panel, whether its layers are read or it comes in as its PDF part; graph values and malformed entries are skipped with a note, and objects aren't bound yet (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). + A `.ai` or PDF whose editing data holds a readable variable library opens with its variable definitions, data-set rows, text, visibility and linked-file values, active row and lock in the Variables panel, whether its layers are read or it comes in as its PDF part; graph values and malformed entries are skipped with a note. With its layers read, the objects its text, visibility and image variables are bound to (type for a text variable, any object for a visibility variable, a linked image for an image variable, found by their XML ids) come in bound, so selecting a data set changes them; locked and hidden objects, objects in a locked or hidden layer or group and objects on a locked artboard keep their bindings, and a data set leaves the locked ones as they are. Bindings whose object didn't come in or is of another kind are skipped with a note, as are graph bindings and every binding of a file that comes in as its PDF part (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data keeps each artboard's center mark, cross hairs, video safe areas and video ruler pixel aspect ratio, and the file's Document Raster Effects Settings; the author comes from the header's `%%For` (the editing data's, else an EPS's own) when the file's File Info gives none, the header's custom colors that no swatch has come in as spot swatches, a named color the file defines takes the place of a default swatch of that name when the file has no palette, and an older file's `%%TemplateBox` places its artboard. A value of another type or out of range keeps its default (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` opened from its editing data opens its Objects on Path groups live, with their path, their objects in order along it, Pivot and Rotate, and their art where the file draws it; a group whose spacing has been dragged, or with options an Objects on Path group doesn't hold, opens as a plain group (`crates/eps/src/import/ai/tests.rs`). A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art. A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. Pattern brushes and brushes that can't be read are left out with a note; brushed paths still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). From 1d459796ad67d3f49330fd9a622ad097e41b1546 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:28:25 -0800 Subject: [PATCH 013/482] i18n: term checks match whole words and the Info row's Tracking label The Leading check now matches each word of the Leading field as a whole word in languages that separate words with spaces, so a longer word such as "liderlik" no longer stands in for "lider". Chinese, Japanese and other unspaced scripts keep substring matching. The Info row check now looks for the whole Tracking name in the label in front of {tracking}, after taking out a Kerning or Leading name that contains it. A word of the name found in the Size label, or a Kerning label that contains the Tracking name, no longer passes. The Czech Auto Leading row uses the singular "proklad", as the Leading field does. --- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/tests.rs | 54 +++++++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 67d5709b77..3d287457e5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5657,7 +5657,7 @@ mark-style Japanese Japonské Word Spacing: Mezery mezi slovy: Letter Spacing: Mezery mezi písmeny: Glyph Scaling: Změna velikosti glyfů: - Auto Leading: Automatické proklady: + Auto Leading: Automatický proklad: Single Word Justification: Zarovnání jednoho slova: Full Justify Zarovnat do bloku Minimum must not exceed Desired, nor Desired Maximum. Minimum nesmí překročit požadovanou hodnotu ani požadovaná hodnota maximum. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index bb2de38d61..2fe5cb4aac 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -524,9 +524,36 @@ fn zh_hans_is_simplified_and_mainland() { assert!(bad.is_empty(), "in zh-hans.tsv:\n{}", bad.join("\n")); } +/// Whether `text` holds `term`. In a script that separates words with spaces the term must stand as +/// whole words, so "liderlik" does not hold "lider"; in Chinese, Japanese, Thai, Lao, Khmer and +/// Myanmar text any occurrence counts. +fn contains_term(text: &str, term: &str) -> bool { + let unspaced = |c: char| matches!(c as u32, 0x0E00..=0x0EFF | 0x1000..=0x109F | 0x1780..=0x17FF | 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF); + if term.chars().any(unspaced) { + return text.contains(term); + } + text.match_indices(term).any(|(at, m)| { + !text[..at].chars().next_back().is_some_and(char::is_alphanumeric) && !text[at + m.len()..].chars().next().is_some_and(char::is_alphanumeric) + }) +} + +#[test] +fn contains_term_matches_whole_words_where_words_are_spaced() { + assert!(contains_term("tepeden tepeye lider", "lider")); + assert!(contains_term("boyut/lider:", "lider")); + assert!(contains_term("réinitialiser l’approche", "approche")); + assert!(!contains_term("tepeden tepeye liderlik", "lider")); + assert!(!contains_term("automatické proklady:", "proklad")); + assert!(contains_term("kích thước: giãn chữ:", "giãn chữ")); + assert!(!contains_term("kích thước chữ: giãn:", "giãn chữ")); + assert!(contains_term("自動行送り:", "行送り")); + assert!(contains_term("大小:字距微調:", "字距")); +} + /// Each catalog names leading with one term: every word of the Character panel's Leading field -/// (the text before " (", ignoring case) appears in the Auto Leading, Size/Leading, Top-to-Top -/// Leading and Bottom-to-Bottom Leading rows outside their placeholders. +/// (the text before " (", ignoring case) appears as a whole word (see [`contains_term`]) in the +/// Auto Leading, Size/Leading, Top-to-Top Leading and Bottom-to-Bottom Leading rows outside their +/// placeholders. /// A catalog without the Leading row, or without one of the others, is skipped for that check. #[test] fn leading_term_agrees_within_each_catalog() { @@ -540,7 +567,7 @@ fn leading_term_agrees_within_each_catalog() { for src in ["Auto Leading:", "Size/Leading", "Top-to-Top Leading", "Bottom-to-Bottom Leading"] { if let Some(text) = row(src) { let bare = placeholders(&text).iter().fold(text.clone(), |t, p| t.replace(&format!("{{{p}}}"), " ")); - for word in leading.split_whitespace().filter(|w| !bare.contains(*w)) { + for word in leading.split_whitespace().filter(|w| !contains_term(&bare, w)) { bad.push(format!("{}: {src:?} → {text:?} lacks {word:?} from the Leading field {leading:?}", l.code)); } } @@ -576,10 +603,12 @@ fn no_translated_word_mixes_latin_cyrillic_and_greek_letters() { } /// Each catalog gives the Character panel's Kerning, Leading and Tracking fields three different -/// names, every word of the Tracking and Kerning names appears in the Reset Tracking and Kerning -/// row, and every word of the Tracking name appears in the Info panel's type line outside its -/// placeholders (ignoring case). Each word is matched once, the longer name first, so a name -/// that contains the other name does not count for both. +/// names, and every word of the Tracking and Kerning names appears in the Reset Tracking and +/// Kerning row (ignoring case). Each word is matched once, the longer name first, so a name that +/// contains the other name does not count for both. The Info panel's type line labels +/// `{tracking}` with the whole Tracking name: the text between the placeholder before it and +/// `{tracking}` holds the name (see [`contains_term`]) once any Kerning or Leading name that +/// contains it has been taken out. /// A catalog without one of these rows is skipped for the checks that need it. #[test] fn character_panel_terms_agree_within_each_catalog() { @@ -613,7 +642,16 @@ fn character_panel_terms_agree_within_each_catalog() { } }; uses("Reset Tracking and Kerning", &[&tracking, &kerning]); - uses("Size: {size} Tracking: {tracking}", &[&tracking]); + if let (Some(text), Some(tracking)) = (row("Size: {size} Tracking: {tracking}"), &tracking) { + let before = text.split("{tracking}").next().unwrap_or_default(); + let mut label = before.rsplit('}').next().unwrap_or_default().to_string(); + for other in [&kerning, &leading].into_iter().flatten().filter(|o| *o != tracking && o.contains(tracking.as_str())) { + label = label.replace(other.as_str(), " "); + } + if !contains_term(&label, tracking) { + bad.push(format!("{}: the Info row {text:?} labels {{tracking}} {label:?}, not the field {tracking:?}", l.code)); + } + } } assert!(bad.is_empty(), "Character panel terms that disagree:\n{}", bad.join("\n")); } From 595db10900d12fa3e1dd4d86fff2947593285c0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:17:20 -0800 Subject: [PATCH 014/482] Type: refuse negative or fractional byte offsets in text commands text.startList read a negative or fractional `at` as the end of the text, so it could remove a typed list marker there and start a list. The `start` and `end` of text.editRange, text.getRange, text.setRangeStyle and the type shortcut commands given an `id` read such values as the start or end of the text. These now return "`at` must be a whole number" (naming the key) and change nothing. Omitted or null keys keep their defaults, and 2.0 is read as 2. --- crates/engine/src/cmd/textedit.rs | 21 +++++++++++++++------ crates/engine/src/tests/textedit.rs | 27 +++++++++++++++++++++++++++ docs/mcp.md | 5 +++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index f0a331b0a7..03943029ea 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -7,6 +7,7 @@ use vectorcraft_doc::{Appearance, CharStyle, Node, NodeId, NodeKind, TextKind, T use vectorcraft_geom::{Affine, Point, Vec2}; use vectorcraft_text::edit; +use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ @@ -233,12 +234,21 @@ fn byte_param(p: &Value, k: &str) -> Option { p.get(k).and_then(Value::as_u64).map(index) } +/// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any +/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. +fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result { + match p.get(k) { + None | Some(Value::Null) => Ok(default), + Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)), + } +} + /// The bytes `start..end` of `p` in text of `len` bytes, clamped and ordered (without them, all of -/// it). A `start` or `end` that is not a number or null, such as `"2"`, is an error. +/// it). A `start` or `end` that is not a whole number of at least 0 or null, such as `"2"`, `-1` +/// or `1.5`, is an error. fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> { - check_numbers(p, &["start", "end"], cmd)?; - let a = byte_param(p, "start").unwrap_or(0).min(len); - let b = byte_param(p, "end").unwrap_or(len).min(len); + let a = offset_or(p, "start", 0, cmd)?.min(len); + let b = offset_or(p, "end", len, cmd)?.min(len); Ok((a.min(b), a.max(b))) } @@ -310,10 +320,9 @@ fn clear_param(s: &Session, p: &Value, id: NodeId, c: &str) -> Result Result { const C: &str = "text.startList"; let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?; - check_numbers(p, &["at"], C)?; let t = text_ref(s, id)?; let len = edit::runs_len(&t.runs); - let at = byte_param(p, "at").unwrap_or(len).min(len); + let at = offset_or(p, "at", len, C)?.min(len); let Some((start, list)) = t.typed_list_at(at) else { return Ok(json!({"id": id.0, "started": false, "caret": at})); }; diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 9e346bf657..fa73e9d50c 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -1200,6 +1200,33 @@ fn start_list_command_removes_the_typed_characters_and_starts_the_list() { assert!(s.execute("text.startList", &json!({"at": 3})).is_err(), "id required"); } +/// A byte offset given as a negative or fractional number is an error, not the end of the text +/// (`at`) or its start or end (`start`, `end`), and the text is left as it was. Null keeps the default. +#[test] +fn byte_offsets_that_are_not_whole_numbers_are_refused() { + let mut s = session(); + let id = text(&mut s, "x\n# "); + for at in [json!(-1), json!(1.5)] { + let e = s.execute("text.startList", &json!({"id": id.0, "at": at})).unwrap_err().to_string(); + assert!(e.contains("`at`"), "{e}"); + } + assert_eq!(obj(&s, id).plain_text(), "x\n# ", "no list was started"); + assert_eq!(s.execute("text.startList", &json!({"id": id.0, "at": null})).unwrap()["started"], json!(true)); + let id = text(&mut s, "Hello"); + for (cmd, p, key) in [ + ("text.getRange", json!({"id": id.0, "start": -1, "end": 2}), "start"), + ("text.getRange", json!({"id": id.0, "start": 1, "end": 2.5}), "end"), + ("text.editRange", json!({"id": id.0, "start": 1.5, "end": 2, "insert": "!"}), "start"), + ("text.editRange", json!({"id": id.0, "start": 1, "end": -2, "insert": "!"}), "end"), + ("text.setRangeStyle", json!({"id": id.0, "start": 0.5, "size": 30}), "start"), + ] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains(&format!("`{key}`")), "{cmd} {p}: {e}"); + } + assert_eq!(obj(&s, id).plain_text(), "Hello"); + assert_eq!(s.execute("text.getRange", &json!({"id": id.0, "start": 1.0, "end": null})).unwrap()["text"], json!("ello")); +} + /// #1881: a Cmd/Ctrl drag while typing (the Selection tool lent to the Type tool) moves the type /// and keeps what was typed, and typing goes on after it. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 398e0fdbdc..e50412eb51 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1207,6 +1207,11 @@ and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gra `width` and `tolerance` in `livePaint.strokeEdge`. A null is read as a key left out. A gradient stop that names a swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. +A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in +`text.editRange`, `text.getRange`, `text.setRangeStyle` and the `type.step`, `type.size.*`, `type.resetTracking` and +`type.resetHorizontalScale` commands given an `id`, refuse a negative or fractional number with +`` `at` must be a whole number ``, naming the key, and change nothing. `2.0` is read as `2`, and a null as the key left out. + A step can use an earlier step's result, in `run` as in the `command_batch` tool. A parameter string that is exactly `$N` or `$N.path` takes that value from the result of step `N` (counting from 0, in the order they ran; `run --in`'s open isn't a step), and `$last…` from the step before. A path goes into objects by key and arrays by index: From e3a55b97fddf01755386e8850e49b18fafa4ad12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:30:31 -0800 Subject: [PATCH 015/482] Type: Text Tweaker leaves byte offsets to range_of Remove Text Tweaker's own start and end check: range_of already refuses a bad offset given with an id, and like the other type commands Text Tweaker now ignores start and end without one. The test's "2" case gets an id so it still reaches the check, and docs/mcp.md lists addon.type.textTweaker with the commands that refuse such offsets. --- crates/engine/src/cmd/addons/typetools.rs | 6 ------ crates/engine/src/cmd/addons/typetools/tests.rs | 2 +- docs/mcp.md | 4 ++-- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 29ca6f6bfd..320dce6b9f 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -89,12 +89,6 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { let mut rng = Rng::new(whole_or(p, "seed", 0, C)?); let skip = switch_or(p, "skipSpaces", true, C)?; let setup = s.doc()?.doc.setup.clone(); - // A range given as anything but whole bytes is refused, not read as all of the text. - for k in ["start", "end"] { - if p.get(k).is_some_and(|v| !v.is_null() && v.as_u64().is_none()) { - return Err(bad(C, format!("`{k}` must be a whole number of bytes"))); - } - } // At a caret, all of the object's text. let ranges = type_ranges(s, p, C, |text, _| Some((0, text.len())))?; // Each object's changed characters: (byte, its change), worked out before the edit. diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index fec04f9c63..6c56f67694 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -196,7 +196,7 @@ fn bad_params_are_refused_without_a_change() { json!({"ids": [999_999]}), json!({"id": id.0, "start": -1}), json!({"id": id.0, "start": 1, "end": 1.5}), - json!({"end": "2"}), + json!({"id": id.0, "end": "2"}), ] { assert!(s.execute(C, &p).is_err(), "{p}"); assert_eq!(s.doc().unwrap().doc, before, "{p}"); diff --git a/docs/mcp.md b/docs/mcp.md index e50412eb51..7c0499a063 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1208,8 +1208,8 @@ and `amount` in `color.harmony`; `angle` in `paint.editGradient` and in the `gra swatch refuses a `tint` that is not a number with `` stop 0: `tint` must be a number ``. A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in -`text.editRange`, `text.getRange`, `text.setRangeStyle` and the `type.step`, `type.size.*`, `type.resetTracking` and -`type.resetHorizontalScale` commands given an `id`, refuse a negative or fractional number with +`text.editRange`, `text.getRange`, `text.setRangeStyle` and the `type.step`, `type.size.*`, `type.resetTracking`, +`type.resetHorizontalScale` and `addon.type.textTweaker` commands given an `id`, refuse a negative or fractional number with `` `at` must be a whole number ``, naming the key, and change nothing. `2.0` is read as `2`, and a null as the key left out. A step can use an earlier step's result, in `run` as in the `command_batch` tool. A parameter string that is exactly From af604625b3ee8e980ca102168b0f012724d1ca7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:21:06 -0800 Subject: [PATCH 016/482] Panels: showing a hidden floating group returns its window's panels `window.panel` on a panel whose group was hidden returned the whole layout and every floating panel in every window. It now returns `{floating}` with the panels of the restored panel's window, as it does when it shows a panel that already floats. --- crates/ui-egui/src/panel_docking.rs | 9 +++++---- crates/ui-egui/src/panel_docking/tests.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 9d8c71538c..0deb2c3c0e 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -339,10 +339,11 @@ fn show_panel(app: &mut VectorcraftApp, params: &Value) -> Result if !layout.contains(&panel.to_string()) && !app.ui.docking_hidden.contains_key(panel) && crate::panels::library_panel::parse(panel).is_some() { return crate::panels::library_panel::float(app, panel); } - if app.ui.docking_hidden.contains_key(panel) { - return restore_hidden_group(app, panel); - } - let value = shared_command(app, "window.panel.activate", &json!({"panel": panel}))?; + let value = if app.ui.docking_hidden.contains_key(panel) { + restore_hidden_group(app, panel)? + } else { + shared_command(app, "window.panel.activate", &json!({"panel": panel}))? + }; let layout = layout_of(&app.ui); Ok(match floating_window(&layout, panel) { Some(window) => json!({"floating": window_panels(window)}), diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 2bae524dd8..f8287944be 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -612,6 +612,19 @@ fn f7_hides_and_restores_a_floating_tab_group() { assert!(showing(&h.app.ui, "layers")); } +#[test] +fn showing_a_hidden_floating_group_returns_its_window_panels() { + let mut h = Harness::new(); + h.app.run("window.panel.float", json!({"panel": "swatches"})).unwrap(); + h.app.run("window.panel.float", json!({"panel": "layers", "group": true})).unwrap(); + h.app.run("window.panel.activate", json!({"panel": "layers"})).unwrap(); + h.frame(vec![]); + h.press(egui::Key::F7, egui::Modifiers::NONE); + assert!(floating_window(&h.layout(), "layers").is_none()); + let reply = h.app.run("window.panel", json!({"panel": "layers"})).unwrap(); + assert_eq!(reply, json!({"floating": ["properties", "layers", "libraries"]}), "only the restored window's panels"); +} + #[test] fn f7_toggles_a_multi_tab_icon_flyout() { let mut h = Harness::new(); From 676cc0ee8e54580d369e18b5bb5217ae8b274633 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:31:38 -0800 Subject: [PATCH 017/482] Render: a long stroke is outlined only near the view after an edit The renderer outlined the whole stroke of an edited path on every frame, so dragging one anchor of a path with many anchors re-outlined every segment. A stroke line of more than 1,024 elements without dashes or a width profile is now outlined only for the segments within the stroke's reach of the view, inflated by the view's own size on each side. The cached outline keeps that region, and a frame outside it outlines the stroke again. Closed subpaths that a wide stroke crosses over stay whole, and a cut closed subpath is walked from a removed segment so no cut lands where it starts and ends. The pixels are the same. At 1600 x 1200, the frame after one anchor moves takes 28 to 30 ms instead of 103 ms on an open path of 200,000 anchors, and 10 ms instead of 30 ms on a closed path of 50,000 anchors (the new anchor_bench example: cargo run --release -p vectorcraft-engine --example anchor_bench). --- crates/engine/examples/anchor_bench.rs | 320 +++++++++++++++++++++++++ crates/render/src/frame.rs | 5 +- crates/render/src/renderer.rs | 3 + crates/render/src/renderer/paint.rs | 109 ++++++++- crates/render/src/tests.rs | 1 + crates/render/src/tests/longstroke.rs | 166 +++++++++++++ docs/target-app-parity.md | 1 + 7 files changed, 602 insertions(+), 3 deletions(-) create mode 100644 crates/engine/examples/anchor_bench.rs create mode 100644 crates/render/src/tests/longstroke.rs diff --git a/crates/engine/examples/anchor_bench.rs b/crates/engine/examples/anchor_bench.rs new file mode 100644 index 0000000000..a460602202 --- /dev/null +++ b/crates/engine/examples/anchor_bench.rs @@ -0,0 +1,320 @@ +//! `cargo run --release -p vectorcraft-engine --example anchor_bench` — wall time of the engine +//! steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of +//! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors. +//! `ITERS` sets the runs per step (default 7); each row is the median in ms. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_engine::tools::{Mods, PointerEvent, PointerKind}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Affine, Anchor, PathData, Point, SubPath, Vec2}; +use vectorcraft_render::{RenderOptions, Renderer}; + +/// Anchors are 10 pt apart and their handles 3 pt long, along the path. +const STEP: f64 = 10.0; +const HANDLE: f64 = 3.0; + +/// A test document: its paths, an anchor to hover, click and drag, a point on a segment, and a +/// marquee from an empty point over about 10,000 anchors. +struct Shape { + name: &'static str, + doc: Document, + ids: Vec, + anchor: (NodeId, usize), + segment: Point, + marquee: (Point, Point), +} + +/// A closed path of `n` smooth anchors around `center`. +fn circle(center: Point, n: usize) -> PathData { + let r = n as f64 * STEP / std::f64::consts::TAU; + let anchors = (0..n) + .map(|i| { + let t = i as f64 / n as f64 * std::f64::consts::TAU; + let p = center + Vec2::new(r * t.cos(), r * t.sin()); + Anchor::smooth(p, p + Vec2::new(-t.sin(), t.cos()) * HANDLE) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + +fn add(doc: &mut Document, path: PathData) -> NodeId { + let l = doc.layers.first().map(|l| l.id); + let id = doc.alloc_id(); + doc.insert(l, usize::MAX, Node::path(id, path, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0))).unwrap(); + id +} + +fn one_outline() -> Shape { + let n = 50_000; + let mut doc = Document::new(1600.0, 1200.0); + let id = add(&mut doc, circle(Point::ZERO, n)); + let r = n as f64 * STEP / std::f64::consts::TAU; + let a = 72f64.to_radians(); + let mid = (n / 2) as f64 / n as f64 * std::f64::consts::TAU; + let next = (n / 2 + 1) as f64 / n as f64 * std::f64::consts::TAU; + let segment = Point::new(r * (mid.cos() + next.cos()) / 2.0, r * (mid.sin() + next.sin()) / 2.0); + Shape { + name: "one closed path, 50,000 anchors", + doc, + ids: vec![id], + anchor: (id, n / 2), + segment, + marquee: (Point::new(r + 50.0, -5.0), Point::new(r * a.cos() - 1.0, r * a.sin() + 1.0)), + } +} + +fn many_paths() -> Shape { + let mut doc = Document::new(1600.0, 1200.0); + let ids: Vec = + (0..2000).map(|i| add(&mut doc, circle(Point::new((i % 50) as f64 * 200.0 + 100.0, (i / 50) as f64 * 200.0 + 100.0), 50))).collect(); + let r = 50.0 * STEP / std::f64::consts::TAU; + // Path 1,025 (row 20, column 25), its anchors 0 and 1. + let c = Point::new(25.0 * 200.0 + 100.0, 20.0 * 200.0 + 100.0); + let t = std::f64::consts::TAU / 50.0; + let segment = c + Vec2::new(r * (1.0 + t.cos()) / 2.0, r * t.sin() / 2.0); + Shape { + name: "2,000 closed paths, 50 anchors each", + doc, + anchor: (ids[1025], 0), + ids, + segment, + marquee: (Point::ZERO, Point::new(10_000.0, 800.0)), + } +} + +fn long_open_path() -> Shape { + let n = 200_000; + let mut doc = Document::new(1600.0, 1200.0); + let anchors = (0..n) + .map(|i| { + let p = Point::new(i as f64 * STEP, 0.0); + Anchor::smooth(p, p + Vec2::new(HANDLE, 0.0)) + }) + .collect(); + let id = add(&mut doc, PathData::single(SubPath::new(anchors, false))); + Shape { + name: "one open path, 200,000 anchors", + doc, + ids: vec![id], + anchor: (id, n / 2), + segment: Point::new((n / 2) as f64 * STEP + STEP / 2.0, 0.0), + marquee: (Point::new(-5.0, -20.0), Point::new(99_995.0, 30.0)), + } +} + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +fn time(mut f: impl FnMut()) -> f64 { + median( + (0..iters()) + .map(|_| { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(), + ) +} + +fn ev(kind: PointerKind, p: Point) -> PointerEvent { + PointerEvent::new(kind, p.x, p.y) +} + +fn exec(s: &mut Session, cmd: &str, p: Value) { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")); +} + +fn anchor_at(s: &Session, (id, ai): (NodeId, usize)) -> Anchor { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors[ai] +} + +/// The anchors selected: those direct-selected, and every anchor of a path selected whole. +fn selected_anchors(s: &Session) -> usize { + let st = s.doc().unwrap(); + let count = |id: &NodeId| st.doc.node(*id).and_then(|n| n.path_data()).map_or(0, |pd| pd.anchors().count()); + st.selection.objects.iter().map(|id| st.selection.partial(*id).map_or_else(|| count(id), |set| set.len())).sum() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn row(name: &str, ms: f64) { + println!(" {name:<58} {ms:>10.3} ms"); +} + +/// Select `count` anchors: the first ones of the first path, or the first anchors of as many +/// paths as needed. +fn select_count(s: &mut Session, shape: &Shape, count: usize) { + exec(s, "select.none", json!({})); + let mut left = count; + for id in &shape.ids { + if left == 0 { + break; + } + let n = s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len(); + let take = left.min(n); + let refs: Vec<[usize; 2]> = (0..take).map(|i| [0, i]).collect(); + exec(s, "select.anchors", json!({"id": id.0, "anchors": refs, "mode": "add"})); + left -= take; + } +} + +fn bench(shape: Shape) { + println!("{}", shape.name); + let view = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + let mut s = Session::new(); + s.add_document(shape.doc.clone(), None); + s.select_tool("directSelection", view).unwrap(); + let a = anchor_at(&s, shape.anchor).p; + let none = Mods::default(); + { + let doc = s.doc().unwrap().doc.clone(); + let opt = vectorcraft_doc::hit::HitOptions { tol: 3.0, clip_outlines: true, ..Default::default() }; + row("hit test at an anchor", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, a, opt))))); + row("hit test at a segment", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment, opt))))); + row("hit test beside the path", time(|| drop(black_box(vectorcraft_doc::hit::hit_test(&doc, shape.segment + Vec2::new(0.0, 40.0), opt))))); + } + + // Hover with nothing selected, then with one anchor of the path selected. + for selected in [false, true] { + if selected { + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + } + let what = if selected { "one anchor selected" } else { "nothing selected" }; + row(&format!("hover over an anchor, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, a), view).unwrap()))); + row(&format!("cursor over an anchor, {what}"), time(|| _ = black_box(s.cursor(a, none, view)))); + row(&format!("hover over a segment, {what}"), time(|| drop(s.pointer(&ev(PointerKind::Move, shape.segment), view).unwrap()))); + row(&format!("cursor over a segment, {what}"), time(|| _ = black_box(s.cursor(shape.segment, none, view)))); + } + + // A click that selects one anchor. + exec(&mut s, "select.none", json!({})); + row( + "click that selects one anchor", + time(|| { + s.pointer(&ev(PointerKind::Down, a), view).unwrap(); + s.pointer(&ev(PointerKind::Up, a), view).unwrap(); + }), + ); + assert_eq!(selected_anchors(&s), 1, "the click selects one anchor"); + + // One anchor dragged: each pointer move, then the release. + let undo = undo_len(&s); + s.pointer(&ev(PointerKind::Down, a), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, 20.0)), view).unwrap(); + let mut y = 20.0; + row( + "anchor drag, one pointer move", + time(|| { + y += 1.0; + s.pointer(&ev(PointerKind::Drag, a + Vec2::new(0.0, y)), view).unwrap(); + }), + ); + let t = Instant::now(); + s.pointer(&ev(PointerKind::Up, a + Vec2::new(0.0, y)), view).unwrap(); + row("anchor drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(undo_len(&s), undo + 1, "the anchor drag records one step"); + exec(&mut s, "edit.undo", json!({})); + + // The selected anchor's outgoing handle dragged. + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let h = anchor_at(&s, shape.anchor).h_out; + let undo = undo_len(&s); + s.pointer(&ev(PointerKind::Down, h), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, 20.0)), view).unwrap(); + let mut y = 20.0; + row( + "handle drag, one pointer move", + time(|| { + y += 1.0; + s.pointer(&ev(PointerKind::Drag, h + Vec2::new(0.0, y)), view).unwrap(); + }), + ); + let t = Instant::now(); + s.pointer(&ev(PointerKind::Up, h + Vec2::new(0.0, y)), view).unwrap(); + row("handle drag, release (commit)", t.elapsed().as_secs_f64() * 1000.0); + assert_eq!(undo_len(&s), undo + 1, "the handle drag records one step"); + assert_eq!(anchor_at(&s, shape.anchor).p, a, "the handle drag leaves the anchor in place"); + exec(&mut s, "edit.undo", json!({})); + + // A marquee over about 10,000 anchors. + let (m0, m1) = shape.marquee; + let ms = time(|| { + exec(&mut s, "select.none", json!({})); + s.pointer(&ev(PointerKind::Down, m0), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, m0.lerp(m1, 0.5)), view).unwrap(); + s.pointer(&ev(PointerKind::Drag, m1), view).unwrap(); + s.pointer(&ev(PointerKind::Up, m1), view).unwrap(); + }); + row(&format!("marquee over {} anchors (press to release)", selected_anchors(&s)), ms); + + // Select All with Direct Selection. + row("Select All", time(|| exec(&mut s, "select.all", json!({})))); + row("tool overlays, everything selected", time(|| drop(s.overlays(view)))); + + // Nudges of 1, 1,000 and every anchor, and Undo and Redo of each. + let total: usize = shape.ids.iter().map(|id| s.doc().unwrap().doc.node(*id).unwrap().path_data().unwrap().subpaths[0].anchors.len()).sum(); + for count in [1, 1000, total] { + select_count(&mut s, &shape, count); + row(&format!("nudge of {count} anchors"), time(|| exec(&mut s, "path.moveAnchors", json!({"dx": 1, "dy": 0})))); + row(&format!("undo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.undo", json!({})))); + row(&format!("redo of a nudge of {count} anchors"), time(|| exec(&mut s, "edit.redo", json!({})))); + } + + // The render of the document after one anchor moves (the renderer warm). + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let opts = RenderOptions::default(); + let mut r = Renderer::new(); + let at = Affine::translate(Vec2::new(800.0 - a.x, 600.0 - a.y)); + r.render(&s.doc().unwrap().doc, 1600, 1200, at, &opts); + let ms = median( + (0..iters()) + .map(|_| { + exec(&mut s, "path.moveAnchors", json!({"dx": 0, "dy": 1})); + let doc = s.doc().unwrap().doc.clone(); + let t = Instant::now(); + drop(r.render(&doc, 1600, 1200, at, &opts)); + t.elapsed().as_secs_f64() * 1000.0 + }) + .collect(), + ); + row("render 1600x1200 around the anchor after it moves", ms); + let doc = s.doc().unwrap().doc.clone(); + row("render 1600x1200 around the anchor, nothing changed", time(|| drop(r.render(&doc, 1600, 1200, at, &opts)))); + + // Delete of one anchor, undone after each run. + let ms = median( + (0..iters()) + .map(|_| { + exec(&mut s, "select.anchors", json!({"id": shape.anchor.0.0, "anchors": [[0, shape.anchor.1]], "mode": "set"})); + let t = Instant::now(); + exec(&mut s, "edit.clear", json!({})); + let ms = t.elapsed().as_secs_f64() * 1000.0; + exec(&mut s, "edit.undo", json!({})); + ms + }) + .collect(), + ); + row("Delete of one anchor", ms); +} + +fn main() { + bench(one_outline()); + bench(many_paths()); + bench(long_open_path()); +} diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index c01f27a3f8..0009957625 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -30,11 +30,14 @@ pub(crate) type PtrMap = HashMap, pub(crate) outline: Arc, pub(crate) stamp: u64, + pub(crate) crop: 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/renderer.rs b/crates/render/src/renderer.rs index db5ab2d6bc..a8a67f270e 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -23,6 +23,9 @@ mod nodes; mod paint; mod text; +#[cfg(test)] +pub(crate) use paint::{CROP_STROKES, crop_line}; + impl Renderer { pub fn new() -> Self { Self { diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index 3214ffe58d..e39f106e8c 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -253,14 +253,27 @@ impl Renderer { } let node = self.cur.clone().filter(|n| owns_stroke(n, st))?; let key = (self.stroke_owner(Arc::as_ptr(&node) as usize), st as *const StrokeLayer as usize, width.to_bits(), level); + let v = f.visible; + let holds = |crop: Option| crop.is_none_or(|r| r.x0 <= v.x0 && r.y0 <= v.y0 && r.x1 >= v.x1 && r.y1 >= v.y1); if let Some(e) = self.strokes.get_mut(&key) && Arc::ptr_eq(&e.node, &node) + && holds(e.crop) { e.stamp = self.stamp; return Some(e.outline.clone()); } - let outline = expand(); - self.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp }); + // A long stroke without dashes or a width profile is outlined only in and around the view, + // with a margin of the view's own size on each side ([`crop_line`]). + let region = v.inflate(v.width(), v.height()); + let tol = 2f64.powi(level); + 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.strokes.insert(key, StrokeEntry { node, outline: outline.clone(), stamp: self.stamp, crop }); Some(outline) } @@ -271,3 +284,95 @@ impl Renderer { if self.made_again { 0 } else { address } } } + +/// The stroke lines with more path elements than this are outlined in and around the view only +/// ([`crop_line`]). +pub(crate) const CROP_ELEMENTS: usize = 1024; + +#[cfg(test)] +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) }; +} + +fn crops() -> bool { + #[cfg(test)] + return CROP_STROKES.with(std::cell::Cell::get); + #[cfg(not(test))] + true +} + +/// How far stroke `st` at `width` can paint from its path, at a join or a cap, with two output +/// pixels (`px`) and the outline's tolerance `tol` added. +pub(crate) fn crop_reach(st: &StrokeLayer, width: f64, px: f64, tol: f64) -> f64 { + let corner = if st.join == vectorcraft_doc::LineJoin::Miter { st.miter_limit.max(std::f64::consts::SQRT_2) } else { std::f64::consts::SQRT_2 }; + width / 2.0 * corner + 2.0 * px + tol +} + +/// The stroke line `line` without the segments whose control points' box lies more than `reach` +/// from `region`, for outlining a stroke of `width` that is drawn only in `region`. A subpath that +/// loses some of its segments is replaced by its runs of kept segments, each an open subpath; a +/// closed one is walked from a removed segment, so that a run passes through the point where it +/// starts and ends. A closed subpath that a stroke of `width` can cross over (`width` at least the +/// smaller side of its bounds) keeps all its segments, and so does a subpath with no segments. +/// `None` when every segment is kept. +pub(crate) fn crop_line(line: &BezPath, region: Rect, reach: f64, width: f64) -> Option { + use kurbo::{PathEl, PathSeg}; + let near = region.inflate(reach, reach); + let keep = |s: &PathSeg| { + let pts: &[kurbo::Point] = match s { + PathSeg::Line(l) => &[l.p0, l.p1], + PathSeg::Quad(q) => &[q.p0, q.p1, q.p2], + PathSeg::Cubic(c) => &[c.p0, c.p1, c.p2, c.p3], + }; + // A coordinate that is not a number keeps the segment. + !(pts.iter().all(|p| p.x < near.x0) + || pts.iter().all(|p| p.x > near.x1) + || pts.iter().all(|p| p.y < near.y0) + || pts.iter().all(|p| p.y > near.y1)) + }; + let els = line.elements(); + let mut starts: Vec = els.iter().enumerate().filter(|(_, e)| matches!(e, PathEl::MoveTo(_))).map(|(i, _)| i).collect(); + if starts.first() != Some(&0) { + starts.insert(0, 0); + } + let mut out = BezPath::new(); + let mut cut = false; + for (k, &start) in starts.iter().enumerate() { + let Some(sub) = els.get(start..starts.get(k + 1).copied().unwrap_or(els.len())) else { continue }; + let segs = || kurbo::segments(sub.iter().copied()); + let (total, kept) = segs().fold((0, 0), |(t, n), s| (t + 1, n + usize::from(keep(&s)))); + let closed = sub.iter().any(|e| matches!(e, PathEl::ClosePath)); + let crosses = || { + let b = BezPath::from_vec(sub.to_vec()).bounding_box(); + width >= b.width().min(b.height()) + }; + if kept == total || closed && crosses() { + out.extend(sub.iter().copied()); + continue; + } + cut = true; + let first = if closed { segs().position(|s| !keep(&s)).map_or(0, |i| i + 1) } else { 0 }; + let mut open = false; + for s in segs().skip(first).chain(segs().take(first)) { + if !keep(&s) { + open = false; + continue; + } + if !open { + out.move_to(match s { + PathSeg::Line(l) => l.p0, + PathSeg::Quad(q) => q.p0, + PathSeg::Cubic(c) => c.p0, + }); + open = true; + } + match s { + PathSeg::Line(l) => out.line_to(l.p1), + PathSeg::Quad(q) => out.quad_to(q.p1, q.p2), + PathSeg::Cubic(c) => out.curve_to(c.p1, c.p2, c.p3), + } + } + } + cut.then_some(out) +} diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index d97de7a3c9..aa16311e0a 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -21,6 +21,7 @@ mod fxzoom; mod isolation; mod knockout; mod layeropts; +mod longstroke; mod memory; mod objectfx; mod placed_document; diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs new file mode 100644 index 0000000000..b8c7e7cf65 --- /dev/null +++ b/crates/render/src/tests/longstroke.rs @@ -0,0 +1,166 @@ +//! A long stroke without dashes or a width profile is outlined in and around the view only +//! (`crop_line`), and draws the same pixels as when it is outlined whole. + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, LineCap, LineJoin, Node, StrokeLayer}; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::renderer::{CROP_STROKES, crop_line}; +use crate::*; + +const SIZE: u32 = 200; + +/// A document holding `path` stroked with `st` and no fill. +fn doc(path: &BezPath, st: StrokeLayer) -> Document { + let mut d = Document::new(1000.0, 1000.0); + let n = Node::path(d.alloc_id(), PathData::from_bezpath(path), Appearance { items: vec![AppearanceItem::Stroke(st)], ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +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 +} + +/// 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() }) +} + +/// What a renderer that outlines every stroke whole draws. +fn whole(d: &Document, at: Point) -> Rendered { + CROP_STROKES.with(|c| c.set(false)); + let mut r = Renderer::new(); + let img = render(&mut r, d, at); + CROP_STROKES.with(|c| c.set(true)); + assert!(r.strokes.values().all(|e| e.crop.is_none()), "the reference outlines the stroke whole"); + img +} + +/// 3,000 anchors 8 pt apart, up and down by 30 pt, every third segment curved: sharp miter joins. +fn zigzag() -> 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..3000 { + 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 +} + +#[test] +fn a_long_stroke_draws_the_same_pixels_outlined_near_the_view() { + let mut inside = stroke(8.0, LineJoin::Round, LineCap::Butt); + inside.align = vectorcraft_doc::StrokeAlign::Inside; + // The ring starts at (5000, 0): the second view is on its start and end. + let cases = [ + ("zigzag, miter joins, square caps", doc(&zigzag(), stroke(6.0, LineJoin::Miter, LineCap::Square)), Point::new(12_000.0, 15.0), true), + ("ring, round joins", doc(&ring(4000, 5000.0), stroke(12.0, LineJoin::Round, LineCap::Round)), Point::new(0.0, 5000.0), true), + ("ring through its start, bevel joins", doc(&ring(4000, 5000.0), stroke(5.0, LineJoin::Bevel, LineCap::Butt)), Point::new(5000.0, 0.0), true), + ("ring, inside stroke", doc(&ring(4000, 5000.0), inside), Point::new(-5000.0, 0.0), true), + ]; + for (what, d, at, crops) in &cases { + let mut r = Renderer::new(); + let img = render(&mut r, d, *at); + assert_eq!(r.strokes.values().any(|e| e.crop.is_some()), *crops, "{what}: outlined near the view"); + assert!(img.pixels == whole(d, *at).pixels, "{what}: the same pixels as the whole outline"); + // A view inside the region kept around the first one reuses the outline; one beyond it + // outlines the stroke again. + for step in [Point::new(60.0, 40.0), Point::new(450.0, 0.0), Point::new(-900.0, 300.0)] { + let next = *at + step.to_vec2(); + assert!(render(&mut r, d, next).pixels == whole(d, next).pixels, "{what}, moved by {step:?}: the same pixels"); + } + } +} + +#[test] +fn a_long_stroke_is_outlined_near_the_view_only() { + let d = doc(&zigzag(), 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); + let near = r.strokes.values().map(|e| e.outline.elements().len()).sum::(); + CROP_STROKES.with(|c| c.set(false)); + let mut full = Renderer::new(); + render(&mut full, &d, at); + CROP_STROKES.with(|c| c.set(true)); + let all = full.strokes.values().map(|e| e.outline.elements().len()).sum::(); + assert!(near > 0 && near * 10 < all, "{near} outline elements near the view, {all} for the whole stroke"); +} + +#[test] +fn a_stroke_a_wide_stroke_crosses_over_stays_whole() { + // A closed sliver 4 pt tall: a 10 pt stroke covers it from side to side. + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for i in 1..=2000 { + bp.line_to((f64::from(i) * 10.0, 0.0)); + } + bp.line_to((20_000.0, 4.0)); + bp.line_to((0.0, 4.0)); + bp.close_path(); + let d = doc(&bp, stroke(10.0, LineJoin::Miter, LineCap::Butt)); + let at = Point::new(20_000.0, 2.0); + let mut r = Renderer::new(); + let img = render(&mut r, &d, at); + assert!(r.strokes.values().all(|e| e.crop.is_none())); + assert!(img.pixels == whole(&d, at).pixels); +} + +fn path(svg: &str) -> BezPath { + BezPath::from_svg(svg).unwrap() +} + +#[test] +fn crop_line_keeps_the_runs_of_segments_near_the_region() { + let region = Rect::new(0.0, 0.0, 100.0, 100.0); + let crop = |svg: &str| crop_line(&path(svg), region, 5.0, 1.0).map(|bp| bp.to_svg()); + // Nothing to leave out: an empty path, one segment, a path in the region. + assert_eq!(crop(""), None); + assert_eq!(crop("M10,10 L90,90"), None); + assert_eq!(crop("M10,10 L90,90 L10,90 Z"), None); + // A segment within the reach of the region stays; one beyond it goes, and the open path is cut. + assert_eq!(crop("M50,50 L104,50 L200,50 L300,50").as_deref(), Some("M50,50 L104,50 L200,50")); + assert_eq!(crop("M50,50 L200,50 L300,50 L400,50").as_deref(), Some("M50,50 L200,50")); + // A curve whose control point reaches the region stays. + assert_eq!(crop("M200,0 C50,50 300,0 400,0 L500,0").as_deref(), Some("M200,0 C50,50 300,0 400,0")); + // Two runs, each its own open subpath. + assert_eq!(crop("M50,10 L300,10 L300,90 L50,90").as_deref(), Some("M50,10 L300,10 M300,90 L50,90")); + // Every segment goes. + assert_eq!(crop("M300,300 L400,400").as_deref(), Some("")); + // A closed subpath is walked from a segment it loses: its start stays inside one run. + assert_eq!(crop("M50,50 L50,500 L500,500 L500,50 Z").as_deref(), Some("M500,50 L50,50 L50,500")); + // A subpath with no segments stays, and so does an untouched subpath beside a cut one. + assert_eq!(crop("M900,900 M10,10 L20,20 M50,50 L300,50 L400,50").as_deref(), Some("M900,900 M10,10 L20,20 M50,50 L300,50")); + // A closed subpath that the stroke crosses over keeps all its segments. + assert_eq!(crop_line(&path("M50,0 L50,2 L500,2 L500,0 Z"), region, 5.0, 3.0), None); + // A coordinate that is not a number keeps its segment. + let mut nan = path("M50,50 L300,50 L400,50"); + nan.line_to((f64::NAN, 50.0)); + assert!(crop_line(&nan, region, 5.0, 1.0).is_some_and(|bp| bp.elements().iter().any(|e| e.end_point().is_some_and(|p| p.x.is_nan())))); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57e3defab3..7b5f5deaaf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1242,6 +1242,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. The Pathfinder panel, Offset Path, Clean Up, Divide Objects Below, Make and Release Blend, Envelope Distort's Make and Release, Repeat (Radial, Grid, Mirror and Release), Vector Halftone, New and Redefine Symbol, Delete Symbol, erasing with the Symbol Sprayer, Rasterize, Convert to Artboards, Flatten Transparency, Clear Guides, Shape Builder, Live Paint, Release Image Trace, Make and Release Opacity Mask, Delete with direct-selected anchor points, Remove Anchor Points, Cut Path, and the Shaper, Knife, Eraser, Path Eraser, Line Cut, Rectangle Cut, Mirror & Cut and Blob Brush tools add and remove objects in one pass over each layer or group they change, and Outline Stroke and Expand write each new object in the place of the object it replaces (#1429). 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 a stroke of 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`). 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). 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). From d6190e79e0f05ae97351fbcc9f93001202252b4b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:49:00 -0800 Subject: [PATCH 018/482] Render: a filter layer's offscreen culls art and crops long strokes to its own area On a multithreaded context, a drop shadow or glow drawn through a filter layer is drawn into an offscreen that covers the art plus the blur's spread, but its frame kept the view's visible rect. Art outside the view but within the spread was culled, so it cast no shadow, and a long stroke was outlined only near the view, so its far parts no longer fed the blur. The offscreen's frame now takes its visible rect from its own area, and the frame of content kept from an earlier split takes the window it is drawn over. --- crates/render/src/fx/pixels.rs | 7 +++- crates/render/src/tests/longstroke.rs | 59 +++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index eb5c698019..e89f2bddac 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -54,7 +54,7 @@ impl Renderer { let split_frame; let (f, screen) = match content.kept.and_then(|k| k.frame.map(|frame| (k.window, frame))) { Some((window, (view, px))) => { - split_frame = Frame { view, px, ..*f }; + split_frame = Frame { view, visible: window, px, ..*f }; (&split_frame, view.transform_rect_bbox(window)) } None => (f, Rect::new(0.0, 0.0, ctx.width() as f64, ctx.height() as f64)), @@ -580,7 +580,10 @@ impl Renderer { None => (x0, y0, w, h, k), }; let mut off = f.offscreen_context(w, h); - let shifted = Frame { mt: false, view: Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view, px: f.px / k, ..*f }; + let view = Affine::scale(k) * Affine::translate((-x0, -y0)) * f.view; + // Art is culled against, and long strokes outlined around, the offscreen's own area. + let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h))); + let shifted = Frame { mt: false, view, visible, px: f.px / k, ..*f }; self.inside_layer(|r| draw(r, &mut off, &shifted, None)); off.flush(); let mut pm = vello_cpu::Pixmap::new(w, h); diff --git a/crates/render/src/tests/longstroke.rs b/crates/render/src/tests/longstroke.rs index b8c7e7cf65..ef7a449d3f 100644 --- a/crates/render/src/tests/longstroke.rs +++ b/crates/render/src/tests/longstroke.rs @@ -98,6 +98,65 @@ fn a_long_stroke_draws_the_same_pixels_outlined_near_the_view() { } } +/// A zigzag of 3,000 anchors 8 pt apart between y = 60 and y = 550, through the bottom of a view +/// on y = 0. +fn tall_zigzag() -> BezPath { + let mut bp = BezPath::new(); + let at = |i: usize| Point::new(i as f64 * 8.0, if i.is_multiple_of(2) { 60.0 } else { 550.0 }); + bp.move_to(at(0)); + for i in 1..3000 { + bp.line_to(at(i)); + } + bp +} + +#[test] +fn a_long_stroke_under_a_wide_blur_draws_the_same_pixels_while_dragging_on_threads() { + // While dragging on threads, a drop shadow this large is drawn through a filter layer whose + // offscreen reaches 602 px past the view: the parts of the stroke that far away feed the blur. + let mut d = Document::new(1000.0, 1000.0); + let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 400, "opacity": 100, "mode": "normal"}); + let look = Appearance { items: vec![AppearanceItem::Stroke(stroke(20.0, LineJoin::Round, LineCap::Butt))], ..Default::default() }; + let n = Node::path(d.alloc_id(), PathData::from_bezpath(&tall_zigzag()), look); + // The shadow is the group's: the path itself draws as a plain path. + let mut g = Node::group(d.alloc_id(), vec![n.into()]); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let at = Point::new(12_000.0, 0.0); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), dragging: true, ..Default::default() }; + let draw = |crops: bool| { + CROP_STROKES.with(|c| c.set(crops)); + let mut r = Renderer::new(); + r.threads = 2; + let img = r.render(&d, SIZE, SIZE, view_at(at), &opts); + CROP_STROKES.with(|c| c.set(true)); + (img, r.strokes.values().any(|e| e.crop.is_some())) + }; + let ((near, cropped), (all, _)) = (draw(true), draw(false)); + assert!(cropped, "outlined near the view"); + assert!(all.pixel(100, 0)[0] < 250, "the shadow shows above the stroke: {:?}", all.pixel(100, 0)); + assert!(near.pixels == all.pixels, "the same pixels as the whole outline"); +} + +#[test] +fn a_member_below_the_view_casts_its_wide_shadow_while_dragging_on_threads() { + // A 400 pt shadow of a group whose only member, a rectangle, lies 50 pt below the view. + let mut d = Document::new(1000.0, 1000.0); + let shadow = serde_json::json!({"x": 0, "y": 0, "blur": 400, "opacity": 100, "mode": "normal"}); + let look = Appearance { items: vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK)))], ..Default::default() }; + let n = Node::path(d.alloc_id(), PathData::from_bezpath(&Rect::new(-1000.0, 150.0, 1000.0, 550.0).to_path(0.1)), look); + let mut g = Node::group(d.alloc_id(), vec![n.into()]); + g.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: shadow, visible: true }); + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), dragging: true, ..Default::default() }; + let mut r = Renderer::new(); + r.threads = 2; + let img = r.render(&d, SIZE, SIZE, view_at(Point::ZERO), &opts); + assert!(img.pixel(100, 199)[0] < 200, "the shadow shows at the bottom of the view: {:?}", img.pixel(100, 199)); +} + #[test] fn a_long_stroke_is_outlined_near_the_view_only() { let d = doc(&zigzag(), stroke(6.0, LineJoin::Miter, LineCap::Square)); From 8d0f251c3773a3b5558b06848387b682f616029c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:02:12 -0800 Subject: [PATCH 019/482] Examples: anchor_bench's doc comment says what the example prints --- crates/engine/examples/anchor_bench.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/examples/anchor_bench.rs b/crates/engine/examples/anchor_bench.rs index a460602202..877526b109 100644 --- a/crates/engine/examples/anchor_bench.rs +++ b/crates/engine/examples/anchor_bench.rs @@ -1,5 +1,5 @@ -//! `cargo run --release -p vectorcraft-engine --example anchor_bench` — wall time of the engine -//! steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of +//! `cargo run --release -p vectorcraft-engine --example anchor_bench` prints the wall time of the +//! engine steps of editing anchors with Direct Selection, on three synthetic documents: one closed path of //! 50,000 anchors, 2,000 closed paths of 50 anchors each, and one open path of 200,000 anchors. //! `ITERS` sets the runs per step (default 7); each row is the median in ms. // Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). From 3fbdf72231bb1a26d5e01a0a5d0a51d006570729 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:10:50 -0800 Subject: [PATCH 020/482] Docs: the long-stroke line names the strokes of path objects --- 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 7b5f5deaaf..45ec87471c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1242,7 +1242,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Overprint Preview or Separations Preview on, the renderer keeps the art it prepared for the preview from one frame to the next. It prepares again the objects that changed, and all of the art when Discard White Overprint changes or, with Separations Preview, when the plates shown, the proof setup, the swatches, the Spot Colors option or the color settings change or a profile is loaded. It draws the other objects from the art, geometry and stroke outlines it kept for them. The Pathfinder panel, Offset Path, Clean Up, Divide Objects Below, Make and Release Blend, Envelope Distort's Make and Release, Repeat (Radial, Grid, Mirror and Release), Vector Halftone, New and Redefine Symbol, Delete Symbol, erasing with the Symbol Sprayer, Rasterize, Convert to Artboards, Flatten Transparency, Clear Guides, Shape Builder, Live Paint, Release Image Trace, Make and Release Opacity Mask, Delete with direct-selected anchor points, Remove Anchor Points, Cut Path, and the Shaper, Knife, Eraser, Path Eraser, Line Cut, Rectangle Cut, Mirror & Cut and Blob Brush tools add and remove objects in one pass over each layer or group they change, and Outline Stroke and Expand write each new object in the place of the object it replaces (#1429). 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 a stroke of 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 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`). 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). 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). From f0f19077df899172b794687af6b9af11851e1055 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 16:55:43 +0700 Subject: [PATCH 021/482] Document Color Mode: convert reusable paints and restore them with Undo Squashed from #4517 onto main. --- crates/doc/src/lib.rs | 1 + crates/doc/src/mem.rs | 45 +- crates/effects/src/lib.rs | 2 +- crates/effects/src/raster.rs | 2 +- crates/engine/src/cmd/colormgmt.rs | 237 +++++-- crates/engine/src/cmd/docmenu.rs | 2 +- crates/engine/src/cmd/edit.rs | 12 + crates/engine/src/cmd/fileio/batch.rs | 27 +- crates/engine/src/cmd/params.rs | 24 +- crates/engine/src/doc_state.rs | 10 + crates/engine/src/history.rs | 60 +- crates/engine/src/interaction.rs | 13 + crates/engine/src/lib.rs | 4 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/edit.rs | 48 +- crates/engine/src/session/execute.rs | 24 +- crates/engine/src/session/undo.rs | 39 +- crates/engine/src/tests/colormgmt.rs | 114 ++++ crates/engine/src/tests/history_mem.rs | 39 ++ crates/engine/src/tests/paintproxy.rs | 13 + crates/engine/src/tests/swatches.rs | 764 +++++++++++++++++++++++ crates/ui-egui/src/dialogs/effect.rs | 15 +- crates/ui-egui/src/dialogs/form.rs | 41 +- crates/ui-egui/src/dialogs/tests.rs | 27 + crates/ui-egui/src/panels/color/tests.rs | 6 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 27 files changed, 1487 insertions(+), 94 deletions(-) diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b59f661c21..49ba5465a1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -40,6 +40,7 @@ pub mod live; pub mod live_paint; pub mod marks; mod mem; +pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; pub mod node; pub mod objects_on_path; diff --git a/crates/doc/src/mem.rs b/crates/doc/src/mem.rs index a1268505fb..a938308226 100644 --- a/crates/doc/src/mem.rs +++ b/crates/doc/src/mem.rs @@ -98,7 +98,7 @@ impl Document { vec_bytes(g) + g.iter().map(|g: &SwatchGroup| g.name.capacity() + swatches_bytes(&g.swatches)).sum::() }); n += shared(&self.graphic_styles, &newer.graphic_styles, |g| { - vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap(&g.appearance)).sum::() + vec_bytes(g) + g.iter().map(|g: &GraphicStyle| g.name.capacity() + appearance_heap_bytes(&g.appearance)).sum::() }); let styles = |s: &Vec| vec_bytes(s) + s.iter().map(|s| s.name.capacity() + map_bytes(&s.attrs)).sum::(); n += shared(&self.char_styles, &newer.char_styles, styles); @@ -245,7 +245,7 @@ fn node_bytes(n: &Node, other: Option<&Node>) -> usize { let mut b = ALLOC + ARC + size_of::(); b += n.name.as_ref().map_or(0, String::capacity); if !other.is_some_and(|m| Shared::ptr_eq(&m.appearance, &n.appearance)) { - b += ALLOC + ARC + appearance_heap(&n.appearance); + b += ALLOC + ARC + appearance_heap_bytes(&n.appearance); } if let Some(e) = n.extras_box() { b += ALLOC + size_of::(); @@ -293,32 +293,53 @@ fn text_bytes(t: &TextObject) -> usize { + vec_bytes(&t.cached_baselines) } -/// The heap an appearance owns (not the appearance itself). -fn appearance_heap(a: &Appearance) -> usize { +/// Approximate retained memory of an appearance and its owned buffers, without serialization. +pub fn appearance_heap_bytes(a: &Appearance) -> usize { size_of::() + vec_bytes(&a.items) + a.items .iter() - .map(|i| match i { - AppearanceItem::Fill(f) => paint_heap(&f.paint), - AppearanceItem::Stroke(s) => paint_heap(&s.paint), + .map(|item| { + let paint = paint_heap_bytes(item.paint()); + let effects = effects_heap(item.effects()); + let stroke = match item { + AppearanceItem::Stroke(s) => { + s.dash.as_ref().map_or(0, |d| vec_bytes(&d.pattern)) + + s.profile.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + s.pressure.as_ref().map_or(0, |p| vec_bytes(&p.points)) + + s.brush.as_ref().map_or(0, String::capacity) + } + _ => 0, + }; + paint + effects + stroke }) .sum::() - + vec_bytes(&a.effects) - + a.effects.iter().map(|e: &Effect| e.id.capacity() + json_bytes(&e.params)).sum::() + + effects_heap(&a.effects) } -fn paint_heap(p: &Paint) -> usize { +fn effects_heap(effects: &Vec) -> usize { + vec_bytes(effects) + effects.iter().map(|e| e.id.capacity() + json_bytes(&e.params)).sum::() +} + +/// Approximate heap retained by one paint, without serializing it. +pub fn paint_heap_bytes(p: &Paint) -> usize { match p { Paint::Solid { swatch, .. } => swatch.as_ref().map_or(0, String::capacity), - Paint::Gradient(g) => ALLOC + size_of_val(&**g) + vec_bytes(&g.gradient.stops), + Paint::Gradient(g) => { + ALLOC + + size_of_val(&**g) + + vec_bytes(&g.gradient.stops) + + g.gradient.stops.iter().map(|s| s.swatch.as_ref().map_or(0, String::capacity)).sum::() + + g.swatch.as_ref().map_or(0, String::capacity) + + g.freeform.as_ref().map_or(0, |f| vec_bytes(&f.points) + vec_bytes(&f.lines) + f.lines.iter().map(vec_bytes).sum::()) + } Paint::Pattern { pattern, .. } => pattern.capacity(), Paint::None => 0, } } fn swatches_bytes(s: &[Swatch]) -> usize { - ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap(&w.paint)).sum::() + ALLOC + std::mem::size_of_val(s) + s.iter().map(|w| w.name.capacity() + paint_heap_bytes(&w.paint)).sum::() } /// A vector's buffer (not what its elements own). diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9af1cfffd3..fbbf3b0a90 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -77,7 +77,7 @@ pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_par pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks}; pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace}; -pub use raster::{RASTERIZE, RasterFx, Rasterize, outset, raster_effects}; +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, diff --git a/crates/effects/src/raster.rs b/crates/effects/src/raster.rs index f8590bbb2e..a1d8df2d61 100644 --- a/crates/effects/src/raster.rs +++ b/crates/effects/src/raster.rs @@ -366,7 +366,7 @@ pub fn blend_mode(s: &str) -> BlendMode { } /// An effect's `color` parameter (`"#rrggbb"`, `[r, g, b]` 0..1 or a colour object). -pub(crate) fn color_param(p: &Value, default: Color) -> Color { +pub fn color_param(p: &Value, default: Color) -> Color { match p.get("color") { Some(Value::String(s)) => Color::from_hex(s).unwrap_or(default), Some(Value::Array(a)) if a.len() >= 3 => { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0cf1a0ec7e..f03b66a925 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -319,17 +319,138 @@ pub(crate) fn convert_mode(s: &mut Session, p: &Value) -> Result { changed = set_color_mode(d, mode, convert, intent, grays); Ok(()) })?; + if convert { + if s.in_interaction() && s.batch_stash.is_none() { + if let Some(it) = &mut s.doc_mut()?.interaction { + it.deferred_color_mode = Some(DeferredColorMode { mode, intent, grays }); + } + } else { + let before = new_art_colors_before(s)?; + convert_new_art_colors(s, mode, intent, grays)?; + record_new_art_colors(s, before)?; + } + } else if s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + let before = new_art_colors_before(s)?; + record_new_art_colors(s, before)?; + } Ok(json!({ "changed": changed })) } -/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks -/// included), symbols, graph designs, pattern tiles (the tile that pattern editing's Cancel puts -/// back included), graphic styles, brushes (their art and a Hue Shift key color) and swatches -/// through the color settings (`intent`, default: theirs) → how many colors of the art (opacity -/// masks included), symbols, graph designs and pattern tiles changed; the colors of graphic -/// styles and brushes convert without being counted. Gray colors stay -/// Gray (they print on the black plate in either mode); RGB grays are colors like any other and -/// separate through the CMYK profile, unless `grays` puts them on the black plate. Lab colors +/// The validated conversion choices of the current tentative color-mode preview. +#[derive(Clone, Copy, Debug)] +pub(crate) struct DeferredColorMode { + mode: ColorMode, + intent: Option, + grays: Grays, +} + +/// Complete the deferred new-art conversion before the interaction becomes an Undo step. +pub(crate) fn commit_new_art_colors(s: &mut Session) -> Result<()> { + let pending = + s.doc()?.interaction.as_ref().filter(|it| it.preview.is_some() && it.color_mode_paints.is_none()).and_then(|it| it.deferred_color_mode); + if let Some(DeferredColorMode { mode, intent, grays }) = pending { + let before = new_art_colors_before(s)?; + convert_new_art_colors(s, mode, intent, grays)?; + record_new_art_colors(s, before)?; + } + Ok(()) +} + +fn record_new_art_colors(s: &mut Session, before: vectorcraft_tools::PaintDefaults) -> Result<()> { + let after = s.paint.clone(); + if before != after || s.batch_stash.is_some() || s.doc()?.undo_group.is_some() { + let st = s.doc_mut()?; + let slot = if let Some(it) = &mut st.interaction { + Some(&mut it.color_mode_paints) + } else { + st.history.undo.last_mut().map(|e| &mut e.color_mode_paints) + }; + if let Some(slot) = slot { + match slot { + Some((_, end)) => *end = after, + slot => *slot = Some((before, after)), + } + } + if st.interaction.is_none() { + if let Some(e) = st.history.undo.last_mut() { + e.recost_paints(); + } + st.history.trim(); + } + } + Ok(()) +} + +fn new_art_colors_before(s: &Session) -> Result { + let st = s.doc()?; + Ok(st.undo_group.as_ref().map(|g| &g.paint).or_else(|| st.interaction.as_ref().map(|it| &it.paint)).cloned().unwrap_or_else(|| s.paint.clone())) +} + +/// Convert the fill and stroke that new art takes, and the colors of its template appearance +/// (paints and effect colors), as [`set_color_mode`] converted the active document's art. The +/// command records their original values for Undo. Previews defer this until acceptance; +/// a batch converts immediately and restores the values itself when it fails. +fn convert_new_art_colors(s: &mut Session, mode: ColorMode, intent: Option, grays: Grays) -> Result<()> { + let d = &s.doc()?.doc; + let bases = global_bases(d); + let conv = mode_converter(mode, intent, grays); + let mut f = |col: &Color, link: proof::Link| mode_color(col, link, &bases, &conv); + map_paint_colors(&mut s.paint.fill, &mut f); + map_paint_colors(&mut s.paint.stroke, &mut f); + if let Some(a) = s.paint.appearance.as_mut() { + for it in &mut a.items { + let paint = match it { + vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, + vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, + }; + map_paint_colors(paint, &mut f); + } + map_effect_colors(a, &mut f); + } + Ok(()) +} + +/// How Document Color Mode converts a color to `mode` through the color settings (`intent`, +/// default: theirs): Gray and Lab colors stay as they are; with `grays` on the black plate, an RGB +/// gray becomes K only in CMYK. +fn mode_converter(mode: ColorMode, intent: Option, grays: Grays) -> impl Fn(&Color) -> Color { + let c = cms::active(); + let intent = intent.unwrap_or(c.settings().intent); + let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb }; + let k_only = model == Model::Cmyk && grays == Grays::Black; + move |col: &Color| match col { + Color::Gray { .. } | Color::Lab { .. } => *col, + // Grey ink percentage, then K only (a Gray colour's CMYK). + Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent), + _ => c.convert(col, model, intent), + } +} + +/// The name and color of each global swatch of `d`, for [`mode_color`]. +fn global_bases(d: &vectorcraft_doc::Document) -> Vec<(String, Color)> { + d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect() +} + +/// The color Document Color Mode gives `col` (swatch link `link`): a tint of a global swatch in +/// `bases` (already converted) is that swatch's color at its tint; any other color goes through +/// `conv` ([`mode_converter`]). +fn mode_color(col: &Color, link: proof::Link, bases: &[(String, Color)], conv: &dyn Fn(&Color) -> Color) -> Color { + match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { + Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), + _ => conv(col), + } +} + +/// Put `d` in color `mode` and, with `convert`, convert every color of its art (opacity masks, +/// effect colors and the series paints and label styles that graphs keep included), symbols, +/// graph designs, pattern tiles (the tile that pattern editing's Cancel puts back included), +/// graphic styles (their effects included), brushes (their art and a Hue Shift key color) and +/// swatches through the color settings (`intent`, default: theirs) → how many colors of the art +/// (opacity masks, effect colors and graphs' paints included), symbols, graph designs and pattern +/// tiles changed; the colors of graphic styles and brushes convert without being counted. Gray +/// colors stay Gray (they print on the black plate in either mode); RGB grays are colors like any +/// other and separate through the CMYK profile, unless `grays` puts them on the black plate +/// ([`mode_converter`]). Lab colors /// (spot color definitions) are device independent and fit either mode. A tint of a global /// swatch becomes the converted swatch's color at its tint. Document Color Mode and /// `document.open {colorMode}` both convert this way. @@ -338,16 +459,7 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, if !convert { return 0; } - let c = cms::active(); - let intent = intent.unwrap_or(c.settings().intent); - let model = if mode == ColorMode::Cmyk { Model::Cmyk } else { Model::Rgb }; - let k_only = model == Model::Cmyk && grays == Grays::Black; - let conv = |col: &Color| match col { - Color::Gray { .. } | Color::Lab { .. } => *col, - // Grey ink percentage, then K only (a Gray colour's CMYK). - Color::Rgb { .. } if k_only && Neutral::of(col).is_some() => c.convert(&c.convert(col, Model::Gray, intent), Model::Cmyk, intent), - _ => c.convert(col, model, intent), - }; + let conv = mode_converter(mode, intent, grays); for sw in d.swatches_iter_mut() { match &mut sw.paint { Paint::Solid { color, .. } => *color = conv(color), @@ -360,13 +472,10 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, } } // Tints are their converted swatch's colour at their tint (exact ink percentages). - let bases: Vec<(String, Color)> = d.swatches_iter().filter_map(|w| Some((w.name.clone(), d.global_color(&w.name)?))).collect(); + let bases = global_bases(d); let changed = std::cell::Cell::new(0usize); let mut count = |col: &Color, link: proof::Link| { - let n = match link.and_then(|(name, tint)| Some((bases.iter().find(|(n, _)| n == name)?, tint))) { - Some(((_, base), tint)) if tint < 1.0 => base.tinted(tint), - _ => conv(col), - }; + let n = mode_color(col, link, &bases, &conv); if n != *col { changed.set(changed.get() + 1); } @@ -384,12 +493,15 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, } // The reply counts the colors of the document's art only, not those of the graphic styles and brushes. let in_art = changed.get(); - for it in d.graphic_styles.iter_mut().flat_map(|g| &mut g.appearance.items) { - let paint = match it { - vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, - vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, - }; - map_paint_colors(paint, &mut count); + for g in &mut d.graphic_styles { + for it in &mut g.appearance.items { + let paint = match it { + vectorcraft_doc::AppearanceItem::Fill(l) => &mut l.paint, + vectorcraft_doc::AppearanceItem::Stroke(l) => &mut l.paint, + }; + map_paint_colors(paint, &mut count); + } + map_effect_colors(&mut g.appearance, &mut count); } // Convert each brush's art. A Hue Shift key color takes the converted color of the art color // it matches (a tint of a global swatch included), so the key still matches the converted art; @@ -438,19 +550,28 @@ pub(crate) fn set_color_mode(d: &mut vectorcraft_doc::Document, mode: ColorMode, in_art } -/// [`proof::map_node_colors`] over `n`'s subtree and the art of every opacity mask in it. +/// [`proof::map_node_colors`] over `n`'s subtree, then [`map_more_colors`]. fn map_art_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { proof::map_node_colors(n, f); - map_mask_colors(n, f); + map_more_colors(n, f); } -fn map_mask_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { - if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { - map_art_colors(Arc::make_mut(&mut mask.art), f); +/// `f` applied to the colors in `n`'s subtree that [`proof::map_node_colors`] does not visit: the +/// effect colors ([`map_effect_colors`]), the series paints and label styles a graph keeps +/// ([`map_graph_colors`]) and the art of every opacity mask. +fn map_more_colors(n: &mut vectorcraft_doc::Node, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + map_effect_colors(&mut n.appearance, f); + if let Some(e) = n.extras_if_any() { + if let Some(g) = e.graph.as_deref_mut() { + map_graph_colors(g, f); + } + if let Some(mask) = e.mask.as_deref_mut() { + map_art_colors(Arc::make_mut(&mut mask.art), f); + } } if let Some(ch) = n.children_mut() { for c in ch.iter_mut() { - map_mask_colors(Arc::make_mut(c), f); + map_more_colors(Arc::make_mut(c), f); } } } @@ -461,7 +582,46 @@ fn matches_key(c: &Color, key: &Color) -> bool { c.to_rgb().iter().zip(key.to_rgb()).map(|(a, b)| (a - b).abs()).sum::() < 0.02 } -/// `f` applied to a solid paint's color or a gradient's stop colors, given their swatch link. +/// `f` applied to the `color` of each effect in appearance `a` (the object's effects and those of +/// each fill and stroke) that has one ([`super::params::effect_color`]). An effect that draws its +/// default color stores the new color as its own. The light colors of the 3D effects stay as they +/// are. +fn map_effect_colors(a: &mut vectorcraft_doc::Appearance, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + let items = a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut()); + for e in a.effects.iter_mut().chain(items) { + if !(e.params.is_object() || e.params.is_null()) { + continue; + } + let Some(color) = super::params::effect_color(&e.id, &e.params) else { continue }; + let n = f(&color, None); + if n == color { + continue; + } + match &mut e.params { + Value::Object(m) => { + m.insert("color".into(), json!(n)); + } + p => *p = json!({ "color": n }), + } + } +} + +/// `f` applied to the series paints and the label styles that graph `g` keeps, which its marks and +/// labels take each time it is drawn again. +fn map_graph_colors(g: &mut vectorcraft_doc::GraphSpec, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { + for p in g.series_paints.iter_mut() { + for paint in [&mut p.fill, &mut p.stroke].into_iter().flatten() { + map_paint_colors(paint, f); + } + } + let styles = &mut g.label_styles; + for st in [&mut styles.values, &mut styles.categories, &mut styles.legend].into_iter().flatten() { + map_paint_colors(&mut st.fill, f); + map_paint_colors(&mut st.stroke, f); + } +} + +/// `f` applied to solid, gradient-stop and freeform-control colors, with any swatch link. fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Color) { match p { Paint::Solid { color, swatch, tint } => *color = f(color, swatch.as_deref().map(|s| (s, *tint))), @@ -469,6 +629,11 @@ fn map_paint_colors(p: &mut Paint, f: &mut dyn FnMut(&Color, proof::Link) -> Col for st in &mut g.gradient.stops { st.color = f(&st.color, st.swatch.as_deref().map(|s| (s, st.tint))); } + if let Some(freeform) = &mut g.freeform { + for point in &mut freeform.points { + point.color = f(&point.color, None); + } + } } _ => {} } diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index f566f1635e..0f13a502e9 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -256,7 +256,7 @@ pub fn specs() -> Vec { "Document Color Mode", ["File", "Document Color Mode"], None, - "{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks included), symbols, graph designs, pattern tiles, graphic styles, brushes and swatches through the color settings; swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}", + "{mode: \"cmyk\"|\"rgb\", convert?: true (convert every color of the art (opacity masks, effect colors and graphs' series and label paints included), symbols, graph designs, pattern tiles, graphic styles (their effect colors included), brushes, swatches and the paints new art takes through the color settings, together in one undo step (Undo restores their original values; Redo reapplies the conversion); swatch links kept; Gray colors stay Gray, on the black plate), intent?, grays?: \"profile\" (default: RGB grays separate through the CMYK profile like any color, into four-color grays and a rich black) | \"black\" (to CMYK, RGB grays with R = G = B go on the black plate only, K = their gray value)} → {changed: how many colors of the art, symbols, graph designs and pattern tiles changed; the colors of graphic styles and brushes are not counted}", has_doc, super::colormgmt::convert_mode ), diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index f252d09ff9..09aab81325 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -487,6 +487,9 @@ fn undo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + let paints = e.color_mode_paints.clone(); + turned.color_mode_paints = e.color_mode_paints; + turned.recost_paints(); st.history.redo.push(turned); st.history.trim(); st.revision += 1; @@ -499,6 +502,9 @@ fn undo(s: &mut Session, _: &Value) -> Result { leave_isolation_if_gone(st); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); + if let Some((before, _)) = paints { + s.paint = before; + } Ok(json!({ "undone": label })) } @@ -516,6 +522,9 @@ fn redo(s: &mut Session, _: &Value) -> Result { let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); turned.named = e.named; + let paints = e.color_mode_paints.clone(); + turned.color_mode_paints = e.color_mode_paints; + turned.recost_paints(); st.history.undo.push(turned); st.history.trim(); st.revision += 1; @@ -527,6 +536,9 @@ fn redo(s: &mut Session, _: &Value) -> Result { leave_isolation_if_gone(st); super::globaledit::follow_history(st); st.drop_stale_variables_highlight(); + if let Some((_, after)) = paints { + s.paint = after; + } Ok(json!({ "redone": label })) } diff --git a/crates/engine/src/cmd/fileio/batch.rs b/crates/engine/src/cmd/fileio/batch.rs index 3dc3a51d9c..60f8be3297 100644 --- a/crates/engine/src/cmd/fileio/batch.rs +++ b/crates/engine/src/cmd/fileio/batch.rs @@ -15,12 +15,12 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { let artboard = p.get("artboard").and_then(Value::as_u64); // What an error rolls back besides the documents: session-level state a step may change // (paint defaults, drawing mode, clipboard, the Untitled-N count, a begun undo group). - let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // A drag or typing still in progress is a step of its own, as before Undo: the batch's steps // would otherwise run inside it and take its baseline as theirs (#1697). - if s.active().is_some() { + if s.active().is_some() && !s.previewing { super::super::edit::settle_interaction(s)?; } + let saved = (s.paint.clone(), s.fill_active, s.draw_mode, s.draw_inside, s.clipboard.clone(), s.untitled_counter, s.explicit_undo_group.clone()); // The documents as they are now, whole: what a failed step brings back. Their art, history, // file, format and saved state share their data with the open ones until a step changes them. let start = s.docs.clone(); @@ -47,10 +47,18 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { } }; // Each document the steps edited keeps them as one undo step. - s.remember_pending_paint(); - for st in &mut s.docs { - if let Some(it) = st.interaction.take() { - st.keep_interaction(it); + if !s.previewing { + s.remember_pending_paint(); + for st in &mut s.docs { + if let Some(mut it) = st.interaction.take() { + // Redo restores the new-art colors the whole batch left, not the ones right after a + // color-mode step. + if let Some((_, after)) = &mut it.color_mode_paints { + after.clone_from(&s.paint); + s.batch_paint_docs.push(st.uid); + } + st.keep_interaction(it); + } } } // The batch journals itself, whichever document it ends in. @@ -58,7 +66,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { if let Some(o) = entry.as_object_mut() { o.insert("commands".into(), Value::Array(cmds)); } - s.journal.push(("command.batch".into(), entry)); + if !s.previewing { + s.journal.push(("command.batch".into(), entry)); + } Ok(json!({ "results": results })) } @@ -104,6 +114,9 @@ fn run_steps( let held: Vec<(u64, Arc)> = s.docs.iter().filter(|st| st.undo_group.is_some()).map(|st| (st.uid, st.doc.clone())).collect(); let (v, noted) = s.execute_step(&id, ¶ms).map_err(|e| EngineError::Other(format!("batch step {} (`{id}`) failed: {e}", results.len())))?; + if s.previewing && s.active().map(|d| d.uid) != start { + return Err(bad("command.batch", "a batch preview cannot switch documents")); + } grouped.push(step_groups(s, start, &held)); // The step's journal entry records what it took from the preferences or the clock (a // save's date, a new document's), as a command of its own would. diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 0c0a81ed90..1ca9bf2339 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -303,16 +303,30 @@ fn is_effect_color(v: &Value) -> bool { pub(crate) fn check_effect_color(id: &str, effect: &str, params: &Value) -> Result<()> { let key = "color"; let Some(v) = params.get(key) else { return Ok(()) }; - if effect.starts_with(vectorcraft_plugins::effect::PREFIX) { - return Ok(()); - } - let takes_color = vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get(key).is_some_and(Value::is_string)); - if takes_color && !is_effect_color(v) { + if effect_takes_color(effect) && !is_effect_color(v) { return Err(bad(id, format!("`{key}` must be a #rrggbb color"))); } Ok(()) } +/// Does built-in effect `effect` have a `color` parameter (one whose default is a string)? Plug-in +/// effects have none here. +pub(crate) fn effect_takes_color(effect: &str) -> bool { + !effect.starts_with(vectorcraft_plugins::effect::PREFIX) + && vectorcraft_render::effects::effect_info(effect).is_some_and(|info| info.defaults.get("color").is_some_and(Value::is_string)) +} + +/// The color that built-in effect `effect` draws with `params`: their `color`, else the effect's +/// default color. `None` when the effect has no `color` parameter ([`effect_takes_color`]) or +/// `params` hold a `color` it can't read ([`is_effect_color`]). +pub(crate) fn effect_color(effect: &str, params: &Value) -> Option { + if !effect_takes_color(effect) || params.get("color").is_some_and(|v| !is_effect_color(v)) { + return None; + } + let merged = vectorcraft_render::effects::merged_params(effect, params); + Some(vectorcraft_render::effects::color_param(&merged, vectorcraft_color::Color::BLACK)) +} + /// The `channel` in `params` of Levels or Curves (`effect`), as command `id` was given it: a /// parameter error naming the channels unless the effect reads it /// ([`vectorcraft_render::effects::is_channel`]); the effect draws any other value as RGB. diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 5ed2abe1ce..34592575c3 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -318,6 +318,16 @@ impl DocState { _ => it.selection, }; self.push_undo(it.label, it.doc, selection); + if let Some(paints) = it.color_mode_paints + && let Some(e) = self.history.undo.last_mut() + { + match &mut e.color_mode_paints { + Some((_, after)) => *after = paints.1, + slot => *slot = Some(paints), + } + e.recost_paints(); + self.history.trim(); + } self.revision += 1; } } diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index ec53acd5ba..cb84e108ed 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -9,8 +9,8 @@ pub struct HistoryEntry { pub doc: Arc, /// The selection as it was, shared with the neighbouring steps that have the same one. pub selection: Arc, - /// Roughly the memory this step keeps of its own: what of `doc` the step after it (or the - /// document now) doesn't share ([`Document::retained_bytes`]). + /// Roughly the memory this step keeps of its own: the unshared document data + /// ([`Document::retained_bytes`]) plus owned color-mode paint snapshots. pub bytes: usize, /// The same the other way round: what that next state keeps that `doc` doesn't share. Undoing /// (redoing) this step makes a step that keeps the next state: this is its `bytes`. @@ -19,6 +19,10 @@ pub struct HistoryEntry { next: usize, /// The template and name `label` was made from ([`Session::edit_named`]). pub(crate) named: Option, + /// Original and converted new-art colors, only for steps that change document color mode. + pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, + /// Owned new-art snapshots included in both directional estimates. + color_mode_bytes: usize, } /// A step name made by filling the `{name}` placeholder of a template with a name @@ -45,7 +49,17 @@ impl HistoryEntry { pub(crate) fn kept(label: String, doc: Arc, selection: Arc, next: &Document) -> Self { doc.drop_lookup_cache(); let (bytes, next_bytes) = doc.retained_bytes_each(next); - HistoryEntry { label, doc, selection, bytes, next_bytes, next: std::ptr::from_ref(next) as usize, named: None } + HistoryEntry { + label, + doc, + selection, + bytes, + next_bytes, + next: std::ptr::from_ref(next) as usize, + named: None, + color_mode_paints: None, + color_mode_bytes: 0, + } } /// The template and name the step's label was made from, while the label is still the one @@ -66,12 +80,42 @@ impl HistoryEntry { return Self::kept(label, doc, selection, now); } doc.drop_lookup_cache(); - HistoryEntry { label, doc, selection, bytes: costs.next_bytes, next_bytes: costs.bytes, next: Arc::as_ptr(now) as usize, named: None } + HistoryEntry { + label, + doc, + selection, + bytes: costs.next_bytes, + next_bytes: costs.bytes, + next: Arc::as_ptr(now) as usize, + named: None, + color_mode_paints: None, + color_mode_bytes: 0, + } } - /// The figures [`HistoryEntry::turned`] reuses. + /// Recount the separately owned paints after a color-mode step or group changes them. + pub(crate) fn recost_paints(&mut self) { + let owned = |p: &vectorcraft_tools::PaintDefaults| { + std::mem::size_of::() + + vectorcraft_doc::paint_heap_bytes(&p.fill) + + vectorcraft_doc::paint_heap_bytes(&p.stroke) + + p.appearance.as_ref().map_or(0, vectorcraft_doc::appearance_heap_bytes) + + p.style.as_ref().map_or(0, String::capacity) + }; + let bytes = self.color_mode_paints.as_ref().map_or(0, |(before, after)| owned(before).saturating_add(owned(after))); + self.bytes = self.bytes.saturating_sub(self.color_mode_bytes).saturating_add(bytes); + self.next_bytes = self.next_bytes.saturating_sub(self.color_mode_bytes).saturating_add(bytes); + self.color_mode_bytes = bytes; + } + + /// The document-only figures [`HistoryEntry::turned`] reuses. Its paint snapshots are + /// attached and counted separately, so swapping direction never doubles their cost. pub(crate) fn costs(&self) -> StepCosts { - StepCosts { bytes: self.bytes, next_bytes: self.next_bytes, next: self.next } + StepCosts { + bytes: self.bytes.saturating_sub(self.color_mode_bytes), + next_bytes: self.next_bytes.saturating_sub(self.color_mode_bytes), + next: self.next, + } } } @@ -140,7 +184,9 @@ impl History { /// merged into it, or an undo group extended it). pub(crate) fn recost_last(&mut self, now: &Document) { if let Some(e) = self.undo.last_mut() { - (e.bytes, e.next_bytes) = e.doc.retained_bytes_each(now); + let (before, after) = e.doc.retained_bytes_each(now); + e.bytes = before.saturating_add(e.color_mode_bytes); + e.next_bytes = after.saturating_add(e.color_mode_bytes); e.next = std::ptr::from_ref(now) as usize; } } diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index b1d11a4793..1de58228a2 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -8,6 +8,13 @@ pub struct Interaction { /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, pub preview: Option<(String, Value)>, + /// A replaced or canceled preview restores these new-art paints from before the interaction. + pub(crate) paint: vectorcraft_tools::PaintDefaults, + /// An accepted batch preview uses these final paints after changing the document color mode. + pub(crate) preview_paint: Option, + /// Conversion of new-art paints waits until a color-mode preview is accepted. + pub(crate) deferred_color_mode: Option, + pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Per-document state restored on cancel (current layer, highlighted Layers panel rows, /// isolation). pub active_layer: Option, @@ -53,6 +60,8 @@ pub(crate) struct PreviewCopies { /// An open undo group ([`Session::begin_undo_group`]): the edits made in it are one undo step. #[derive(Clone, Debug)] pub struct UndoGroup { + /// The new-art paints from before the group's first command. + pub(crate) paint: vectorcraft_tools::PaintDefaults, /// The document before the group's first edit, as the undo step that edit recorded keeps it. pub(crate) first: Option>, /// The numbers of the journal entries made in the group's document while it was open: a canceled @@ -83,4 +92,8 @@ pub struct UndoScope { /// that the group's undo step keeps, as they were when the scope began; `None` when the scope /// opened the group. pub(crate) joined: Option<(Arc, Selection, Option>)>, + /// The new-art colors and the group's color-mode history metadata at the scope's start. + /// Only used when cancelling a joined scope that converted those colors. + pub(crate) paint: vectorcraft_tools::PaintDefaults, + pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 14db3a2cdb..7a77a1920b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -157,6 +157,10 @@ pub struct Session { /// groups: for each step, the documents ([`DocState::uid`]) whose undo groups it belongs to, and /// the index of the document it left active when it changed the active document. pub(crate) batch_steps: Option, Option)>>, + /// After `command.batch` kept a color-mode step's new-art colors, until the top-level command + /// has inherited the selection's appearance: the documents ([`DocState::uid`]) whose newest + /// history step takes the colors the batch finally left. + pub(crate) batch_paint_docs: Vec, /// While [`Session::place_read`] runs `file.place`: the file read for it, which the command /// places instead of reading the file; `None` otherwise. pub(crate) place_hand_off: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6e462e029c..6b048e6fa3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -77,6 +77,7 @@ impl Session { explicit_undo_group: None, batch_stash: None, batch_steps: None, + batch_paint_docs: Vec::new(), place_hand_off: None, queue_hand_off: None, place_queue_roots: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 71f70d25a0..da285eb3d3 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -225,6 +225,7 @@ impl Session { cmd::settle_interaction(self)?; } self.clear_deferred_overlay_cache(); + let paint = self.paint.clone(); let st = self.doc_mut()?; if st.interaction.is_some() { return Ok(()); @@ -234,6 +235,10 @@ impl Session { doc: st.doc.clone(), selection: Arc::new(st.selection.clone()), preview: None, + paint, + preview_paint: None, + color_mode_paints: None, + deferred_color_mode: None, active_layer: st.active_layer, layer_rows: st.layer_rows.clone(), variables_highlight: st.variables_highlight.clone(), @@ -246,10 +251,10 @@ impl Session { /// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview). pub fn preview(&mut self, cmd: &str, params: &Value) -> Result { - { + let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; - let Some(it) = &st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; + let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) }; // Undoing the previous preview counts as a change, so views redraw even when the command // below returns without an edit. let selection_changed = st.selection != *it.selection; @@ -257,6 +262,11 @@ impl Session { st.revision += 1; } st.doc = it.doc.clone(); + let restore_paint = cmd == "command.batch" || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch"); + let paint = it.paint.clone(); + it.preview_paint = None; + it.color_mode_paints = None; + it.deferred_color_mode = None; if selection_changed { st.selection.clone_from(&it.selection); } @@ -264,30 +274,54 @@ impl Session { // even when the preview fails. deselect_hidden(&menu, &st.doc, &mut st.selection); cmd::globaledit::follow_history(st); + (paint, restore_paint) + }; + if restore_paint { + self.paint = paint.clone(); } - // The previous preview's paint is undone with it. self.pending_paint = None; let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params)); let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p)); + // A selected object's converted appearance must not replace the current paints while + // this tentative color-mode preview is still cancellable. + let color_mode_paint = matches!(cmd, "file.documentColorMode" | "object.convertDocumentColorMode").then(|| self.paint.clone()); let outer = std::mem::replace(&mut self.previewing, true); let r = self.execute(cmd, params); self.previewing = outer; + if let Some(paint) = color_mode_paint { + self.paint = paint; + } let params = self.noted(params); + let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); + if it.color_mode_paints.is_some() { + it.preview_paint = batch_paint.clone(); + } + } + if batch_paint.is_some() && self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.preview_paint.is_some()) { + self.paint = paint; } r } pub fn commit_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); + if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) { + self.paint = paint; + } self.remember_pending_paint(); + cmd::colormgmt::commit_new_art_colors(self)?; + let paint = self.paint.clone(); let st = self.doc_mut()?; let Some(mut it) = st.interaction.take() else { return Ok(()) }; let Some(preview) = it.preview.take() else { return Ok(()) }; + if let Some((_, after)) = &mut it.color_mode_paints { + after.clone_from(&paint); + } let perspective_again = it.perspective_again.take(); let copy = preview.0 == "object.transform" && preview.1.get("copy").and_then(Value::as_bool).unwrap_or(false); // Alt pressed or released during a move drag turns it into a copy or back: name it for @@ -353,6 +387,14 @@ impl Session { pub fn cancel_interaction(&mut self) -> Result<()> { self.clear_deferred_overlay_cache(); self.pending_paint = None; + if let Some(paint) = self + .active() + .and_then(|st| st.interaction.as_ref()) + .filter(|it| it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch")) + .map(|it| it.paint.clone()) + { + self.paint = paint; + } let menu = self.menu.clone(); let st = self.doc_mut()?; st.undo_interaction(); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index f4ebd87c42..f993ac5857 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -107,9 +107,31 @@ impl Session { let (doc, journal, grouped) = (self.active().map(|d| d.uid), self.journal.len(), self.undo_group_docs()); let open = (self.depth == 0).then(|| self.docs.iter().map(|d| d.uid).collect::>()); let r = if self.depth == 0 { self.run_guarded(id, run) } else { self.run_nested(run) }; + if r.is_err() && self.depth == 0 { + self.batch_paint_docs.clear(); + } let r = r?; if self.depth == 0 { - self.inherit_new_art(); + // A color-mode history step restores exact new-art colors; selection inheritance + // must not immediately replace that restoration. + let restored = self.active().is_some_and(|d| match id { + "edit.undo" => d.history.redo.last().is_some_and(|e| e.color_mode_paints.is_some()), + "edit.redo" => d.history.undo.last().is_some_and(|e| e.color_mode_paints.is_some()), + _ => false, + }); + if !restored { + self.inherit_new_art(); + } + for uid in std::mem::take(&mut self.batch_paint_docs) { + if let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) + && let Some(e) = st.history.undo.last_mut() + && let Some((_, after)) = &mut e.color_mode_paints + { + after.clone_from(&self.paint); + e.recost_paints(); + st.history.trim(); + } + } } if let Some(open) = open { self.open_undo_groups_in_new_documents(&open); diff --git a/crates/engine/src/session/undo.rs b/crates/engine/src/session/undo.rs index c5f3f1595e..831f550bed 100644 --- a/crates/engine/src/session/undo.rs +++ b/crates/engine/src/session/undo.rs @@ -13,10 +13,11 @@ impl Session { /// [`Session::begin_undo_group`] with the undo step named `label` (else after its first edit). pub fn begin_named_undo_group(&mut self, label: Option) { + let paint = self.paint.clone(); if let Some(st) = self.active_mut() && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label }); + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label, paint }); } } @@ -27,9 +28,10 @@ impl Session { /// entry that made the document stays. pub(super) fn open_undo_groups_in_new_documents(&mut self, open: &[u64]) { let Some(label) = &self.explicit_undo_group else { return }; + let paint = self.paint.clone(); for st in &mut self.docs { if !open.contains(&st.uid) && st.undo_group.is_none() { - st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone() }); + st.undo_group = Some(UndoGroup { first: None, journal: vec![], steps: vec![], label: label.clone(), paint: paint.clone() }); } } } @@ -91,12 +93,26 @@ impl Session { continue; } let Some(g) = st.undo_group.take() else { continue }; + // Redo of a group that changed document color mode restores the new-art colors the + // whole group left, not the ones right after the conversion. + if !cancel + && let Some(first) = &g.first + && let Some(e) = st.history.undo.last_mut().filter(|e| Arc::ptr_eq(&e.doc, first)) + && let Some((_, after)) = &mut e.color_mode_paints + { + after.clone_from(&self.paint); + e.recost_paints(); + st.history.trim(); + } // Only while the group's step is still the newest one. if cancel && let Some(first) = g.first && st.history.undo.last().is_some_and(|e| Arc::ptr_eq(&e.doc, &first)) && let Some(e) = st.history.undo.pop() { + if let Some((before, _)) = e.color_mode_paints { + self.paint = before; + } st.doc = e.doc; st.selection = Arc::unwrap_or_clone(e.selection); deselect_hidden(&self.menu, &st.doc, &mut st.selection); @@ -194,11 +210,17 @@ impl Session { let journal = self.journal.len(); let st = self.active()?; let uid = st.uid; + let color_mode_paints = st + .undo_group + .as_ref() + .and_then(|g| g.first.as_ref()) + .and_then(|first| st.history.undo.last().filter(|e| Arc::ptr_eq(&e.doc, first)).and_then(|e| e.color_mode_paints.clone())); + let paint = self.paint.clone(); let joined = st.undo_group.as_ref().map(|g| (st.doc.clone(), st.selection.clone(), g.first.clone())); if joined.is_none() { self.begin_undo_group(); } - Some(UndoScope { uid, journal, joined }) + Some(UndoScope { uid, journal, joined, paint, color_mode_paints }) } /// End `scope` in its own document, whichever document is active now; undo groups open in other @@ -219,13 +241,19 @@ impl Session { if !cancel || !newest { return; } + let colors_changed = st.history.undo.last().and_then(|e| e.color_mode_paints.as_ref()) != scope.color_mode_paints.as_ref(); match &first { // The scope's first edit recorded the group's step. None => { st.history.undo.pop(); g.first = None; } - Some(f) if g.first.as_ref().is_some_and(|now| Arc::ptr_eq(now, f)) => {} + Some(f) if g.first.as_ref().is_some_and(|now| Arc::ptr_eq(now, f)) => { + if let Some(e) = st.history.undo.last_mut() { + e.color_mode_paints = scope.color_mode_paints; + e.recost_paints(); + } + } Some(_) => return, } st.doc = doc; @@ -235,6 +263,9 @@ impl Session { deselect_hidden(&menu, &st.doc, &mut st.selection); st.history.recost_last(&st.doc); st.revision += 1; + if colors_changed { + self.paint = scope.paint; + } self.journal.truncate(scope.journal); // The next commands take the cut entries' numbers, so no open undo group keeps them. for g in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) { diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index d1df8f5a16..7208f44f58 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -114,6 +114,120 @@ fn swatch_links_survive_mode_conversion() { assert_eq!(color, sw, "object and swatch converted identically"); } +/// The process color the active color settings give `c` in CMYK (the default intent). +fn to_cmyk(c: Color) -> Color { + let cms = cms::active(); + cms.convert(&c, cms::Model::Cmyk, cms.settings().intent) +} + +/// A document with colors that no 8-bit hex value holds: a plain fill, a three-stop gradient, a +/// pattern fill, a global swatch on one object's fill and at a 50% tint on another's stroke, and a +/// spot swatch on a third object → (session, plain, gradient, patterned, the swatch's two users, +/// the spot user). +fn reusable_paints_document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let plain = rect(&mut s, 0.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.123_457, 0.765_432, 0.333_333))); + let grad = rect(&mut s, 20.0, 0.0, 10.0, 10.0, json!("#000000")); + let stops = json!([ + {"offset": 0, "color": Color::rgb(0.912_345, 0.1, 0.2)}, + {"offset": 0.37, "color": Color::rgb(0.2, 0.876_543, 0.3)}, + {"offset": 1, "color": Color::rgb(0.3, 0.4, 0.654_321)}, + ]); + s.execute("paint.setFill", &json!({"ids": [grad.0], "gradient": {"kind": "linear", "stops": stops}})).unwrap(); + let tile = rect(&mut s, 40.0, 0.0, 10.0, 10.0, json!(Color::rgb(0.6, 0.111_111, 0.9))); + s.execute("object.pattern.make", &json!({"ids": [tile.0], "name": "Odd Tile", "edit": false})).unwrap(); + let patterned = rect(&mut s, 60.0, 0.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [patterned.0], "swatch": "Odd Tile"})).unwrap(); + s.execute("swatch.new", &json!({"name": "Shared", "color": Color::rgb(0.271_937, 0.314_773, 0.583_119), "global": true})).unwrap(); + let filled = rect(&mut s, 0.0, 20.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Shared"})).unwrap(); + let stroked = rect(&mut s, 20.0, 20.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Shared", "tint": 50})).unwrap(); + s.execute("swatch.new", &json!({"name": "Spot Lab", "color": Color::Lab { l: 61.5, a: 42.25, b: -17.75 }, "global": true})).unwrap(); + s.execute("swatch.setSpot", &json!({"name": "Spot Lab"})).unwrap(); + let spot = rect(&mut s, 40.0, 20.0, 10.0, 10.0, json!("#000000")); + s.execute("paint.setFill", &json!({"ids": [spot.0], "swatch": "Spot Lab"})).unwrap(); + (s, [plain, grad, patterned, filled, stroked, spot]) +} + +/// RGB → CMYK → Undo gives back the document bit for bit (no conversion back through the +/// profile), and Redo gives back the converted one. +#[test] +fn rgb_cmyk_undo_restores_every_color_exactly() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, _) = reusable_paints_document(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let converted = s.doc().unwrap().doc.clone(); + assert_ne!(*converted, *before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one Undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *converted); +} + +/// Each stop of a gradient converts on its own and keeps its offset. +#[test] +fn rgb_cmyk_converts_each_gradient_stop() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [_, grad, ..]) = reusable_paints_document(); + let Paint::Gradient(old) = fill_of(&s, grad) else { panic!("not a gradient") }; + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let Paint::Gradient(new) = fill_of(&s, grad) else { panic!("not a gradient") }; + assert_eq!(new.gradient.stops.len(), 3); + for (o, n) in old.gradient.stops.iter().zip(&new.gradient.stops) { + assert_eq!(n.offset, o.offset); + assert!(matches!(n.color, Color::Cmyk { .. }), "{:?}", n.color); + assert_eq!(n.color, to_cmyk(o.color)); + } +} + +/// A pattern's tile art converts, and the art filled with the pattern keeps it. +#[test] +fn rgb_cmyk_converts_a_pattern_tile() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [_, _, patterned, ..]) = reusable_paints_document(); + let tile = |s: &Session| s.doc().unwrap().doc.pattern("Odd Tile").unwrap().art[0].appearance.fill_paint().color().unwrap(); + let old = tile(&s); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert!(matches!(tile(&s), Color::Cmyk { .. }), "{:?}", tile(&s)); + assert_eq!(tile(&s), to_cmyk(old)); + assert!(matches!(fill_of(&s, patterned), Paint::Pattern { ref pattern, .. } if pattern == "Odd Tile"), "{:?}", fill_of(&s, patterned)); +} + +/// A global swatch used in two places converts once: both uses keep the link and take the +/// converted swatch color (the 50% tint at that tint), not a conversion of their own. +#[test] +fn rgb_cmyk_converts_a_shared_swatch_once() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [.., filled, stroked, _]) = reusable_paints_document(); + let shared = |s: &Session| s.doc().unwrap().doc.swatch("Shared").unwrap().paint.color().unwrap(); + let old = shared(&s); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let new = shared(&s); + assert_eq!(new, to_cmyk(old)); + assert_eq!(fill_of(&s, filled), Paint::Solid { color: new, swatch: Some("Shared".into()), tint: 1.0 }); + let stroke = s.doc().unwrap().doc.node(stroked).unwrap().appearance.stroke_paint(); + assert_eq!(stroke, Paint::Solid { color: new.tinted(0.5), swatch: Some("Shared".into()), tint: 0.5 }); +} + +/// A spot color stays a spot color: its Lab definition, its link and its own plate are kept. +#[test] +fn rgb_cmyk_keeps_a_spot_color() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let (mut s, [.., spot]) = reusable_paints_document(); + let swatch = |s: &Session| s.doc().unwrap().doc.swatch("Spot Lab").unwrap().clone(); + let (old_swatch, old_fill) = (swatch(&s), fill_of(&s, spot)); + s.execute("object.convertDocumentColorMode", &json!({"mode": "cmyk"})).unwrap(); + assert_eq!(swatch(&s), old_swatch); + assert!(swatch(&s).spot); + assert_eq!(fill_of(&s, spot), old_fill); + let plates = s.execute("color.plates", &json!({})).unwrap(); + assert!(plates["plates"].as_array().unwrap().iter().any(|p| p["name"] == "Spot Lab"), "{plates}"); +} + #[test] fn gamut_check_flags_unprintable_colours() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/src/tests/history_mem.rs b/crates/engine/src/tests/history_mem.rs index af5d495528..d3cbbda95f 100644 --- a/crates/engine/src/tests/history_mem.rs +++ b/crates/engine/src/tests/history_mem.rs @@ -179,3 +179,42 @@ fn redo_during_an_interaction_keeps_the_history_and_the_document_in_step() { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(first_x(&s), start); } + +#[test] +fn color_mode_paint_snapshots_count_toward_the_history_budget() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":100,"height":100})).unwrap(); + let mut appearance = s.new_art(); + appearance.effects.push(vectorcraft_doc::Effect { + id: "stylize.dropShadow".into(), + visible: true, + params: json!({"color":"#ab6739", "retainedTemplateData":"x".repeat(128*1024)}), + }); + s.paint.appearance = Some(appearance); + let original = s.paint.clone(); + s.active_mut().unwrap().history.byte_budget = 64 * 1024; + for i in 0..12 { + s.execute("file.documentColorMode", &json!({"mode": if i%2 == 0 {"cmyk"} else {"rgb"}})).unwrap(); + } + let st = s.doc().unwrap(); + assert_eq!(st.history.undo.len(), History::MIN_STEPS); + assert!(st.history.undo.iter().all(|e| e.bytes > 256 * 1024), "both large templates count even without artwork"); + assert!(st.doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty()))); + let retained = st.history.bytes(); + let after = s.paint.clone(); + for _ in 0..History::MIN_STEPS { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.doc().unwrap().history.redo.len(), History::MIN_STEPS); + assert!(s.doc().unwrap().history.redo.iter().all(|e| e.bytes > 256 * 1024)); + assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024, "turning entries must not double-count paint snapshots"); + for _ in 0..History::MIN_STEPS { + s.execute("edit.redo", &json!({})).unwrap(); + } + assert_eq!(s.paint, after); + assert!(s.doc().unwrap().history.bytes().abs_diff(retained) < 64 * 1024); + assert_eq!( + s.paint.appearance.as_ref().unwrap().effects[0].params["retainedTemplateData"], + original.appearance.unwrap().effects[0].params["retainedTemplateData"] + ); +} diff --git a/crates/engine/src/tests/paintproxy.rs b/crates/engine/src/tests/paintproxy.rs index 9ddbc288eb..a9e832bb36 100644 --- a/crates/engine/src/tests/paintproxy.rs +++ b/crates/engine/src/tests/paintproxy.rs @@ -217,6 +217,19 @@ fn live_previews_remember_only_the_committed_colour() { assert_eq!(hexes(&s), ["#300000"], "a preview undone by a failed one is forgotten"); } +#[test] +fn ordinary_preview_keeps_paint_changed_during_the_interaction() { + let mut s = session(); + rect(&mut s); + s.begin_interaction("Move").unwrap(); + s.preview("paint.setFill", &json!({"color": "#123456"})).unwrap(); + let paint = s.paint.clone(); + s.preview("object.transform", &json!({"matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + assert_eq!(s.paint, paint); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint, paint); +} + #[test] fn focus_false_keeps_the_active_proxy() { let mut s = session(); diff --git a/crates/engine/src/tests/swatches.rs b/crates/engine/src/tests/swatches.rs index 406c269262..c0145d20d4 100644 --- a/crates/engine/src/tests/swatches.rs +++ b/crates/engine/src/tests/swatches.rs @@ -192,6 +192,694 @@ fn document_color_mode_converts_the_tile_that_pattern_cancel_puts_back() { assert_eq!(tile, [red]); } +/// The `color` stored in each effect of `a` (the object's, then each fill's and stroke's) that has +/// one, read as a color, and the `lightColor` of each effect that has one. +fn effect_colors(a: &vectorcraft_doc::Appearance) -> (Vec, Vec) { + let effects: Vec<&vectorcraft_doc::Effect> = a.effects.iter().chain(a.items.iter().flat_map(|i| i.effects())).collect(); + let colors = effects + .iter() + .filter_map(|e| e.params.get("color")) + .map(|v| v.as_str().map_or_else(|| serde_json::from_value(v.clone()).unwrap(), |h| Color::from_hex(h).unwrap())) + .collect(); + (colors, effects.iter().filter_map(|e| e.params.get("lightColor").cloned()).collect()) +} + +/// Document Color Mode converts the colors that effects draw with, on objects (the effects of a +/// fill included) and in graphic styles, as it converts the art. An effect that drew its default +/// color keeps the converted default as its own; the light color of a 3D effect stays RGB. The +/// reply counts the object's effect colors, and one undo step takes them back. +#[test] +fn document_color_mode_converts_effect_colors() { + let build = |effects: bool| { + let mut s = session(); + let id = rect(&mut s); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [id.0]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [id.0]})); + if effects { + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.dropShadow", "params": {"color": "#ff0000"}})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.outerGlow", "item": null})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "stylize.innerGlow", "item": 0, "params": {"color": "#ff0000"}})); + run(&mut s, "effect.apply", json!({"ids": [id.0], "effect": "threeD.rotate", "item": null})); + // The Outer Glow draws its default color, as in a file that leaves `color` out. + s.edit("Default color", |d, _| { + let glow = &mut d.node_mut(id).unwrap().appearance.effects[1]; + assert_eq!(glow.id, "stylize.outerGlow"); + if let Some(p) = glow.params.as_object_mut() { + p.remove("color"); + } + Ok(()) + }) + .unwrap(); + } + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "graphicStyle.new", json!({"name": "Glow"})); + (s, id) + }; + let (mut s, id) = build(true); + let object = |s: &Session| effect_colors(&doc(s).node(id).unwrap().appearance); + let style = |s: &Session| effect_colors(&doc(s).graphic_style("Glow").unwrap().appearance); + let before = (object(&s), style(&s)); + assert_eq!(before.0.0.len(), 2, "the Outer Glow stores no color: {before:?}"); + assert_eq!(before.1.0.len(), 2, "{before:?}"); + let undo = s.doc().unwrap().history.undo.len(); + + let changed = run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"}))["changed"].as_u64().unwrap(); + let red = first_fill(doc(&s).node(id).unwrap()); + assert!(matches!(red, Color::Cmyk { .. }), "{red:?}"); + for (colors, lights) in [object(&s), style(&s)] { + assert_eq!(colors.len(), 3, "{colors:?}"); + // Drop Shadow, then the Outer Glow's default yellow, then the fill's Inner Glow. + assert_eq!([colors[0], colors[2]], [red; 2]); + assert!(matches!(colors[1], Color::Cmyk { .. }), "{colors:?}"); + assert_eq!(lights, [json!("#ffffff")]); + } + // The three effect colors on the object count; those of the graphic style, like its paints, do not. + let (mut plain, _) = build(false); + let without = run(&mut plain, "file.documentColorMode", json!({"mode": "cmyk"}))["changed"].as_u64().unwrap(); + assert_eq!(changed, without + 3); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!((object(&s), style(&s)), before); +} + +/// Document Color Mode converts the series paints and label styles a graph keeps, so a graph drawn +/// again after the switch paints its series and labels in the new mode. +#[test] +fn document_color_mode_converts_the_paints_a_graph_keeps() { + let mut s = session(); + let red = rect(&mut s); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [red.0]})); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let id = NodeId( + run(&mut s, "graph.create", json!({"type": "column", "x": 10, "y": 10, "width": 60, "height": 40, "csv": csv}))["id"].as_u64().unwrap(), + ); + let part = |s: &Session, name: &str| -> vectorcraft_doc::Node { + let g = doc(s).node(id).unwrap(); + g.children().unwrap().iter().find(|c| c.name.as_deref() == Some(name)).map(|c| (**c).clone()).unwrap_or_else(|| panic!("no {name}")) + }; + let series = part(&s, "2024").id; + let label = part(&s, "Axes").children().unwrap().iter().find(|c| matches!(c.kind, vectorcraft_doc::NodeKind::Text(_))).unwrap().id; + for target in [series, label] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [target.0]})); + } + let kept = |s: &Session| -> Vec { + let g = doc(s).node(id).unwrap().extras().graph.as_deref().unwrap().clone(); + let labels = [g.label_styles.values, g.label_styles.categories, g.label_styles.legend]; + let labels = labels.into_iter().flatten().map(|st| st.fill.color().unwrap()); + g.series_paints.iter().filter_map(|p| p.fill.as_ref()?.color()).chain(labels).collect() + }; + let before = kept(&s); + assert_eq!(before, [Color::rgb(1.0, 0.0, 0.0); 2]); + let undo = s.doc().unwrap().history.undo.len(); + + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + let cmyk = first_fill(doc(&s).node(red).unwrap()); + assert!(matches!(cmyk, Color::Cmyk { .. }), "{cmyk:?}"); + assert_eq!(kept(&s), [cmyk; 2]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + // Drawn again from new data, the series keeps the converted color. + run(&mut s, "graph.setData", json!({"id": id.0, "rows": [[2, 3], [4, 5]]})); + let marks = part(&s, "2024"); + assert!(marks.children().unwrap().iter().all(|m| m.appearance.fill_paint().color() == Some(cmyk)), "{marks:?}"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert_eq!(kept(&s), before); +} + +/// Document Color Mode converts the fill and stroke that new art takes, so an object drawn after +/// the switch gets the same colors in the new mode as the art drawn before it. +#[test] +fn document_color_mode_converts_the_colors_new_art_takes() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + let old = rect(&mut s); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + let paints = |a: &vectorcraft_doc::Appearance| (a.fill_paint().color(), a.stroke().and_then(|st| st.paint.color())); + let converted = paints(&doc(&s).node(old).unwrap().appearance); + assert!(matches!(converted, (Some(Color::Cmyk { .. }), Some(Color::Cmyk { .. }))), "{converted:?}"); + assert_eq!(paints(&s.new_art()), converted); + let new = rect(&mut s); + assert_eq!(paints(&doc(&s).node(new).unwrap().appearance), converted); + + // As a `command.batch` step too; a batch that fails leaves them as they were. + for fails in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + let before = paints(&s.new_art()); + let mut steps = vec![json!({"command": "file.documentColorMode", "params": {"mode": "cmyk"}})]; + if fails { + steps.push(json!({"command": "no.such.command"})); + } + let r = s.execute("command.batch", &json!({"commands": steps})); + assert_eq!(r.is_err(), fails, "{r:?}"); + assert_eq!(paints(&s.new_art()), if fails { before } else { converted }, "fails {fails}"); + } +} + +#[test] +fn color_mode_undo_restores_original_new_art_colors_and_redo_reapplies_them() { + for batch in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "paint.setStroke", json!({"color": "#123456"})); + let before = s.paint.clone(); + if batch { + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}} + ]}), + ); + } else { + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + } + let after = s.paint.clone(); + assert_ne!(before.fill, after.fill); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before, "batch {batch}: exact original values"); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after, "batch {batch}"); + let id = rect(&mut s); + assert_eq!(doc(&s).node(id).unwrap().appearance.fill_paint(), after.fill); + } +} + +#[test] +fn color_mode_batch_undo_restores_paints_from_before_the_batch() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "paint.setFill", "params": {"color": "#0000ff"}}, + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}} + ]}), + ); + let after = s.paint.clone(); + assert_ne!(before.fill, after.fill); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +#[test] +fn color_mode_group_undo_restores_paints_from_before_the_group() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + s.begin_undo_group(); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + s.end_undo_group(false); + let after = s.paint.clone(); + assert_ne!(before.fill, after.fill); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +/// Undo and Redo of an undo group that converts the document color mode and then changes the +/// stroke weight of new art restore the whole new-art template, not only its paints. +#[test] +fn color_mode_group_undo_restores_the_new_art_stroke_weight() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + s.begin_undo_group(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + run(&mut s, "stroke.set", json!({"weight": 7})); + s.end_undo_group(false); + let after = s.paint.clone(); + assert_eq!(after.stroke_width, 7.0); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +/// With New Art Has Basic Appearance off, Redo of a batch that converts the color mode and then +/// applies an effect to the selected object restores the appearance new art took from that object. +#[test] +fn color_mode_batch_redo_keeps_the_appearance_new_art_inherited() { + let mut s = session(); + run(&mut s, "prefs.set", json!({"key": "newArtBasic", "value": false})); + rect(&mut s); + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "effect.apply", "params": {"effect": "stylize.dropShadow"}} + ]}), + ); + let after = s.paint.clone(); + assert!(after.appearance.is_some()); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +/// Redo of a batch or undo group that converts the document color mode and then changes the paints +/// new art takes restores the paints as the whole step left them. +#[test] +fn color_mode_redo_of_a_group_restores_the_paints_the_group_left() { + let converted = { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + s.paint.clone() + }; + for batch in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let before = s.paint.clone(); + if batch { + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#0000ff"}} + ]}), + ); + } else { + s.begin_undo_group(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + s.end_undo_group(false); + } + let after = s.paint.clone(); + assert_ne!(after.fill, converted.fill, "batch {batch}"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before, "batch {batch}"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after, "batch {batch}: the group's final paints"); + } +} + +fn color_mode_restores_paints_when_conversion_changes_none(batch: bool, convert: bool) { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let before = s.paint.clone(); + assert!(before.fill.is_none()); + assert!(before.stroke.is_none()); + if batch { + run( + &mut s, + "command.batch", + json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk", "convert": convert}}, + {"command": "paint.setFill", "params": {"color": "#0000ff"}} + ]}), + ); + } else { + s.begin_undo_group(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk", "convert": convert})); + assert_eq!(s.paint, before, "the conversion leaves both paints unchanged"); + run(&mut s, "paint.setFill", json!({"color": "#0000ff"})); + s.end_undo_group(false); + } + let after = s.paint.clone(); + assert_ne!(after.fill, before.fill); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before, "batch {batch}: undo restores the group's starting paints"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, after, "batch {batch}: redo restores the group's final paints"); +} + +#[test] +fn color_mode_group_restores_paints_when_conversion_changes_none() { + color_mode_restores_paints_when_conversion_changes_none(false, true); +} + +#[test] +fn color_mode_batch_restores_paints_when_conversion_changes_none() { + color_mode_restores_paints_when_conversion_changes_none(true, true); +} + +#[test] +fn color_mode_group_without_conversion_restores_paints() { + color_mode_restores_paints_when_conversion_changes_none(false, false); +} + +#[test] +fn color_mode_batch_without_conversion_restores_paints() { + color_mode_restores_paints_when_conversion_changes_none(true, false); +} + +#[test] +fn color_mode_ungrouped_skips_unchanged_paint_snapshot() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"none": true})); + run(&mut s, "paint.setStroke", json!({"none": true})); + let before = s.paint.clone(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + assert_eq!(s.paint, before); + assert!(s.doc().unwrap().history.undo.last().unwrap().color_mode_paints.is_none()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, before); +} + +/// A failing batch that settles a pending color-mode preview keeps the converted paints with the +/// converted document. +#[test] +fn a_failed_batch_keeps_the_paints_of_a_settled_color_mode_preview() { + let converted = { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + s.paint.clone() + }; + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + s.begin_interaction("Document Color Mode").unwrap(); + s.preview("file.documentColorMode", &json!({"mode": "cmyk"})).unwrap(); + let r = s.execute("command.batch", &json!({"commands": [{"command": "no.such.command", "params": {}}]})); + assert!(r.is_err()); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, converted); +} + +#[test] +fn canceling_a_batch_preview_restores_the_document_and_paints() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}]})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn accepting_a_batch_preview_restores_new_art_paints_on_undo_and_redo() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &json!({"commands": [{"command": "file.documentColorMode", "params": {"mode": "cmyk"}}]})).unwrap(); + assert_eq!(s.paint, before); + s.commit_interaction().unwrap(); + let after = s.paint.clone(); + assert_ne!(after.fill, before.fill); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + assert_eq!(s.journal.len(), journal + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Cmyk); + assert_eq!(s.paint, after); +} + +#[test] +fn batch_preview_with_later_paint_restores_or_keeps_the_final_paint() { + let commands = json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#123456"}} + ]}); + let mut expected = color_mode_preview_session(false); + run(&mut expected, "command.batch", commands.clone()); + let final_paint = expected.paint.clone(); + + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &commands).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(s.journal.len(), journal); + + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &commands).unwrap(); + s.commit_interaction().unwrap(); + assert_eq!(s.paint, final_paint); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + assert_eq!(s.journal.len(), journal + 1); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, final_paint); +} + +#[test] +fn failed_batch_preview_leaves_no_document_paint_or_journal_change() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let journal = s.journal.len(); + s.begin_interaction("Batch Preview").unwrap(); + s.preview( + "command.batch", + &json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#654321"}} + ]}), + ) + .unwrap(); + let result = s.preview( + "command.batch", + &json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#123456"}}, + {"command": "no.such.command", "params": {}} + ]}), + ); + assert!(result.is_err()); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + s.cancel_interaction().unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn batch_preview_restores_paint_when_mode_conversion_does_not_change_it() { + let mut s = session(); + s.paint.fill = Paint::None; + s.paint.stroke = Paint::None; + s.paint.appearance = None; + let before = s.paint.clone(); + let commands = json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "paint.setFill", "params": {"color": "#123456"}} + ]}); + s.begin_interaction("Batch Preview").unwrap(); + s.preview("command.batch", &commands).unwrap(); + s.commit_interaction().unwrap(); + let after = s.paint.clone(); + assert_ne!(after, before); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); +} + +#[test] +fn batch_preview_that_switches_documents_rolls_back_every_step() { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let journal = s.journal.len(); + let docs = s.docs.len(); + let active = s.active; + s.begin_interaction("Batch Preview").unwrap(); + let result = s.preview( + "command.batch", + &json!({"commands": [ + {"command": "file.documentColorMode", "params": {"mode": "cmyk"}}, + {"command": "file.new", "params": {"width": 100, "height": 100}} + ]}), + ); + assert!(result.is_err()); + assert_eq!(s.docs.len(), docs); + assert_eq!(s.active, active); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.paint, before); + s.cancel_interaction().unwrap(); + assert_eq!(s.journal.len(), journal); +} + +#[test] +fn color_mode_undo_restores_template_paints_and_effect_colors() { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + run(&mut s, "paint.setStroke", json!({"color": "#123456"})); + let mut appearance = s.new_art(); + appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"color":"#d37a42"}), visible: true }); + s.paint.appearance = Some(appearance); + let before = s.paint.clone(); + run(&mut s, "file.documentColorMode", json!({"mode": "cmyk"})); + let after = s.paint.clone(); + assert_ne!(before.appearance, after.appearance); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + let id = rect(&mut s); + assert_eq!(doc(&s).node(id).unwrap().appearance.effects, after.appearance.unwrap().effects); +} + +#[test] +fn color_mode_cancelled_joined_scope_restores_paints_and_history_metadata() { + for converted_before_scope in [false, true] { + let mut s = session(); + run(&mut s, "paint.setFill", json!({"color": "#ab6739"})); + let original = s.paint.clone(); + s.begin_undo_group(); + rect(&mut s); + if converted_before_scope { + run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"})); + } + let before_scope = s.paint.clone(); + let mode = doc(&s).color_mode; + let scope = s.begin_undo_scope().unwrap(); + run(&mut s, "file.documentColorMode", json!({"mode": if converted_before_scope {"rgb"} else {"cmyk"}})); + s.end_undo_scope(scope, true); + assert_eq!(s.paint, before_scope); + assert_eq!(doc(&s).color_mode, mode); + s.end_undo_group(false); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, if converted_before_scope { original } else { before_scope.clone() }); + run(&mut s, "edit.redo", json!({})); + assert_eq!(doc(&s).color_mode, mode); + assert_eq!(s.paint, before_scope, "redo must not reapply the cancelled conversion"); + } +} + +fn color_mode_preview_session(selected: bool) -> Session { + let mut s = session(); + if selected { + rect(&mut s); + } + run(&mut s, "paint.setFill", json!({"color": "#808080"})); + run(&mut s, "paint.setStroke", json!({"color": "#123456"})); + let mut appearance = s.new_art(); + appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params: json!({"color":"#d37a42"}), visible: true }); + s.paint.appearance = Some(appearance); + s +} + +#[test] +fn color_mode_preview_commit_converts_new_art_once_and_keeps_exact_history() { + for selected in [false, true] { + let mut s = color_mode_preview_session(selected); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + let mut expected = color_mode_preview_session(false); + expected.paint = before.clone(); + run(&mut expected, "file.documentColorMode", json!({"mode":"cmyk", "grays":"black"})); + // The template is intentionally independent from selected artwork. + let after = expected.paint.clone(); + s.begin_interaction("Document Color Mode").unwrap(); + for grays in ["profile", "black", "profile", "black"] { + s.preview("file.documentColorMode", &json!({"mode":"cmyk", "grays":grays})).unwrap(); + assert_eq!(s.paint, before, "preview must leave new-art paints tentative"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + } + s.commit_interaction().unwrap(); + assert_eq!(s.paint, after); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + let e = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(e.color_mode_paints, Some((before.clone(), after.clone()))); + let history_bytes = e.bytes; + assert!(history_bytes >= 2 * std::mem::size_of::()); + for _ in 0..3 { + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + assert_eq!(doc(&s).color_mode, vectorcraft_doc::ColorMode::Rgb); + assert_eq!(s.doc().unwrap().history.redo.last().unwrap().color_mode_paints, Some((before.clone(), after.clone()))); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + assert_eq!(s.doc().unwrap().history.undo.last().unwrap().bytes, history_bytes); + } + s.commit_interaction().unwrap(); + assert_eq!(s.paint, after, "a second commit cannot convert twice"); + } +} + +#[test] +fn color_mode_preview_cancel_replacement_and_failure_do_not_convert_new_art() { + for finish in ["cancel", "noop", "failed", "mode-only"] { + let mut s = color_mode_preview_session(true); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + s.begin_interaction("Document Color Mode").unwrap(); + s.preview("file.documentColorMode", &json!({"mode":"cmyk"})).unwrap(); + match finish { + "cancel" => s.cancel_interaction().unwrap(), + "noop" => { + s.preview("file.documentColorMode", &json!({"mode":"rgb"})).unwrap(); + s.commit_interaction().unwrap(); + } + "failed" => { + assert!(s.preview("file.documentColorMode", &json!({"mode":"invalid"})).is_err()); + s.commit_interaction().unwrap(); + } + _ => { + s.preview("file.documentColorMode", &json!({"mode":"cmyk", "convert":false})).unwrap(); + s.commit_interaction().unwrap(); + } + } + assert_eq!(s.paint, before, "{finish}"); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + usize::from(finish == "mode-only"), "{finish}"); + } +} + +#[test] +fn color_mode_preview_commit_joins_paint_history_and_group_cancel_restores_it() { + for cancel in [false, true] { + let mut s = color_mode_preview_session(false); + let before = s.paint.clone(); + let depth = s.doc().unwrap().history.undo.len(); + s.begin_undo_group(); + // Existing grouped metadata must keep its original snapshot when the preview commits. + run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"})); + s.begin_interaction("Document Color Mode").unwrap(); + s.preview("object.convertDocumentColorMode", &json!({"mode":"rgb"})).unwrap(); + s.commit_interaction().unwrap(); + let after = s.paint.clone(); + let e = s.doc().unwrap().history.undo.last().unwrap(); + assert_eq!(e.color_mode_paints, Some((before.clone(), after.clone()))); + assert_eq!(s.doc().unwrap().history.undo.len(), depth + 1); + s.end_undo_group(cancel); + if cancel { + assert_eq!(s.paint, before); + assert_eq!(s.doc().unwrap().history.undo.len(), depth); + } else { + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + } + } +} + #[test] fn grouped_spot_swatches_print_on_their_own_plate() { let mut s = session(); @@ -529,6 +1217,82 @@ fn global_swatch_edits_reach_opacity_mask_art() { assert_eq!(mask_fill(&s).color(), Some(Color::rgb(1.0, 1.0, 1.0))); } +#[test] +fn color_mode_converts_freeform_defaults_templates_and_stored_graph_paints() { + use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint}; + let mut s = session(); + let id = NodeId( + run( + &mut s, + "graph.create", + json!({"type":"column", "x":0, "y":0, "width":60, "height":40, + "csv":",2024\nQ1,3\nQ2,5"}), + )["id"] + .as_u64() + .unwrap(), + ); + let mut gradient = GradientPaint::new(Gradient::new(GradientKind::Freeform, vec![])); + gradient.set_freeform(Freeform { + points: vec![ + FreeformPoint::new((0.0, 0.0).into(), Color::rgb(0.8, 0.2, 0.1)), + FreeformPoint::new((20.0, 10.0).into(), Color::rgb(0.1, 0.3, 0.9)), + ], + lines: vec![vec![0, 1]], + ..Default::default() + }); + let paint = Paint::Gradient(Box::new(gradient)); + s.edit("Stored graph paint", |d, _| { + d.node_mut(id).unwrap().extras_mut().graph.as_mut().unwrap().series_paints = + vec![vectorcraft_doc::SeriesPaint { fill: Some(paint.clone()), stroke: Some(paint.clone()), ..Default::default() }]; + Ok(()) + }) + .unwrap(); + s.paint.fill = paint.clone(); + s.paint.stroke = paint.clone(); + s.paint.stroke_width = 1.0; + s.paint.appearance = None; + s.paint.appearance = Some(s.new_art()); + let before = s.paint.clone(); + let stored = |s: &Session| doc(s).node(id).unwrap().extras().graph.as_ref().unwrap().series_paints.clone(); + let before_graph = stored(&s); + run(&mut s, "file.documentColorMode", json!({"mode":"cmyk"})); + let after = s.paint.clone(); + let after_graph = stored(&s); + let converted = |paint: &Paint| { + let Paint::Gradient(g) = paint else { panic!("expected gradient") }; + assert!(g.gradient.stops.iter().all(|p| matches!(p.color, Color::Cmyk { .. }))); + assert!(g.freeform.as_ref().unwrap().points.iter().all(|p| matches!(p.color, Color::Cmyk { .. }))); + }; + converted(&after.fill); + converted(&after.stroke); + converted(&after.appearance.as_ref().unwrap().fill_paint()); + converted(&after.appearance.as_ref().unwrap().stroke().unwrap().paint); + converted(after_graph[0].fill.as_ref().unwrap()); + converted(after_graph[0].stroke.as_ref().unwrap()); + run(&mut s, "edit.undo", json!({})); + assert_eq!(s.paint, before); + assert_eq!(stored(&s), before_graph); + run(&mut s, "edit.redo", json!({})); + assert_eq!(s.paint, after); + assert_eq!(stored(&s), after_graph); + let new = rect(&mut s); + let new_fill = doc(&s).node(new).unwrap().appearance.fill_paint(); + converted(&new_fill); + let control_colors = |paint: &Paint| { + let Paint::Gradient(g) = paint else { panic!("expected gradient") }; + g.freeform.as_ref().unwrap().points.iter().map(|p| p.color).collect::>() + }; + assert_eq!(control_colors(&new_fill), control_colors(&after.fill)); + run(&mut s, "graph.setData", json!({"id":id.0, "rows":[[2], [4]]})); + assert_eq!(stored(&s), after_graph); + let graph = doc(&s).node(id).unwrap(); + let series = graph.children().unwrap().iter().find(|n| n.name.as_deref() == Some("2024")).unwrap(); + for mark in series.children().unwrap() { + converted(&mark.appearance.fill_paint()); + converted(&mark.appearance.stroke().unwrap().paint); + } +} + /// The fills of graph design "Bar" and of the art of brush "Holder", as `place: color, link`. fn fills_outside_the_layers(s: &Session) -> Vec { let d = doc(s); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 15d0b7004d..273c0291ef 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -478,7 +478,11 @@ fn adjust_fields(ui: &mut egui::Ui, d: &mut Dialog) -> bool { for (key, label, width) in [("points", tl!("Points"), 220.0), ("color", tl!("Color"), 120.0)] { if d.fields.contains_key(key) { widgets::label_row(ui, label, LABEL_W, |ui| { - form::text(ui, d, key, width); + if key == "color" { + form::color_text(ui, d, key, width); + } else { + form::text(ui, d, key, width); + } }); } } @@ -710,13 +714,8 @@ fn drop_shadow_fields(ui: &mut egui::Ui, d: &mut Dialog, unit: vectorcraft_doc:: if widgets::radio(ui, tl!("Color"), !darkness, true) { d.fields.insert("shade".into(), json!("color")); } - ui.add_enabled_ui(!darkness, |ui| match d.fields.get("color") { - Some(Value::String(_)) | None => { - form::text(ui, d, "color", 128.0); - } - Some(other) => { - widgets::dim_label(ui, &other.to_string()); - } + ui.add_enabled_ui(!darkness, |ui| { + form::color_text(ui, d, "color", 128.0); }); ui.end_row(); if widgets::radio(ui, tl!("Darkness"), darkness, true) { diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 47567e51e7..faad934c2a 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -155,6 +155,31 @@ pub(super) fn text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> text_edit(ui, d, key, width).changed() } +/// A parameter value that is a color object (`{"model": "cmyk", …}`, as Document Color Mode or an +/// imported file stores an effect's color), read as a color. `None` for any other value. +pub(super) fn color_object(v: &Value) -> Option { + v.is_object().then(|| serde_json::from_value(v.clone()).ok()).flatten() +} + +/// [`text`] for a color parameter `key`: a color object ([`color_object`]) shows as its hex and +/// stays as it is until the text is edited; any other value that isn't text shows dimmed. +pub(super) fn color_text(ui: &mut egui::Ui, d: &mut Dialog, key: &str, width: f32) -> bool { + let Some(v) = d.fields.get(key).cloned() else { return text(ui, d, key, width) }; + if let Some(c) = color_object(&v) { + d.fields.insert(key.into(), json!(c.to_hex())); + let changed = text(ui, d, key, width); + if !changed { + d.fields.insert(key.into(), v); + } + return changed; + } + if v.is_string() { + return text(ui, d, key, width); + } + crate::widgets::dim_label(ui, &v.to_string()); + false +} + /// [`text`] for a row whose visible meaning is not the immediately preceding label widget /// (Export for Screens' Range field follows its radio buttons): screen readers name the field /// `name`, already translated. The pending label is still consumed, so it cannot name a later @@ -432,9 +457,19 @@ pub(super) fn param_fields( changed = true; } } - other => { - ui.label(egui::RichText::new(other.to_string()).color(t.text_dim).size(11.0)); - } + // A color object shows as its hex; typing in the field stores the typed text. + other => match color_object(&other) { + Some(c) => { + let mut s = c.to_hex(); + if ui.add(egui::TextEdit::singleline(&mut s).desired_width(140.0)).changed() { + d.fields.insert(k.clone(), json!(s)); + changed = true; + } + } + None => { + ui.label(egui::RichText::new(other.to_string()).color(t.text_dim).size(11.0)); + } + }, } }); ui.end_row(); diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4fc17b097e..ef3bf88483 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -199,6 +199,33 @@ fn effect_dialog_refuses_a_color_it_cannot_draw() { } } +/// After File › Document Color Mode, a Drop Shadow's, an Outer Glow's and a Shift to Color's +/// dialog show the converted color as its hex in an editable field, and OK without editing it +/// keeps the color. +#[test] +fn effect_dialogs_edit_a_color_that_document_color_mode_converted() { + for effect in ["stylize.dropShadow", "stylize.outerGlow", "adjust.shiftToColor"] { + let mut app = app(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("effect.apply", json!({"ids": [id], "effect": effect, "item": null, "params": {"color": "#ff0000"}})).unwrap(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let color = |app: &VectorcraftApp| { + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params["color"].clone() + }; + let converted = color(&app); + let hex = serde_json::from_value::(converted.clone()) + .unwrap_or_else(|e| panic!("{effect}: {converted}: {e}")) + .to_hex(); + app.run("effect.dialog", json!({"effect": effect, "index": 0, "item": null})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert!(text.lines().any(|l| l.trim() == hex), "{effect}: no {hex} in {text}"); + assert!(!text.contains("\"model\""), "{effect}: {text}"); + confirm(&mut app).unwrap(); + assert_eq!(color(&app), converted, "{effect}"); + } +} + #[test] fn raster_filter_dialogs_preview_and_apply() { for (effect, key, value) in [ diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index cf02301a62..7670d8cdff 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -238,11 +238,12 @@ fn the_picked_mode_comes_back_after_a_restart() { app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); app.run("select.none", json!({})).unwrap(); let ctx = egui::Context::default(); - assert_eq!(slider_labels(&mut app, &ctx), ["R", "G", "B"], "the white default is RGB"); + assert_eq!(slider_labels(&mut app, &ctx), ["C", "M", "Y", "K"], "the white default follows the CMYK document"); let _ = ctx.run_ui(Default::default(), |ui| { let tgt = target(&app, ui); set_mode(&mut app, &tgt, Mode::Cmyk); }); + assert_eq!(app.ui.color_mode, Some(Mode::Cmyk)); assert_eq!(slider_labels(&mut app, &ctx), ["C", "M", "Y", "K"]); // Quit and start again: the saved UI state comes back, the session and the panel are new. let saved: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); @@ -250,7 +251,8 @@ fn the_picked_mode_comes_back_after_a_restart() { app.ui = saved.sanitized(); app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); - assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Rgb { .. })), "the defaults start as RGB white"); + assert_eq!(app.ui.color_mode, Some(Mode::Cmyk), "the picked mode comes back"); + assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Cmyk { .. })), "the defaults follow the CMYK document"); let ctx = egui::Context::default(); assert_eq!(slider_labels(&mut app, &ctx), ["C", "M", "Y", "K"]); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 7c0499a063..89ec257683 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -625,9 +625,13 @@ remembers its options, so the next save reuses them; a document not yet saved as VectorCraft Options the last native Save or Save As used (not its artboards, nor Use Compression). A PDF opened with `pages`, `cropTo` or `password` is only part of the file, so Save asks for a new name instead of writing it back. `file.documentColorMode {mode, convert?, intent?, grays?}` switches the document color mode, converting the colors of -the art (opacity masks included), symbols, graph designs, pattern tiles (with the tile that pattern editing's Cancel -puts back), graphic styles, brushes (their art and a Hue Shift key color) and swatches through the color settings, in -one undo step (`object.convertDocumentColorMode` is an alias kept for older scripts). Gray colors stay Gray and print +the art (opacity masks, effect colors and the series paints and label styles that graphs keep included), symbols, +graph designs, pattern tiles (with the tile that pattern editing's Cancel puts back), graphic styles (their effect +colors included), brushes (their art and a Hue Shift key color) and swatches through the color settings, in one undo +step (`object.convertDocumentColorMode` is an alias kept for older scripts). It also converts the fill, stroke and +effect colors that new art takes; Undo restores their original values and Redo reapplies the conversion. The light +colors of 3D effects stay RGB. +Gray colors stay Gray and print on the black plate only. RGB grays are colors like any other: to CMYK they separate through the profile into four-colour greys and a rich black, as Illustrator converts them. `grays: "black"` puts RGB greys with R = G = B on the black plate instead, K = their grey value (the inks Edit Colors › diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 45ec87471c..479bd26d45 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1029,6 +1029,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. + - **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. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. - **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them. From abc220166425ae1751dd24805b3cc6e69f7f1e1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:28:32 +0700 Subject: [PATCH 022/482] Select: the font Same commands skip type on a template sublayer Squashed from #5566 onto main. --- crates/engine/src/cmd/docmenu.rs | 2 +- crates/engine/src/tests/menucmds.rs | 35 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 0f13a502e9..f2972a1f13 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -337,7 +337,7 @@ fn same_text(s: &mut Session, cmd: &str, eq: fn(&CharStyle, &CharStyle) -> bool) /// object inside two selected objects is given twice. The walk stops when `f` returns false. fn each_selected_text(s: &Session, mut f: impl FnMut(NodeId) -> bool) { fn inside(n: &Node, f: &mut impl FnMut(NodeId) -> bool) -> bool { - if !n.visible || n.locked { + if !n.visible || n.locked || n.is_template() { return true; } if matches!(n.kind, NodeKind::Text(_)) && !f(n.id) { diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index fe0783a135..e47cabc5f1 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2049,6 +2049,41 @@ fn select_same_font_takes_its_reference_from_the_isolated_group_on_a_selected_la assert!(!got.contains(&outside)); } +/// A template sublayer inside a selected sublayer of the isolated layer gives no type for the +/// reference of the font Same commands, so the reference is the first type that can be selected. +#[test] +fn select_same_font_ignores_type_on_a_template_sublayer_inside_the_isolated_layer() { + let mut s = session(); + let typed = + |s: &mut Session, y: f64, font: &str| id_of(&s.execute("text.create", &json!({"x": 0, "y": y, "text": "type", "font": font})).unwrap()); + let l2 = id_of(&s.execute("layer.new", &json!({"top": true})).unwrap()); + let sub = id_of(&s.execute("layer.newSublayer", &json!({"parent": l2.0})).unwrap()); + let template = id_of(&s.execute("layer.newSublayer", &json!({"parent": sub.0, "bottom": true})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": template.0})).unwrap(); + let on_template = typed(&mut s, 20.0, "Arial"); + s.execute("layer.setProps", &json!({"id": template.0, "template": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": template.0, "locked": false})).unwrap(); + assert!(s.doc().unwrap().doc.node(template).is_some_and(|n| n.is_template() && !n.locked)); + s.execute("layer.setCurrent", &json!({"id": sub.0})).unwrap(); + let courier = typed(&mut s, 60.0, "Courier"); + let other_courier = typed(&mut s, 100.0, "Courier"); + let arial = typed(&mut s, 140.0, "Arial"); + let doc = &s.doc().unwrap().doc; + let order: Vec = doc.node(sub).unwrap().children().unwrap().iter().map(|c| c.id).collect(); + assert_eq!(order, vec![template, courier, other_courier, arial]); + assert!(doc.ancestry(on_template).unwrap().contains(&template), "{:?}", doc.ancestry(on_template)); + s.execute("object.isolate", &json!({"id": l2.0})).unwrap(); + sel(&mut s, &[sub]); + assert_eq!(s.doc().unwrap().isolation, Some(l2)); + assert_eq!(s.execute("select.same.fontFamily", &json!({})).unwrap()["count"], 2); + let mut got = selected(&s); + got.sort(); + let mut want = vec![courier, other_courier]; + want.sort(); + assert_eq!(got, want); + assert!(!got.contains(&arial) && !got.contains(&on_template)); +} + /// Select › Same › Symbol Instance takes its reference from the first selected object that can be /// selected: an instance that is hidden, locked, on a template layer or outside the isolated group /// is passed over. From 4c51f853c1cd5f25a5dc8eca84c3d024da4ee26a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:06:23 -0800 Subject: [PATCH 023/482] Render: node renders follow the anti-aliasing option render_node_with and render_node_thumbnail_with drew into a new context without setting its aliasing threshold, so AntiAlias::None still gave smooth edges. Both now set the threshold from the options, as a page render does. --- crates/render/src/renderer.rs | 2 ++ crates/render/src/tests.rs | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index a8a67f270e..1e07075e71 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -321,6 +321,7 @@ impl Renderer { let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let mut ctx = single_threaded_context(w, h); + ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let frame = Frame { mt: false, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, plates: None }; self.begin_frame(); @@ -361,6 +362,7 @@ impl Renderer { let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6); let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2()); let mut ctx = single_threaded_context(w, w); + ctx.set_aliasing_threshold(opts.anti_alias.threshold()); if let Some(bg) = background { ctx.set_paint(peniko::Color::from_rgba8(bg[0], bg[1], bg[2], bg[3])); ctx.fill_rect(&kurbo::Rect::new(0.0, 0.0, w as f64, w as f64)); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index aa16311e0a..a723c4da8d 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -886,6 +886,25 @@ fn node_thumbnail_reports_the_size_it_draws() { } } +/// A node rendered with `AntiAlias::None` has hard edges, as a page render with that option does. +#[test] +fn node_renders_follow_the_anti_alias_option() { + let mut d = Document::new(100.0, 100.0); + let id = d.alloc_id(); + let n = Node::path(id, shapes::ellipse(Rect::new(10.3, 10.3, 60.6, 60.6)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + let node = Arc::new(n.clone()); + let hard = RenderOptions { anti_alias: AntiAlias::None, ..Default::default() }; + let partial = |img: &Rendered| img.pixels.chunks(4).any(|p| p[3] != 0 && p[3] != 255); + let drawn = |img: &Rendered| img.pixels.chunks(4).any(|p| p[3] == 255); + let mut r = Renderer::new(); + assert!(partial(&r.render_node(&d, &node, 100, 100, Affine::IDENTITY).unwrap()), "art anti-aliasing has partial edge pixels"); + assert!(partial(&r.render_node_thumbnail(&d, &n, 37, None).unwrap()), "art anti-aliasing has partial edge pixels"); + let img = r.render_node_with(&d, &node, 100, 100, Affine::IDENTITY, &hard).unwrap(); + assert!(drawn(&img) && !partial(&img), "render_node_with: every alpha is 0 or 255"); + let thumb = r.render_node_thumbnail_with(&d, &n, 37, None, &hard).unwrap(); + assert!(drawn(&thumb) && !partial(&thumb), "render_node_thumbnail_with: every alpha is 0 or 255"); +} + #[test] fn opacity_mask_with_undecodable_image_leaves_out_object() { use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind, OpacityMask}; From 67cc383d771845a4a89e78eb77f361c512795780 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:53:52 -0800 Subject: [PATCH 024/482] Shortcuts: a held Escape that cancels a Tools or ruler move skips the tool Holding Escape to cancel a floating Tools panel move or a ruler-origin drag no longer passes its key repeats to the active tool or to the other Escape actions (pattern edit, isolation, a flyout) once the cancel frame has passed. The repeats are skipped until Escape is released or pressed again. Tests hold Escape through both cancels in each screen mode. --- crates/ui-egui/src/shortcuts.rs | 32 +++++++++++++++-- crates/ui-egui/src/tests/screenmode.rs | 49 ++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 9c62eb1885..b551b758d2 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -219,8 +219,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { presentation_keys(app, ctx, escape_pair); return; } - // Escape that cancels a ruler-origin drag or floating Tools move skips the tool and later Escape actions. - let escape_ended_gesture = crate::canvas::ruler_origin_dragging(ctx) || crate::tools_float::escape_cancelled_move(ctx); + // Escape that cancels a ruler-origin drag or floating Tools move skips the tool and later Escape actions, + // and so do its repeats while it is held. + let escape_ended_gesture = escape_ended_gesture(ctx); let escape_held_by_drag = crate::canvas::dragging(ctx) || escape_ended_gesture; let typing = ctx.egui_wants_keyboard_input(); // Escape closes Edit Toolbar's drawer first (egui drops a drag from it on Escape already). @@ -368,6 +369,33 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { single_key_shortcuts(app, ctx); } +/// The key of the mark that the Escape held down ended a ruler-origin drag or a floating Tools move. +fn escape_ended_gesture_id() -> egui::Id { + egui::Id::unique("escape-ended-gesture") +} + +/// Does this frame's Escape end a ruler-origin drag or a floating Tools move? The repeats of an +/// Escape that ended one do too, up to the frame that releases Escape or presses it again. +fn escape_ended_gesture(ctx: &egui::Context) -> bool { + let (down, pressed, repeated) = ctx.input(|i| { + let escape = + |repeat: bool| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::Escape, pressed: true, repeat: r, .. } if *r == repeat)); + (i.key_down(Key::Escape), escape(false), escape(true)) + }); + if crate::canvas::ruler_origin_dragging(ctx) || crate::tools_float::escape_cancelled_move(ctx) { + if down { + ctx.data_mut(|d| d.insert_temp(escape_ended_gesture_id(), true)); + } + return true; + } + // A release in the same frame as a repeat still holds that repeat back. + let held = (down || repeated) && !pressed && ctx.data(|d| d.get_temp::(escape_ended_gesture_id())).is_some(); + if !(held && down) { + ctx.data_mut(|d| d.remove::(escape_ended_gesture_id())); + } + held +} + fn remember_escape_pair(ctx: &egui::Context, key: Key, escape_pair: Option) { if key == Key::Escape && escape_pair.is_some() && !egui::Popup::is_any_open(ctx) { let now = ctx.input(|i| i.time); diff --git a/crates/ui-egui/src/tests/screenmode.rs b/crates/ui-egui/src/tests/screenmode.rs index 6011fa3349..2e35006300 100644 --- a/crates/ui-egui/src/tests/screenmode.rs +++ b/crates/ui-egui/src/tests/screenmode.rs @@ -416,6 +416,55 @@ fn cancelling_ruler_origin_drag_keeps_the_tools_escape() { } } +/// An Escape event: a press (a repeat when `repeat`) or a release. +fn escape_event(pressed: bool, repeat: bool) -> Vec { + vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat, modifiers: Default::default() }] +} + +#[test] +fn held_escape_that_cancels_tools_move_keeps_the_tool() { + for mode in [0, 1, 2] { + let ctx = egui::Context::default(); + let mut app = in_screen_mode(&ctx, mode); + app.select_tool("intertwine"); + let (original, to) = begin_tools_move(&mut app, &ctx); + frame(&mut app, &ctx, escape_event(true, false)); + assert_eq!(app.ui.toolbar_pos, original, "move canceled in mode {mode}"); + for _ in 0..3 { + frame(&mut app, &ctx, escape_event(true, true)); + } + assert_eq!(app.session.tool_id(), "intertwine", "held Escape keeps the tool in mode {mode}"); + release_drag(&mut app, &ctx, to); + frame(&mut app, &ctx, escape_event(true, true)); + assert_eq!(app.session.tool_id(), "intertwine", "held Escape keeps the tool after the release in mode {mode}"); + assert_eq!(app.ui.screen_mode, mode, "held Escape keeps the screen mode {mode}"); + frame(&mut app, &ctx, [escape_event(true, true), escape_event(false, false)].concat()); + assert_eq!(app.session.tool_id(), "intertwine", "a repeat with the release keeps the tool in mode {mode}"); + frame(&mut app, &ctx, escape()); + assert_eq!(app.session.tool_id(), "selection", "the next Escape reaches the tool in mode {mode}"); + } +} + +#[test] +fn held_escape_that_cancels_ruler_origin_drag_keeps_the_tool() { + for mode in [0, 1, 2] { + let ctx = egui::Context::default(); + let mut app = in_screen_mode(&ctx, mode); + app.select_tool("intertwine"); + let to = begin_ruler_origin_drag(&mut app, &ctx); + frame(&mut app, &ctx, escape_event(true, false)); + release_drag(&mut app, &ctx, to); + assert!(!crate::canvas::ruler_origin_dragging(&ctx)); + for _ in 0..3 { + frame(&mut app, &ctx, escape_event(true, true)); + } + assert_eq!(app.session.tool_id(), "intertwine", "held Escape keeps the tool in mode {mode}"); + frame(&mut app, &ctx, escape_event(false, false)); + frame(&mut app, &ctx, escape()); + assert_eq!(app.session.tool_id(), "selection", "the next Escape reaches the tool in mode {mode}"); + } +} + #[test] fn a_popup_takes_escape_before_full_screen_exits() { let ctx = egui::Context::default(); From 55dc5bb4a5a2776717e2335abe0b74db006fdd76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:08:05 -0800 Subject: [PATCH 025/482] .ai import: a brush object without a name counts as a brush left out A plug-in object that names a brush kind but ends before the brush's name was dropped without a trace. When it was the file's only brush object, the document kept the default brushes and showed no note. It is now counted with the other brushes that can't be read, so the file gets the Brushes panel note and no default brushes. --- crates/eps/src/import/ai/brush.rs | 10 ++++++---- crates/eps/src/import/ai/read/directives.rs | 13 ++++++++++--- crates/eps/src/import/ai/tests.rs | 14 ++++++++++++++ 3 files changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index f7e1f8893d..3904e6aabe 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -126,8 +126,9 @@ pub(super) enum BrushError { } /// The strings of a plug-in object's section (`section`: what follows `%AI8_BeginPluginObject`): -/// its plug-in name, its name and its parameters, joined. `None` with fewer than two strings. -pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, String, String)> { +/// its plug-in name, its name and its parameters, joined. The name is `None` with one string, and +/// the whole is `None` with none. +pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, Option, String)> { let mut lex = Lexer::new(section); let mut strings = vec![]; let mut params = vec![]; @@ -142,8 +143,9 @@ pub(super) fn plugin_strings(section: &[u8]) -> Option<(String, String, String)> } } } - let [kind, name]: [String; 2] = strings.try_into().ok()?; - Some((kind, name, obj::text(¶ms))) + let mut strings = strings.into_iter(); + let kind = strings.next()?; + Some((kind, strings.next(), obj::text(¶ms))) } /// The brush manager's order (`params`: its parameters): the kind and name of each brush. Pairs diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index e2c9df048b..b1c9db39d3 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -518,16 +518,23 @@ impl<'a> Reader<'a> { } /// A plug-in object (`section`: what follows `%AI8_BeginPluginObject`): the brush manager's - /// order or a brush ([`brush`]); other objects are left alone. + /// order or a brush ([`brush`]); other objects are left alone. A brush without a name is counted + /// as not read. fn plugin_object(&mut self, section: &[u8]) { let Some((kind, name, params)) = brush::plugin_strings(section) else { return }; if kind == brush::MANAGER { - self.brush_objects = true; - self.brush_order = brush::parse_brush_manager(¶ms); + if name.is_some() { + self.brush_objects = true; + self.brush_order = brush::parse_brush_manager(¶ms); + } return; } let Some(tool) = brush::tool(&kind) else { return }; self.brush_objects = true; + let Some(name) = name else { + self.brushes_unread += 1; + return; + }; if self.brush_drafts.len() >= brush::MAX_BRUSHES { self.brushes_unread += 1; return; diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index eb46288c42..6e97b279df 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -5224,6 +5224,20 @@ fn a_file_whose_brushes_are_all_left_out_has_none() { assert!(vectorcraft_brush::library(&r.doc).is_empty()); } +/// A brush object that ends after its plug-in name is counted as a brush left out, and the file +/// gets no default brushes. +#[test] +fn a_brush_object_without_a_name_is_counted_as_left_out() { + let nameless = format!("%AI5_Begin_NonPrinting\nNp\n%AI8_BeginPluginObject\n({CALLIGRAPHIC})\n%AI8_EndPluginObject\n%AI5_End_NonPrinting--\n"); + let r = read_ok(&format!("{nameless}{}", layer(""))); + assert!(vectorcraft_brush::library(&r.doc).is_empty(), "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (1)")), "{:?}", r.warnings); + let r = read_ok(&format!("{}{nameless}{}", plugin_object(CALLIGRAPHIC, "Nib", NIB), layer(""))); + let lib = vectorcraft_brush::library(&r.doc); + assert_eq!(lib.iter().map(|b| b.name.as_str()).collect::>(), ["Nib"], "{:?}", r.warnings); + assert!(r.warnings.iter().any(|w| w.ends_with("Brushes panel (1)")), "{:?}", r.warnings); +} + /// A gradient's `Br` (a stop's ramp) isn't a brush: the gradient keeps its stops. #[test] fn a_gradients_br_is_not_a_brush() { From e67277ebe7eb9f191380a43e4ad6204eaf162794 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:19:31 -0800 Subject: [PATCH 026/482] Hide: Unselected Artwork keeps groups that hold a selected layer or a locked guide A layer nested in a group whose art was all locked counted for nothing, so the group was hidden or locked with the layer inside it. The selected layer now counts as selected itself. While Lock Guides was on, a guide path that was locked itself, or sat in a locked object, was not kept, so the group around it was hidden. Guide paths inside locked objects are now kept too. --- crates/engine/src/cmd/menucmds.rs | 22 ++++++++++++-- crates/engine/src/tests/menucmds.rs | 45 +++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 73cf96c9ba..5077408e49 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -347,7 +347,7 @@ fn other_layers(s: &mut Session, lock: bool) -> Result { } /// Returns the objects [`super::select::walk_selectable`] visits that are not among the selected objects `roots` and -/// hold none of them. A selected layer's objects count as selected. The walk goes into a plain group, but not a Shaper +/// hold none of them. A selected layer and its objects count as selected. The walk goes into a plain group, but not a Shaper /// group, that holds a selected object. With `lock`, it also goes into a clip group or compound path that holds one, /// and includes guide paths while `guides_locked`. Without `lock`, guide paths and the objects that hold one are left /// out while `guides_locked`; a clip group, Shaper group, compound path and every other object that holds a selected @@ -360,14 +360,32 @@ fn unselected( guides_locked: bool, lock: bool, ) -> Vec { + /// Pushes the visible guide paths in `n`, `n` included, locked ones too. + fn shown_guides(n: &vectorcraft_doc::Node, out: &mut Vec) { + if !n.visible { + return; + } + if matches!(n.kind, NodeKind::Path { guide: true, .. }) { + out.push(n.id); + } + for c in n.children().into_iter().flatten() { + shown_guides(c, out); + } + } let mut roots: HashSet = roots.iter().copied().collect(); - roots.extend(selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()).flat_map(|l| l.layer_art(true))); + let layers = || selection.iter().filter_map(|id| d.node(*id)).filter(|n| n.is_layer()); + roots.extend(layers().map(|l| l.id)); + roots.extend(layers().flat_map(|l| l.layer_art(true))); let mut kept: Vec = roots.iter().copied().collect(); if guides_locked && !lock { super::select::walk_selectable(d, iso, |n| { if matches!(n.kind, NodeKind::Path { guide: true, .. }) { kept.push(n.id); } + // The walk skips locked objects, so the guide paths in them are looked for here. + for c in n.children().into_iter().flatten().filter(|c| c.locked) { + shown_guides(c, &mut kept); + } true }); } diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index e47cabc5f1..b5cb952553 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -865,6 +865,51 @@ fn hide_unselected_artwork_keeps_groups_with_locked_guides_and_the_selected_laye assert_eq!(selected(&s), [other]); } +/// While Lock Guides is on, Hide › Unselected Artwork keeps a group visible when it holds a guide path that is locked +/// itself, and hides the group's other members one by one. +#[test] +fn hide_unselected_artwork_keeps_groups_with_a_locked_guide_path() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let guide = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + let x = rect(&mut s, 60.0, 0.0, 10.0, 10.0); + sel(&mut s, &[guide, x]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + sel(&mut s, &[guide]); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("layer.setProps", &json!({"id": guide.0, "locked": true})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + sel(&mut s, &[a]); + assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 1})); + assert_eq!([a, g, guide, x].map(|id| node(&s, id).visible), [true, true, true, false]); +} + +/// Hide › Unselected Artwork keeps a group visible when it holds a selected layer whose art is all locked, and hides the +/// group's other members one by one. +#[test] +fn hide_unselected_artwork_keeps_a_group_that_holds_a_selected_layer() { + let mut s = session(); + let b = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let y = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let z = rect(&mut s, 40.0, 0.0, 10.0, 10.0); + sel(&mut s, &[y]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + let sub = s + .edit("nest", |d, _| { + let id = d.alloc_id(); + d.insert(Some(g), usize::MAX, Node::layer(id, "Sub", vectorcraft_doc::LayerColor::Preset(1))) + .map_err(|e| EngineError::Other(e.to_string()))?; + let art = d.remove(z).map_err(|e| EngineError::Other(e.to_string()))?; + d.insert(Some(id), 0, (*art).clone()).map_err(|e| EngineError::Other(e.to_string()))?; + Ok(id) + }) + .unwrap(); + s.execute("layer.setProps", &json!({"id": z.0, "locked": true})).unwrap(); + sel(&mut s, &[sub]); + assert_eq!(s.execute("object.hide.unselected", &json!({})).unwrap(), json!({"count": 2})); + assert_eq!([b, g, y, sub, z].map(|id| node(&s, id).visible), [false, true, false, true, true]); +} + /// Lock Unselected Artwork locks `b`, `n` in the group that holds selected `m`, `p` on another layer, and the clip /// group's unselected members `c1` and clipping path `c3` in one undo step labeled "Lock". The clip group container, /// `c2`, the selected objects, group `g`, hidden object `h` and art `q` on a locked layer stay unlocked. `k` was locked From c24c06ef7fb2e30509e0fe71c48a1d798415af49 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:03:05 -0800 Subject: [PATCH 027/482] Direct Selection: a marquee over a long path tests its segments without building a path for each The marquee's segment test built a two-anchor path for every segment and ran hit::intersects_rect on it. It now skips a segment whose anchors and handles all lie past one side of the marquee, and tests the rest directly with the same bounds and edge checks, so it selects the same segments. A marquee over 10,000 anchors, press to release (anchor_bench, median of 7): one open path of 200,000 anchors 84.9 ms -> 24.1 ms, 2,000 closed paths of 50 anchors 27.5 ms -> 13.5 ms, one closed path of 50,000 anchors 14.6 ms -> 8.5 ms. --- crates/tools/src/direct.rs | 32 +++++++- crates/tools/src/direct/tests.rs | 127 +++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 157 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index c321975182..ffb3a6560b 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -51,7 +51,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde_json::{Value, json}; use vectorcraft_doc::hit::{HitKind, compound_part_at, hit_test, selected_hidden_at}; use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection}; -use vectorcraft_geom::{Anchor, PathData, Point, Rect, Vec2}; +use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; use crate::bbox::move_delta; use crate::corners::{self, CornerDrag, over_widget}; @@ -590,7 +590,17 @@ fn anchors_json(v: &[AnchorRef]) -> Value { /// The segments of `path` that marquee `r` crosses with neither of their anchors inside it, as /// (subpath, segment) pairs: the reference app selects a segment that a marquee is dragged "over /// part of" (). +/// Each segment is judged as `hit::intersects_rect` judges a path of that segment alone. A segment +/// whose anchors and handles all lie past one side of `r` is skipped without the exact test. fn crossed_segments(path: &PathData, r: Rect) -> Vec { + let (x0, x1, y0, y1) = (r.min_x(), r.max_x(), r.min_y(), r.max_y()); + let edges = [ + vectorcraft_geom::Line::new((r.x0, r.y0), (r.x1, r.y0)), + vectorcraft_geom::Line::new((r.x1, r.y0), (r.x1, r.y1)), + vectorcraft_geom::Line::new((r.x1, r.y1), (r.x0, r.y1)), + vectorcraft_geom::Line::new((r.x0, r.y1), (r.x0, r.y0)), + ]; + let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0; let mut out = vec![]; for (si, sp) in path.subpaths.iter().enumerate() { let n = sp.anchors.len(); @@ -600,8 +610,24 @@ fn crossed_segments(path: &PathData, r: Rect) -> Vec { if r.contains(a.p) || r.contains(b.p) { continue; } - let piece = PathData::single(vectorcraft_geom::SubPath::new(vec![*a, *b], false)); - if vectorcraft_geom::hit::intersects_rect(&piece, r) { + // A segment with no handles is drawn as a line, as `SubPath::to_bezpath_into` draws it. + let line = !a.has_out() && !b.has_in(); + let pts = if line { [a.p, b.p, b.p, b.p] } else { [a.p, a.h_out, b.h_in, b.p] }; + // A segment lies within the box of its anchors and handles. The comparisons are false + // for a NaN coordinate, so such a segment goes on to the exact test. + if pts.iter().all(|p| p.x < x0) || pts.iter().all(|p| p.x > x1) || pts.iter().all(|p| p.y < y0) || pts.iter().all(|p| p.y > y1) { + continue; + } + let piece = if line { + PathSeg::Line(vectorcraft_geom::Line::new(a.p, b.p)) + } else { + PathSeg::Cubic(vectorcraft_geom::CubicBez::new(a.p, a.h_out, b.h_in, b.p)) + }; + let bounds = vectorcraft_geom::path::segment_bounds(piece); + if bounds.intersect(r).area() <= 0.0 && !degenerate(bounds) && !degenerate(r) { + continue; + } + if edges.iter().any(|e| !piece.intersect_line(*e).is_empty()) { out.push((si, seg)); } } diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index b7892cc2d3..ef60102200 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -587,6 +587,133 @@ fn a_marquee_over_part_of_a_segment_selects_it() { assert!(!drag(&mut g, Mods::default()).iter().any(|a| matches!(a, Action::Exec(c, _) if c == "select.segments"))); } +/// The segments `r` crosses, found by testing a two-anchor path built for each segment with +/// `hit::intersects_rect`. `crossed_segments` gives the same result without building the paths. +fn crossed_by_pieces(path: &PathData, r: Rect) -> Vec { + let mut out = vec![]; + for (si, sp) in path.subpaths.iter().enumerate() { + let n = sp.anchors.len(); + let count = if sp.closed { n } else { n.saturating_sub(1) }; + for seg in 0..count { + let (Some(a), Some(b)) = (sp.anchors.get(seg), sp.anchors.get((seg + 1) % n)) else { continue }; + if r.contains(a.p) || r.contains(b.p) { + continue; + } + let piece = PathData::single(vectorcraft_geom::SubPath::new(vec![*a, *b], false)); + if vectorcraft_geom::hit::intersects_rect(&piece, r) { + out.push((si, seg)); + } + } + } + out +} + +/// A cubic segment from `p0` to `p3` with handles `p1` and `p2`, as an open path. +fn curve(p0: (f64, f64), p1: (f64, f64), p2: (f64, f64), p3: (f64, f64)) -> PathData { + let a = Anchor::with_handles(p0.into(), p0.into(), p1.into()); + let b = Anchor::with_handles(p3.into(), p2.into(), p3.into()); + PathData::single(vectorcraft_geom::SubPath::new(vec![a, b], false)) +} + +fn polyline(points: &[(f64, f64)], closed: bool) -> PathData { + let pts: Vec = points.iter().map(|p| (*p).into()).collect(); + PathData::single(vectorcraft_geom::SubPath::polyline(&pts, closed)) +} + +/// A Direct Selection marquee crosses a segment, with neither of its anchors inside, only where +/// the segment itself meets the marquee: a straight segment, a curve that reaches the marquee only +/// between its anchors, and not a curve whose handles reach it while the curve stays outside. +#[test] +fn a_marquee_crosses_a_segment_only_where_the_segment_meets_it() { + let line = polyline(&[(0.0, 0.0), (100.0, 0.0)], false); + assert_eq!(crossed_segments(&line, Rect::new(40.0, -10.0, 60.0, 10.0)), vec![(0, 0)], "across a straight segment"); + assert!(crossed_segments(&line, Rect::new(40.0, 5.0, 60.0, 10.0)).is_empty(), "beside it"); + // The curve rises to y = 67.5 between its anchors on y = 0; its handles reach y = 90. + let arch = curve((0.0, 0.0), (0.0, 90.0), (100.0, 90.0), (100.0, 0.0)); + assert_eq!(crossed_segments(&arch, Rect::new(40.0, 60.0, 60.0, 70.0)), vec![(0, 0)], "the curve crosses between its anchors"); + assert!(crossed_segments(&arch, Rect::new(40.0, 75.0, 60.0, 85.0)).is_empty(), "only the handles reach the marquee"); + // Within the curve's box, above the curve where it leaves (0, 0): at x = 10 it is near y = 42. + assert!(crossed_segments(&arch, Rect::new(0.5, 55.0, 10.0, 66.0)).is_empty(), "the curve's box reaches the marquee"); + assert!(crossed_segments(&arch, Rect::new(40.0, 95.0, 60.0, 105.0)).is_empty(), "the handles stop short of it"); +} + +/// A segment that touches the marquee's edge is crossed as `hit::intersects_rect` judges it: a +/// straight segment along the edge is crossed, and a curve whose top only touches it is not. +#[test] +fn a_marquee_touching_a_segment_crosses_it_as_the_hit_test_does() { + let along = polyline(&[(0.0, 10.0), (100.0, 10.0)], false); + let r = Rect::new(40.0, 10.0, 60.0, 20.0); + assert_eq!(crossed_segments(&along, r), crossed_by_pieces(&along, r)); + assert_eq!(crossed_segments(&along, r), vec![(0, 0)], "a straight segment along the edge"); + // The curve's top is at y = 67.5. + let arch = curve((0.0, 0.0), (0.0, 90.0), (100.0, 90.0), (100.0, 0.0)); + let r = Rect::new(40.0, 67.5, 60.0, 80.0); + assert_eq!(crossed_segments(&arch, r), crossed_by_pieces(&arch, r)); + assert!(crossed_segments(&arch, r).is_empty(), "a curve whose top touches the edge"); + let r = Rect::new(40.0, 67.0, 60.0, 80.0); + assert_eq!(crossed_segments(&arch, r), vec![(0, 0)], "the same curve a little into the marquee"); +} + +/// Empty and one-anchor paths have no segments to cross; an open path's last anchor has no +/// segment after it, a closed path's closing segment is crossed, and each subpath of a compound +/// path is tested with its own index. +#[test] +fn a_marquee_crosses_segments_of_open_closed_and_compound_paths() { + let r = Rect::new(-10.0, 40.0, 10.0, 60.0); + assert!(crossed_segments(&PathData::default(), r).is_empty(), "an empty path"); + for closed in [false, true] { + assert!(crossed_segments(&polyline(&[(0.0, 50.0)], closed), r).is_empty(), "one anchor (closed: {closed})"); + } + let square = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + assert!(crossed_segments(&polyline(&square, false), r).is_empty(), "an open path has no segment from its last anchor"); + assert_eq!(crossed_segments(&polyline(&square, true), r), vec![(0, 3)], "the closing segment"); + let mut compound = polyline(&square, true); + compound.subpaths.extend(polyline(&[(200.0, 0.0), (200.0, 100.0), (300.0, 100.0)], false).subpaths); + let r = Rect::new(190.0, 40.0, 210.0, 60.0); + assert_eq!(crossed_segments(&compound, r), vec![(1, 0)], "the second subpath"); + let wide = Rect::new(-10.0, 40.0, 210.0, 60.0); + assert_eq!(crossed_segments(&compound, wide), vec![(0, 1), (0, 3), (1, 0)], "both subpaths"); +} + +/// Over a grid of marquees, zero-width ones and ones touching anchors and edges included, +/// `crossed_segments` picks the same segments as testing a path built for each segment. +#[test] +fn crossed_segments_match_testing_a_path_for_each_segment() { + let mut compound = polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], true); + compound.subpaths.extend(curve((20.0, 20.0), (20.0, 90.0), (80.0, 90.0), (80.0, 20.0)).subpaths); + let mut loops = curve((0.0, 50.0), (150.0, -40.0), (-50.0, -40.0), (100.0, 50.0)); + loops.subpaths[0].closed = true; + let paths = [ + polyline(&[(0.0, 0.0), (100.0, 0.0)], false), + polyline(&[(0.0, 10.0), (100.0, 10.0)], false), + polyline(&[(0.0, 0.0), (100.0, 100.0)], false), + polyline(&[(50.0, -20.0), (50.0, 120.0), (90.0, 30.0)], false), + curve((0.0, 0.0), (0.0, 90.0), (100.0, 90.0), (100.0, 0.0)), + curve((0.0, 100.0), (30.0, -50.0), (70.0, 150.0), (100.0, 0.0)), + loops, + compound, + polyline(&[(30.0, 30.0)], true), + PathData::default(), + ]; + let sizes = [0.0, 5.0, 10.0, 35.0, 120.0]; + let mut crossings = 0; + for path in &paths { + for x in (-30..=120).step_by(5) { + for y in (-30..=120).step_by(5) { + for w in sizes { + for h in sizes { + let r = Rect::new(f64::from(x), f64::from(y), f64::from(x) + w, f64::from(y) + h); + let want = crossed_by_pieces(path, r); + assert_eq!(crossed_segments(path, r), want, "{r:?} over {path:?}"); + crossings += want.len(); + } + } + } + } + } + assert!(crossings > 1000, "the grid crosses segments ({crossings})"); +} + #[test] fn marquee_selects_ruler_guides() { let (mut d, id) = doc_with_rect(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 479bd26d45..c762d355b9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -709,6 +709,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In Construction mode, a Selection-tool drag that drops an original shape wholly outside the bounds of the group's original shapes takes it out of the group in the move's undo step (Remove from Shaper Group, `shaper.releaseSource`): the shape becomes a path above the group and stays selected, and a group left with no shapes is removed. Engine tests drag a shape out of a two-shape group and back across the bounds, take the last shape out, undo, and save the result. - **Selection:** Selection, Direct/Group Selection, Magic Wand, Lasso. A Shift-drag marquee toggles what it reaches: objects with the Selection tool, anchors with Direct and Group Selection (#483); the Lasso adds with Shift and subtracts with Alt. Dragging a path segment with Direct Selection bends it when it's curved (its anchors stay) and moves its two anchors when it's straight, one undo step; the fill, Shift or Alt still pick the whole path (Alt-drag copies it). A Direct Selection marquee over part of a segment, with neither of its anchors inside, selects that segment as a click on it does (Shift toggles it), as [Selecting objects](http://web.archive.org/web/20211230015528/https://helpx.adobe.com/illustrator/using/selecting-objects.html) describes (#4654). + To find those segments, the marquee skips each segment whose anchors and handles all lie past one side of it and tests only the rest exactly, without building a path for each segment. It selects the same segments as before, and a marquee over a path of many anchors finishes sooner. With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection. 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. From 5ebb6796fe2524eefa76e98291363c7b1574dcdb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:31:26 -0800 Subject: [PATCH 028/482] Tests: skip the Arabic Optical kerning test without craft-fonts optical_pair_after_rtl_separate_mark_uses_base_outline sets Noto Sans Arabic, which is not in assets/fonts. Without CRAFT_FONTS_DIR the font database returns a fallback face, so the test checked that face instead. The test now skips when Noto Sans Arabic is missing, as the Shippori Mincho tests in the same file do. --- crates/text/src/tests/typo.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 092ed4c09f..689e956b30 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -172,6 +172,10 @@ fn optical_pair_after_separate_combining_mark_uses_base_outline() { #[test] fn optical_pair_after_rtl_separate_mark_uses_base_outline() { + if db().face("Noto Sans Arabic", "Regular").is_none_or(|f| f.family != "Noto Sans Arabic") { + eprintln!("skipped: built without craft-fonts (set CRAFT_FONTS_DIR to a craft-fonts checkout to run it)"); + return; + } let st = CharStyle { font_family: "Noto Sans Arabic".into(), size: 100.0, optical_kerning: true, ..CharStyle::default() }; let shaped = |text: &str, manual: bool| { let mut style = st.clone(); From 1600696aeac9b2e67aff6b5cba2b3f9d7926dd30 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:39:08 -0800 Subject: [PATCH 029/482] Canvas: a drag's release reads Backtick as it was at the button-up A press or release of Backtick, or a window focus loss, that came after the mouse button went up in the same frame changed whether the drag committed a pattern-only transform. The release now takes Backtick's state at the button-up from the frame's ordered input events. --- crates/ui-egui/src/canvas/drag.rs | 40 ++++++++++++++++++++ crates/ui-egui/src/canvas/input.rs | 50 +++++++----------------- crates/ui-egui/src/canvas/tests.rs | 61 ++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 37 deletions(-) diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 3f3c156edd..1980661b88 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -89,6 +89,46 @@ pub(super) fn tool_drag_mods_changed(ui: &Ui, m: Mods, backquote: bool) -> bool dragged && last.is_some_and(|l| l != held) } +/// Whether Backtick is held at the end of this frame, and whether it was at the end of the frame +/// before (`None` before the first). The canvas records it once a frame. +pub(super) fn backquote_seen(ui: &Ui) -> (bool, Option) { + let id = egui::Id::unique("canvas-backquote-seen"); + let now = ui.input(|i| i.key_down(egui::Key::Backtick)); + let before = ui.data_mut(|d| { + let before = d.get_temp::(id); + d.insert_temp(id, now); + before + }); + (now, before) +} + +/// Whether Backtick was held when `button` went up in this frame, with `before` its state at the end +/// of the frame before ([`backquote_seen`]). Its state as the frame began is the opposite of its +/// first press or release in the frame; when the window lost the focus first (which lets go of every +/// key without a release), it is `before`; with neither, it is its state now. The frame's presses, +/// releases and focus losses before the button-up then apply in the order they came. Without a +/// button-up in this frame, its state now. +pub(super) fn backquote_at_release(ui: &Ui, button: egui::PointerButton, before: Option) -> bool { + ui.input(|i| { + let now = i.key_down(egui::Key::Backtick); + // A press or release of Backtick (`Some(pressed)`), or a focus loss (`None`). + let step = |e: &egui::Event| match e { + egui::Event::Key { key: egui::Key::Backtick, pressed, repeat: false, .. } => Some(Some(*pressed)), + egui::Event::WindowFocused(false) => Some(None), + _ => None, + }; + let Some(up) = i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: false, .. } if *b == button)) else { + return now; + }; + let start = match i.events.iter().find_map(step) { + Some(Some(down)) => !down, + Some(None) => before.unwrap_or(now), + None => now, + }; + i.events[..up].iter().filter_map(step).fold(start, |_, s| s.unwrap_or(false)) + }) +} + /// The pen pressure (0..1) of the press in progress: the force of this frame's pen or touch /// input, else the pressure in the host's feed while a pen is the pointer that moved last /// ([`crate::Services::stylus`]: [`StylusFeed::press`] for a new press, [`StylusFeed::held`] diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 3775edeb86..e0bd9f0292 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -1,7 +1,8 @@ use super::artboards::{artboard_name_at, begin_artboard_name_edit, name_press_id, select_named_artboard}; use super::drag::{ - FrameMove, HoverContext, apply_requests, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, drop_press, mods, move_pose, on_canvas, - pen_pose, pen_pressure, tool_drag_doc_id, tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, tool_holds, tool_press_doc_id, + FrameMove, HoverContext, apply_requests, backquote_at_release, backquote_seen, dispatch, drag_art_out, drag_id, drag_layer_id, drag_pos_id, + drop_press, mods, move_pose, on_canvas, pen_pose, pen_pressure, tool_drag_doc_id, tool_drag_mods_changed, tool_drag_moved, tool_frame_moves, + tool_holds, tool_press_doc_id, }; use super::view::{ HOLD_DELAY, HOLD_ZOOM, SCRUB_SLOP, SCRUB_ZOOM, WheelTurn, animated_zoom, pan_pixels, rotate_about, scroll_view, touch_gestures, trackpad_turn, @@ -19,7 +20,8 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo // double-taps) where it was seen last (#491). let at = hover.or_else(|| pointer.interact_pos().filter(|p| rect.contains(*p))); let view = app.view_info(); - let f = Pointing { resp, rect, pointer: &pointer, m, space, xf, v, view }; + let (_, backquote_before) = backquote_seen(ui); + let f = Pointing { resp, rect, pointer: &pointer, m, space, xf, v, view, backquote_before }; touch_gestures(app, ui, rect, view); // Pressed and held still, a pen or a finger opens the context menu (egui's long touch): the // tool's press is dropped, as a right-click presses nothing. @@ -186,6 +188,8 @@ struct Pointing<'a> { xf: Xf, v: View, view: vectorcraft_engine::ViewInfo, + /// Whether Backtick was held at the end of the frame before ([`backquote_seen`]). + backquote_before: Option, } /// Zoom around the pointer, and scroll ([`wheel`]); a trackpad rotation turns the view. Returns the pointer, the @@ -433,6 +437,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po dd.remove::(tool_drag_doc_id()); dd.remove::(tool_press_doc_id()); }); + // Backtick as it was at the button-up: a key pressed or released later in the frame does not count. + let backquote = backquote_at_release(ui, egui::PointerButton::Primary, f.backquote_before); match d { Drag::ZoomBox { start } => { let start = zoom_marquee_start(ui, start, before, p, space); @@ -472,7 +478,6 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let (moves, last_pose) = tool_frame_moves(ui, app, true); let pen = move_pose(app, &xf, last_pose); if let Some(last) = last_drag { - let backquote = ui.input(|i| i.key_down(egui::Key::Backtick)); dispatch_frame_moves(app, ui, f, backquote, moves); if last != xf.to_doc(p) { let ev = PointerEvent { @@ -490,7 +495,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po kind: PointerKind::Up, pos: xf.to_doc(p), mods: mods(m, space), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), + backquote, pressure: pen_pressure(ui, app, false), pen, }; @@ -501,30 +506,8 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po egui::DragAndDrop::clear_payload(ui.ctx()); let (pressure, pen) = (pen_pressure(ui, app, false), pen_pose(app, &xf)); let pos = xf.to_doc(p); - dispatch( - app, - &PointerEvent { - kind: PointerKind::Drag, - pos, - mods: mods(m, space), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), - pressure, - pen, - }, - view, - ); - dispatch( - app, - &PointerEvent { - kind: PointerKind::Up, - pos, - mods: mods(m, space), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), - pressure, - pen, - }, - view, - ); + dispatch(app, &PointerEvent { kind: PointerKind::Drag, pos, mods: mods(m, space), backquote, pressure, pen }, view); + dispatch(app, &PointerEvent { kind: PointerKind::Up, pos, mods: mods(m, space), backquote, pressure, pen }, view); } Drag::Art => { // Released over a panel: the move goes back. (The app ends it before the panels @@ -533,14 +516,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po let _ = app.session.cancel_interaction(); dispatch( app, - &PointerEvent { - kind: PointerKind::Up, - pos: Point::ZERO, - mods: Mods::default(), - backquote: ui.input(|i| i.key_down(egui::Key::Backtick)), - pressure: 1.0, - pen: None, - }, + &PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote, pressure: 1.0, pen: None }, view, ); } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 0c9462818e..201faa3273 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3051,6 +3051,67 @@ fn egui_backtick_drag_uses_key_state_at_release() { ); } +/// The release takes Backtick as it was at the button-up, when the key goes up or down later in the +/// same frame. +#[test] +fn backtick_changed_after_the_button_up_in_its_frame_does_not_change_the_release() { + use egui::Event; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let tile = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [tile], "name": "Dots", "width": 20, "height": 20})).unwrap(); + app.run("object.pattern.done", json!({})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setFill", json!({"ids": [id], "swatch": "Dots"})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.select_tool("selection"); + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let from = xf.to_screen(Point::new(125.0, 125.0)); + let to = xf.to_screen(Point::new(145.0, 125.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let key = |pressed| Event::Key { key: egui::Key::Backtick, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + let node = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().clone(); + let pattern_x = |node: &vectorcraft_doc::Node| { + let vectorcraft_color::Paint::Pattern { xf, .. } = node.appearance.fill_paint() else { panic!("pattern fill expected") }; + xf.as_coeffs()[4] + }; + let before = node(&app); + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![key(true), Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false), key(false)]); + let pattern_only = node(&app); + assert!(app.session.active().unwrap().interaction.is_none(), "committed"); + assert_eq!(pattern_only.geometric_bounds(), before.geometric_bounds(), "Backtick held at the button-up keeps geometry still"); + assert!((pattern_x(&pattern_only) - pattern_x(&before) - 20.0).abs() < 0.001, "Backtick held at the button-up moves the pattern"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app), before); + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false), key(true)]); + let ordinary = node(&app); + frame(&mut app, &ctx, vec![key(false)]); + assert!( + (ordinary.geometric_bounds().unwrap().x0 - before.geometric_bounds().unwrap().x0 - 20.0).abs() < 0.001, + "Backtick pressed after the button-up commits an ordinary move" + ); + assert!((pattern_x(&ordinary) - pattern_x(&before)).abs() < 0.001, "the ordinary move keeps the pattern matrix"); + // A focus loss after the button-up lets go of Backtick with no release event. + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(node(&app), before); + frame(&mut app, &ctx, vec![Event::PointerMoved(from), button(from, true)]); + frame(&mut app, &ctx, vec![key(true), Event::PointerMoved(to)]); + frame(&mut app, &ctx, vec![button(to, false), Event::WindowFocused(false)]); + let unfocused = node(&app); + assert_eq!(unfocused.geometric_bounds(), before.geometric_bounds(), "a focus loss after the button-up keeps geometry still"); + assert!((pattern_x(&unfocused) - pattern_x(&before) - 20.0).abs() < 0.001, "a focus loss after the button-up moves the pattern"); +} + #[test] fn mirror_axis_drag_uses_canvas_coordinates_in_a_zoomed_rotated_view() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); From c220c500e92dbb0726e51311c1eadfdfe19db23a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:48:17 -0800 Subject: [PATCH 030/482] Type: Done during a Cmd press does not save empty point type Done (pattern editing), Stop Editing Opacity Mask and Exit Isolation Mode end the Type tool's edit first, so point type a click placed and left empty is discarded. While a Cmd/Ctrl press had lent a selection tool, the Type tool was not the active tool, its edit was not ended, and the empty point type was saved into the pattern tile or the mask. The lent tool is now given back first. A drag the lent tool started is kept as its own step, with its last position applied when Real-time Drawing and Editing is off. --- crates/engine/src/tests/opacitymask.rs | 27 +++++++++- crates/engine/src/tests/pattern.rs | 68 +++++++++++++++++++++++++- crates/engine/src/tooling.rs | 17 ++++++- 3 files changed, 108 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/opacitymask.rs b/crates/engine/src/tests/opacitymask.rs index c2db4f3688..206ef7e66d 100644 --- a/crates/engine/src/tests/opacitymask.rs +++ b/crates/engine/src/tests/opacitymask.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; -use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use crate::cmd::maskedit::MASK_EDIT_LAYER; use crate::tests::{history, select_with_a_step_to_redo}; @@ -234,6 +234,31 @@ fn empty_point_type_is_not_saved_into_the_mask() { } } +/// The same while a Cmd/Ctrl press has lent the Selection tool to the Type tool: the command before +/// the release gives the Type tool back first, so the empty point type is still discarded. +#[test] +fn empty_point_type_is_not_saved_into_the_mask_during_a_cmd_press() { + for cmd in ["transparency.stopEditingOpacityMask", "object.exitIsolation"] { + let mut s = session(); + s.prefs.placeholder_text = false; + let obj = editing_mask(&mut s); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 250.0, 250.0), v).unwrap(); + } + let press = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 280.0).with_mods(press), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "{cmd}: the press lends the Selection tool"); + s.execute(cmd, &json!({})).unwrap(); + assert_eq!(s.tool_id(), "type", "{cmd}: the Type tool is back"); + assert!(!s.tool_wants_text(), "{cmd}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 280.0).with_mods(press), v).unwrap(); + let art = &mask(&s, obj).unwrap().art; + assert!(art.children().is_none() && !matches!(art.kind, vectorcraft_doc::NodeKind::Text(_)), "{cmd}: the mask keeps only the square"); + } +} + /// Releasing the masks of a group and of an object inside it puts each mask's art directly above /// its object, as releasing one mask at a time does. #[test] diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index a23e621b93..544dcce96a 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -5,7 +5,7 @@ use vectorcraft_color::Paint; use vectorcraft_doc::pattern::{PATTERN_EDIT_LAYER, RepeatKind, TileType}; use vectorcraft_doc::{Node, NodeKind}; use vectorcraft_geom::{Point, Rect}; -use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; use crate::tests_menucmds::place_undecodable_png; use crate::*; @@ -134,6 +134,72 @@ fn empty_point_type_is_not_saved_into_the_pattern() { } } +/// The same while a Cmd/Ctrl press has lent the Selection tool to the Type tool: Done or Exit +/// Isolation Mode before the release gives the Type tool back first, so the empty point type is +/// still discarded, and the release that follows leaves the tile as it is. +#[test] +fn empty_point_type_is_not_saved_into_the_pattern_during_a_cmd_press() { + for cmd in ["object.pattern.done", "object.exitIsolation"] { + let mut s = session(); + s.prefs.placeholder_text = false; + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 200.0, 200.0), v).unwrap(); + } + let press = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 300.0).with_mods(press), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "{cmd}: the press lends the Selection tool"); + s.execute(cmd, &json!({})).unwrap(); + assert_eq!(s.tool_id(), "type", "{cmd}: the Type tool is back"); + assert!(!s.tool_wants_text(), "{cmd}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0).with_mods(press), v).unwrap(); + let art = &doc(&s).pattern("P").unwrap().art; + assert_eq!(art.len(), 1, "{cmd}: the tile keeps only the square"); + assert!(!matches!(art[0].kind, NodeKind::Text(_)), "{cmd}"); + } +} + +/// Done during a drag of the lent Selection tool keeps the drag as its own step before the tile is +/// saved, so no drag is left open for the release to end. With Real-time Drawing and Editing off, +/// the drag's last position is applied first, as the release would apply it. +#[test] +fn done_during_a_lent_selection_drag_keeps_the_drag_as_its_own_step() { + for real_time in [true, false] { + let mut s = session(); + s.prefs.placeholder_text = false; + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": real_time})).unwrap(); + let r = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + sel(&mut s, &[r]); + s.execute("object.pattern.make", &json!({"name": "P"})).unwrap(); + let st = s.doc().unwrap(); + let b = st.doc.bounds_of(&st.selection.objects, false).expect("the tile art is selected"); + let c = b.center(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 200.0, 200.0), v).unwrap(); + } + let press = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, c.x, c.y).with_mods(press), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, c.x + 20.0, c.y).with_mods(press), v).unwrap(); + assert!(s.in_interaction(), "{real_time}: the lent Selection tool drags the square"); + s.execute("object.pattern.done", &json!({})).unwrap(); + assert!(!s.in_interaction(), "{real_time}: the drag is kept before the tile is saved"); + assert_eq!(s.tool_id(), "type", "{real_time}"); + s.pointer(&PointerEvent::new(PointerKind::Up, c.x + 20.0, c.y).with_mods(press), v).unwrap(); + let labels = s.doc().unwrap().history.undo.iter().map(|e| e.label.as_str()).collect::>(); + assert_eq!(labels.last(), Some(&"Done Editing Pattern"), "{real_time}: {labels:?}"); + assert!(labels.contains(&"Move"), "{real_time}: {labels:?}"); + let art = &doc(&s).pattern("P").unwrap().art; + assert_eq!(art.len(), 1, "{real_time}: the tile keeps only the square"); + assert!(!matches!(art[0].kind, NodeKind::Text(_)), "{real_time}"); + } +} + #[test] fn cancel_new_pattern_removes_it() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index ee83e72d68..18e8da3d59 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -861,9 +861,22 @@ impl Session { /// End the Type tool's text editing before a command saves the art of an editing layer (pattern /// editing's Done, Stop Editing Opacity Mask): point type its click placed that is still empty is - /// discarded first, so it is not saved into the pattern tile or the mask. + /// discarded first, so it is not saved into the pattern tile or the mask. A selection tool that a + /// Cmd press lent is given back first, so the Type tool behind it ends its edit too; a drag of the + /// lent tool is kept as its own step, as its release would keep it. pub(crate) fn end_text_edit(&mut self) { - if self.in_tool_actions || !self.tool.wants_text() { + if self.in_tool_actions { + return; + } + if self.lender.is_some() { + if let Err(e) = self.apply_actions(vec![Action::Commit]) { + log::warn!("keeping the lent tool's drag before ending the text edit: {e}"); + } + if let Err(e) = self.give_back_tool(self.last_view) { + log::warn!("giving back the lent tool before ending the text edit: {e}"); + } + } + if !self.tool.wants_text() { return; } let acts = self.with_tool_cx(self.last_view, |t, cx| t.deactivate(cx)); From 4a9ccc6fe35614c3427592ff54c8bedc793d6dbb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:04:31 -0800 Subject: [PATCH 031/482] Preferences: a Render Threads change before the first UI pass restarts the canvas renderer The first UI pass applies the saved preferences again (#4837) by removing the record of what was last applied. A Render Threads change made by a control request between an earlier tick and that pass was then applied with no previous value to compare, so the canvas renderer kept its old thread count. The pass now forces the theme refresh and keeps the record, so the thread change still restarts the renderer. --- crates/ui-egui/src/prefs_dialog.rs | 16 +++++++++++----- crates/ui-egui/src/prefs_dialog/tests.rs | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/prefs_dialog.rs b/crates/ui-egui/src/prefs_dialog.rs index b91c149f45..20502f0f65 100644 --- a/crates/ui-egui/src/prefs_dialog.rs +++ b/crates/ui-egui/src/prefs_dialog.rs @@ -109,6 +109,12 @@ fn canvas_color(key: &str) -> Option { /// Per frame: push UI-side preferences into egui / the renderer when they change. pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) { + apply(app, ctx, false); +} + +/// [`apply_runtime`]; with `force`, the preferences are pushed into `ctx` even when nothing changed +/// since the last push. +fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, force: bool) { let p = &app.session.prefs; if let Some(b) = Brightness::parse(&p.ui_brightness) && b != app.ui.brightness @@ -127,7 +133,7 @@ pub fn apply_runtime(app: &mut VectorcraftApp, ctx: &egui::Context) { }; let id = applied_id(); let prev: Option = ctx.data(|d| d.get_temp::>(id)).flatten(); - if prev != Some(want) { + if force || prev != Some(want) { theme::apply_with(ctx, want.brightness, want.accent, want.scheme); // General › Show Tool Tips: off, no button or field shows its tool tip (they never come // due), whichever widget asks for one. @@ -165,11 +171,11 @@ fn applied_id() -> egui::Id { egui::Id::unique("dc-applied-prefs") } -/// [`apply_runtime`] with nothing recorded as applied, so the theme (brightness, accent, color -/// scheme and canvas color) and the other UI-side preferences are pushed into `ctx` again. +/// [`apply_runtime`] even when nothing changed, so the theme (brightness, accent, color scheme and +/// canvas color) and the other UI-side preferences are pushed into `ctx` again. The record of what +/// was last applied stays, so a Render Threads change since then still restarts the renderer. pub(crate) fn reapply(app: &mut VectorcraftApp, ctx: &egui::Context) { - ctx.data_mut(|d| d.remove::>(applied_id())); - apply_runtime(app, ctx); + apply(app, ctx, true); } pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 2e47115056..cbc429b5f9 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -79,6 +79,23 @@ fn saved_scheme_accent_and_canvas_color_show_from_the_first_frame() { } } +/// A Render Threads change made after the preferences were applied, and before the first UI pass +/// applies them again, still restarts the canvas renderer. +#[test] +fn reapply_restarts_the_renderer_after_a_render_threads_change() { + let mut app = app(); + let ctx = egui::Context::default(); + apply_runtime(&mut app, &ctx); + app.canvas.worker_started = true; + // The automatic count as an explicit value: the process-wide count other tests read stays the same. + let threads = vectorcraft_render::default_threads(); + app.run("prefs.set", json!({"key": "renderThreads", "value": threads})).unwrap(); + reapply(&mut app, &ctx); + let restarted = !app.canvas.worker_started; + app.run("prefs.set", json!({"key": "renderThreads", "value": -1})).unwrap(); + assert!(restarted, "the canvas renderer kept its old thread count"); +} + fn app() -> VectorcraftApp { VectorcraftApp::new(Session::new(), Services::default()) } From f11df30d234f9e20f4d16e51c34ad9384a97413a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:14:57 -0800 Subject: [PATCH 032/482] Type: Kerning menu lists Auto and Optical for mixed kerning modes A selection that mixed kerning modes left the Kerning dropdown without its Auto and Optical entries, so one mode could not be set on all of it. The menu now lists both entries with neither checked. --- crates/ui-egui/src/panels/character.rs | 11 +++++++++-- crates/ui-egui/src/panels/character/tests.rs | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index da5c6d410e..98c3be6bcd 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -316,6 +316,14 @@ fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> { Some((value, true)) } +/// The check marks of the Kerning menu's Auto and Optical entries for the selection's kerning +/// `mode` (Optical on, manual value). A selection that mixes modes checks neither, and the menu +/// still lists both. +fn kerning_methods(mode: Option<(bool, Option)>) -> (Option, Option) { + let (automatic, optical) = mode.map_or((false, false), |(optical, manual)| (!optical && manual.is_none(), optical)); + (Some(automatic), Some(optical)) +} + /// The faces Type › Bold and Type › Italic switch to. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Face { @@ -756,8 +764,7 @@ pub(crate) fn metrics_grid(app: &mut VectorcraftApp, ui: &mut Ui, id: &str, s: & let caret = text_editing(app).is_some_and(|(_, a, b)| a == b); let at_caret = if caret { caret_kerning(app, ui) } else { None }; let kerning = at_caret.map(|(v, _)| v).or_else(|| mode.map(|(_, manual)| manual.unwrap_or(0.0))); - let automatic = mode.map(|(optical, manual)| !optical && manual.is_none()); - let optical = mode.map(|(optical, _)| optical); + let (automatic, optical) = kerning_methods(mode); match widgets::spin_kerning( ui, "ch-kern", diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 7716c3bb4e..7cdfddad3a 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -258,6 +258,26 @@ fn character_kerning_setter_and_automatic_pair_value() { assert_eq!(shared(&app, |s| (s.optical_kerning, s.kerning)), None, "a mixed range shows a blank Kerning field"); } +/// The Kerning menu lists Auto and Optical for a selection that mixes kerning modes, with +/// neither checked, so one mode can be set on all of it. +#[test] +fn kerning_menu_lists_auto_and_optical_for_mixed_modes() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AV", "size": 12})).unwrap()["id"].clone(); + let b = app.run("text.create", json!({"x": 20, "y": 90, "text": "AV", "size": 12})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [b.clone()]})).unwrap(); + app.run("text.setFormat", json!({"kerning": "optical"})).unwrap(); + app.run("select.set", json!({"ids": [a.clone()]})).unwrap(); + assert_eq!(kerning_methods(shared(&app, |s| (s.optical_kerning, s.kerning))), (Some(true), Some(false)), "Auto"); + app.run("select.set", json!({"ids": [b.clone()]})).unwrap(); + assert_eq!(kerning_methods(shared(&app, |s| (s.optical_kerning, s.kerning))), (Some(false), Some(true)), "Optical"); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mode = shared(&app, |s| (s.optical_kerning, s.kerning)); + assert_eq!(mode, None, "the selection mixes Auto and Optical"); + assert_eq!(kerning_methods(mode), (Some(false), Some(false)), "both entries are listed, neither checked"); +} + /// Highlight Kerning and Highlight Tracking show the Character panel and give its field the /// keyboard focus with the value selected: what is typed replaces it, and Enter applies it. /// Highlight Font Name opens the font family menu with its search field focused. Without From dbfe3fdc3803cedf79a0424d3fb2d43bccb49237 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:21:05 -0800 Subject: [PATCH 033/482] Global Edit: the options dropdowns close when Global Edit starts The Global Edit Options dropdowns in the Control bar and in the Properties panel's Quick Actions turn their button off while Global Edit is on, but a popup that was already open stayed open and still changed the options. Both dropdowns now close their popup while Global Edit is on, and it stays closed after Global Edit stops until the button is clicked again. --- crates/ui-egui/src/chrome/control_bar.rs | 7 ++-- crates/ui-egui/src/chrome/tests.rs | 9 +++-- crates/ui-egui/src/panels/properties.rs | 12 ++++++- crates/ui-egui/src/panels/properties/tests.rs | 34 +++++++++++++++++++ 4 files changed, 56 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index a40d88dfe5..1df1f08ab0 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -142,9 +142,9 @@ const GLOBAL_EDIT_OPTIONS_WIDTH: f32 = 24.0; /// page places the options in the Control panel as well as in Properties /// (). /// It opens the Properties panel's Global Edit Options, which set the same session options, and is -/// off while Global Edit is on, as that panel's dropdown is. It sits after Recolor Artwork, ahead of -/// the X/Y/W/H fields that the bar leaves out when it runs short of room, and is left out only when -/// no room is left for it. +/// off and closed while Global Edit is on, as that panel's dropdown is. It sits after Recolor +/// Artwork, ahead of the X/Y/W/H fields that the bar leaves out when it runs short of room, and is +/// left out only when no room is left for it. fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { if !crate::menus::enabled(app, "select.globalEdit") || ui.available_width() < GLOBAL_EDIT_OPTIONS_WIDTH { return; @@ -152,6 +152,7 @@ fn global_edit_options(app: &mut VectorcraftApp, ui: &mut Ui) { let on = app.session.active().is_some_and(|d| d.global_edit.is_some()); let options = widgets::icon_button_enabled(ui, "chevron-down", tl!("Global Edit Options"), false, !on, GLOBAL_EDIT_OPTIONS_WIDTH); egui::Popup::menu(&options) + .open_memory(crate::panels::properties::global_edit_options_open(&options, on)) .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) .show(|ui| crate::panels::properties::global_edit_options(app, ui)); } diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 00c56ff67a..5c49b153df 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1807,7 +1807,7 @@ fn the_control_bar_shows_the_distribute_buttons_for_two_or_more_objects() { /// The Control bar shows the Global Edit Options dropdown while Start Global Edit can run. Its /// options are the session's, which the Properties panel's dropdown also sets: Match Size from /// the Control bar narrows the Results and the objects Start Global Edit takes. The dropdown is off -/// while Global Edit is on, and absent when the selection cannot start it. +/// and closed while Global Edit is on, and absent when the selection cannot start it. #[test] fn the_control_bar_shows_the_global_edit_options() { crate::i18n::set_current(crate::i18n::Lang::EN); @@ -1860,9 +1860,14 @@ fn the_control_bar_shows_the_global_edit_options() { let nodes = frame(&mut app, vec![]); let button = find(&nodes, "Global Edit Options").unwrap_or_else(|| panic!("Global Edit on: the dropdown still shows")); assert!(button.is_disabled(), "the options are off while Global Edit is on"); + let results = |nodes: &Nodes| nodes.iter().any(|(_, n)| n.label().or(n.value()).is_some_and(|t| t.starts_with("Result"))); + assert!(!results(&nodes), "Global Edit starting closes the open options"); + assert!(!results(&frame(&mut app, vec![]))); + app.run("select.globalEdit", json!({})).unwrap(); + frame(&mut app, vec![]); + assert!(!results(&frame(&mut app, vec![])), "the options stay closed once Global Edit stops"); // At any width the button either fits inside the bar or is left out, and a wider bar never // leaves it out once a narrower one showed it. - app.run("select.globalEdit", json!({})).unwrap(); let mut seen = false; for width in (600..=2400).step_by(10) { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width as f32, 300.0)); diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index f236c6a738..b775dc05ae 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -240,10 +240,20 @@ fn global_edit_row(app: &mut VectorcraftApp, ui: &mut Ui) { crate::menus::invoke(app, "select.globalEdit", json!({})); } let options = widgets::icon_button_enabled(ui, "chevron-down", tl!("Global Edit Options"), false, !on, 20.0); - egui::Popup::menu(&options).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| global_edit_options(app, ui)); + egui::Popup::menu(&options) + .open_memory(global_edit_options_open(&options, on)) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| global_edit_options(app, ui)); }); } +/// The open state for a Global Edit Options dropdown's popup: a click on the button toggles the +/// popup, and the popup is closed while Global Edit is on, including when Global Edit starts with +/// the popup open. +pub(crate) fn global_edit_options_open(options: &egui::Response, on: bool) -> Option { + if on { Some(egui::SetOpenCommand::Bool(false)) } else { options.clicked().then_some(egui::SetOpenCommand::Toggle) } +} + /// The Global Edit Options: what else similar objects must share (Match), where they may lie (On /// Artboards) and how many objects that takes now. The Control bar's Global Edit Options dropdown /// shows them too. diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index f13e983842..1a38e4f707 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -135,6 +135,40 @@ fn start_global_edit_quick_action_and_escape() { assert!(!tall(&mut app, vec![]).iter().any(|(t, _)| t == "Start Global Edit"), "type has no Global Edit"); } +/// The Quick Actions' Global Edit Options close when Global Edit starts while they are open, and +/// stay closed once it stops. +#[test] +fn global_edit_starting_closes_the_quick_action_options() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let a = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap()["id"].clone(); + app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 40, "height": 40})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(300.0, 700.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| global_edit_row(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + type Nodes = Vec<(egui::accesskit::NodeId, egui::accesskit::Node)>; + let results = |nodes: &Nodes| nodes.iter().any(|(_, n)| n.label().or(n.value()).is_some_and(|t| t.starts_with("Result"))); + let nodes = frame(&mut app, vec![]); + let b = nodes.iter().find(|(_, n)| n.label() == Some("Global Edit Options")).and_then(|(_, n)| n.bounds()).unwrap_or_else(|| panic!("{nodes:?}")); + let at = Pos2::new(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, vec![Event::PointerMoved(at), press(true)]); + frame(&mut app, vec![press(false)]); + assert!(results(&frame(&mut app, vec![])), "the options open"); + app.run("select.globalEdit", json!({})).unwrap(); + assert!(!results(&frame(&mut app, vec![])), "Global Edit starting closes the open options"); + app.run("select.globalEdit", json!({})).unwrap(); + frame(&mut app, vec![]); + assert!(!results(&frame(&mut app, vec![])), "the options stay closed once Global Edit stops"); +} + /// The options' Results count is found once per document revision, options and selected /// object, not every frame; another selected object or other options find it again. #[test] From 8762242dfe1d6049bb85589ac584af7b9476474c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:44:52 -0800 Subject: [PATCH 034/482] Select: describe which object Same Symbol Instance compares with The params text of select.same.symbolInstance, docs/mcp.md and docs/target-app-parity.md now say that the object compared with can be of any kind (a group member selected on its own, or an object that is not a symbol instance, which leaves the selection empty), and that new art on a locked artboard is not passed over while it stays selected. A test covers the three cases. --- crates/engine/src/cmd/docmenu.rs | 2 +- crates/engine/src/tests/menucmds.rs | 38 +++++++++++++++++++++++++++++ docs/mcp.md | 8 +++--- docs/target-app-parity.md | 2 +- 4 files changed, 45 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index f2972a1f13..fc146fdec8 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Symbol Instance", ["Select", "Same"], None, - "{} select the instances of the symbol of the first selected object that can be selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group or layer are passed over → {count}", + "{} select the instances of the symbol of the first selected object that can be selected, including a group member selected on its own; when that object is not a symbol instance, such as a group, nothing is selected; objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard while nothing is isolated (new art while it stays selected excepted), or outside the isolated group or layer are passed over → {count}", has_selection, |s, _| same(s, "select.same.symbolInstance", |a, b| match (&a.kind, &b.kind) { (NodeKind::SymbolInstance { symbol: x, .. }, NodeKind::SymbolInstance { symbol: y, .. }) => x == y, diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index b5cb952553..b201a60c3c 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2176,6 +2176,44 @@ fn select_same_symbol_instance_skips_objects_that_cannot_be_selected() { assert_eq!(selected(&s), vec![a1, on_template]); } +/// Select › Same › Symbol Instance takes as its reference the first selected object that can be +/// selected, whatever its kind: an instance inside a selected group, and an instance just placed +/// on a locked artboard while it stays selected. A first object that is not an instance matches +/// nothing, so the selection is cleared. +#[test] +fn select_same_symbol_instance_reference_can_be_any_selectable_object() { + const C: &str = "select.same.symbolInstance"; + let mut s = session(); + let place = |s: &mut Session, name: &str, x: f64| id_of(&s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()); + rect(&mut s, 0.0, 0.0, 20.0, 20.0); + let a1 = id_of(&s.execute("symbol.new", &json!({"name": "A"})).unwrap()); + rect(&mut s, 50.0, 0.0, 20.0, 20.0); + let b1 = id_of(&s.execute("symbol.new", &json!({"name": "B"})).unwrap()); + let b2 = place(&mut s, "B", 200.0); + let plain = rect(&mut s, 0.0, 100.0, 20.0, 20.0); + // A path selected before an instance is the reference, and no instance matches it. + sel(&mut s, &[plain, b1]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 0); + assert!(selected(&s).is_empty()); + // An instance inside a group, selected on its own, is the reference. + sel(&mut s, &[b1, plain]); + s.execute("object.group", &json!({})).unwrap(); + sel(&mut s, &[b1]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2); + let mut got = selected(&s); + got.sort(); + let mut want = vec![b1, b2]; + want.sort(); + assert_eq!(got, want); + // An instance placed on a locked artboard is the reference while it stays selected. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 400})).unwrap(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + let a2 = place(&mut s, "A", 1100.0); + assert_eq!(selected(&s), vec![a2]); + assert_eq!(s.execute(C, &json!({})).unwrap()["count"], 2); + assert_eq!(selected(&s), vec![a1, a2]); +} + /// Select › Same › Text Fill & Stroke Color selects the type with characters whose fill and stroke /// both match the first character of the selected type: the same fill with another stroke, or the /// same stroke with another fill, is left out, and in type with several runs one run has to match diff --git a/docs/mcp.md b/docs/mcp.md index 89ec257683..ba467c12a1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1475,9 +1475,11 @@ selection holds no other type, they return the error "select a text object". `select.same.fillColor`, `strokeColor`, `fillAndStroke`, `strokeWeight`, `opacity`, `blendingMode`, `appearance`, `shapeType`, `graphicStyle`, `appearanceAttribute` and `symbolInstance` compare the other objects with the first -selected object, in selection order, that these commands could select. A selected object that is hidden or locked, -inside a hidden or locked group or layer, on a template layer, on a locked artboard while nothing is isolated, or -outside the isolated group is passed over. When the selection holds no other object, they return the error "nothing +selected object, in selection order, that can be selected. That object can be of any kind: a group, a member of a +group selected on its own, or, for `symbolInstance`, an object that is not a symbol instance, which matches nothing and +leaves the selection empty. A selected object that is hidden or locked, inside a hidden or locked group or layer, on a +template layer, on a locked artboard while nothing is isolated, or outside the isolated group is passed over. New art, +such as a symbol instance just placed, is not passed over for being on a locked artboard while it stays selected. When the selection holds no other object, they return the error "nothing selected". ## Shaper Groups diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c762d355b9..68e17e7487 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -932,7 +932,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Select › Same › Link Block Series selects every frame of the threads of the selected type; type in no thread selects itself (`select.same.linkBlockSeries`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); selecting several threads at once and type in no thread selecting itself are VectorCraft's own behavior. Select › Same › Text Fill & Stroke Color selects the type whose characters match both the fill and the stroke of the selected type (`select.same.textFillAndStrokeColor`). The menu entry is listed in [Select objects by characteristics](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects-by-characteristics.html); requiring one run of characters to match both is VectorCraft's own behavior. The Select › Same font and text color commands take the type to match from the selected type that can be selected: type that is hidden or locked, on a template layer, or outside the isolated group is passed over. This is VectorCraft's own behavior. - Select › Same › Fill Color, Stroke Color, Fill & Stroke, Stroke Weight, Opacity, Blending Mode, Appearance, Shape, Graphic Style, Appearance Attribute and Symbol Instance compare the other objects with the first selected object that can be selected: an object that is hidden or locked, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group is passed over. This is VectorCraft's own behavior. + Select › Same › Fill Color, Stroke Color, Fill & Stroke, Stroke Weight, Opacity, Blending Mode, Appearance, Shape, Graphic Style, Appearance Attribute and Symbol Instance compare the other objects with the first selected object that can be selected, of any kind: an object that is hidden or locked, on a template layer, on a locked artboard while nothing is isolated (except new art while it stays selected), or outside the isolated group is passed over. This is VectorCraft's own behavior. Object › Flatten Transparency takes a frame of threaded text out of the thread in the same way when Convert All Text to Outlines outlines it or when the frame becomes flat regions or an image, and the other frames keep the text they hold. New Symbol and Redefine Symbol on a frame of threaded text take it out of the thread with the text it shows, which the symbol's art holds, and the other frames keep the text they hold. When the last frame goes into the symbol, the text it has no room for goes after the text of the last frame that stays. When every frame of a thread goes into the symbol, the copy of the last frame keeps all its text. With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. From f65cd179f8f61907291e1edb88cb7207095732c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:56:48 -0800 Subject: [PATCH 035/482] Docs: re-wrap the select.same paragraph in docs/mcp.md --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index ba467c12a1..83e8a3c248 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1479,8 +1479,8 @@ selected object, in selection order, that can be selected. That object can be of group selected on its own, or, for `symbolInstance`, an object that is not a symbol instance, which matches nothing and leaves the selection empty. A selected object that is hidden or locked, inside a hidden or locked group or layer, on a template layer, on a locked artboard while nothing is isolated, or outside the isolated group is passed over. New art, -such as a symbol instance just placed, is not passed over for being on a locked artboard while it stays selected. When the selection holds no other object, they return the error "nothing -selected". +such as a symbol instance just placed, is not passed over for being on a locked artboard while it stays selected. When +the selection holds no other object, they return the error "nothing selected". ## Shaper Groups From 12508e6c609c54f2f2e913638c05ef8c433c0449 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:28:47 -0800 Subject: [PATCH 036/482] Dialogs: a color with an alpha part is refused instead of losing its alpha `Color::from_hex` reads `#rrggbbaa` and keeps only its first six digits, so a `color` set to `#ff000080` through `ui.dialog.set` was applied as `#ff0000` without an error by Tile Edge Color, Live Paint Selection Tool Options, Live Paint Bucket Options and Gap Options. - A new `checked` next to `resolve` in `dialogs/tile_edge_color.rs` gives the existing "is not a colour" error for an 8-digit hex color, and otherwise reads the color as `resolve` does. `resolve` is unchanged, so the swatches the dialogs draw with it show such a color by its RGB as before. - Each of the four dialogs' OK checks the color with `checked` first, and leaves the dialog open with nothing changed. Tile Edge Color and Gap Options already refused `#rgba`, which `from_hex` does not read. Live Paint Selection and Live Paint Bucket used to ignore a color they could not read, such as `#f008`, and apply their other fields; their OK now refuses it. - With Preview on, Gap Options sends no color for a `#rrggbbaa` value, so the groups keep their own color, and the previewed gaps draw in black. Docs: the params text, docs/mcp.md, docs/control-protocol.md and docs/target-app-parity.md. --- .../ui-egui/src/dialogs/live_paint_bucket.rs | 27 +++++++- crates/ui-egui/src/dialogs/live_paint_gaps.rs | 64 ++++++++++++++++++- .../src/dialogs/live_paint_selection.rs | 27 +++++++- crates/ui-egui/src/dialogs/tile_edge_color.rs | 51 ++++++++++++++- crates/ui-egui/src/menus/ui_commands.rs | 6 +- docs/control-protocol.md | 1 + docs/mcp.md | 10 ++- docs/target-app-parity.md | 1 + 8 files changed, 174 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index e9267b0f39..c040cdcc31 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -13,7 +13,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, resolve}; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -78,8 +78,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options, or an error for a `color` that is not a color. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key("color") { + checked(&d.str("color"))?; + } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) } @@ -148,4 +151,24 @@ mod tests { app.select_tool(TOOL); assert!(!hover(&mut app, 151.0).iter().any(|o| matches!(o, Overlay::Path { .. }))); } + + /// A highlight color with an alpha part is refused and leaves the tool's options as they were; + /// `#rrggbb` still sets them. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!("#ff000080")); + d.fields.insert("width".into(), json!(8)); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let o = app.session.tool_options_of(TOOL); + assert_eq!((o["color"].as_str(), o["width"].as_f64()), (Some("#ff2a2a"), Some(4.0)), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of(TOOL)["color"], json!("#ff0000")); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_gaps.rs b/crates/ui-egui/src/dialogs/live_paint_gaps.rs index 98c7abfba5..e01a08e9a4 100644 --- a/crates/ui-egui/src/dialogs/live_paint_gaps.rs +++ b/crates/ui-egui/src/dialogs/live_paint_gaps.rs @@ -15,7 +15,7 @@ use vectorcraft_doc::{GapSize, LAYER_COLORS}; use vectorcraft_geom::{BezPath, Point}; use vectorcraft_tools::Overlay; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, has_alpha, resolve}; use super::{DialogSpec, form}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -116,7 +116,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); ui.add_space(6.0); form::check(ui, d, "closeGaps", tl!("Close Gaps With Paths")); - let p = params(d); + let mut p = params(d); + // OK refuses a color with an alpha part, so the preview leaves each group's own color. + if has_alpha(&d.str("color")) { + p["color"] = Value::Null; + } if let Some(r) = form::preview_result(app, ui, d, "Gap Options", CMD, p) { d.fields.insert(GAPS.into(), r["gaps"].clone()); } @@ -127,6 +131,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + checked(&d.str("color"))?; form::commit_preview(app, CMD, params(d)) } @@ -134,7 +139,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// off or another dialog is open). pub(crate) fn overlays(app: &VectorcraftApp) -> Vec { let Some(d) = app.ui.dialog.as_ref().filter(|d| d.kind == KIND && d.bool("preview")) else { return vec![] }; - let [r, g, b, _] = resolve(&d.str("color")).unwrap_or(Color::BLACK).to_rgba8(1.0); + let [r, g, b, _] = checked(&d.str("color")).unwrap_or(Color::BLACK).to_rgba8(1.0); let gaps = d.fields.get(GAPS).and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default(); gaps.iter() .filter_map(|gap| { @@ -257,4 +262,57 @@ mod tests { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("size"), d.f64("custom", 0.0)), ("large".to_string(), GapSize::LARGE)); } + + /// A Gap Preview Color with an alpha part is refused and leaves the group's options as they + /// were; `#rrggbb` still sets them. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + app.run("select.all", json!({})).unwrap(); + let g = app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!("#ff000080")); + d.fields.insert("detect".into(), json!(true)); + let depth = app.session.doc().unwrap().history.undo.len(); + let err = crate::dialogs::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!((options(&app, g), app.session.doc().unwrap().history.undo.len()), (GapOptions::default(), depth), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(options(&app, g).color, [0xff, 0, 0]); + } + + /// With Preview on, a Gap Preview Color with an alpha part is not previewed: the group keeps + /// its own color, the gaps draw in black, OK refuses the color and Cancel rolls the preview back. + #[test] + fn a_color_with_an_alpha_part_is_not_previewed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + // An open path round a square, its end 2 pt short of its start. + let anchors = [(0, 0), (100, 0), (100, 100), (0, 100), (0, 2)].map(|(x, y)| json!({"x": x, "y": y})); + let p = app.run("path.create", json!({ "anchors": anchors })).unwrap(); + app.run("select.set", json!({"ids": [p["id"]]})).unwrap(); + let g = app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap(); + let own = options(&app, g).color; + app.run("ui.livePaintGapOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("preview".into(), json!(true)); + d.fields.insert("detect".into(), json!(true)); + d.fields.insert("color".into(), json!("#ff000080")); + let depth = app.session.doc().unwrap().history.undo.len(); + frame(&mut app); + assert_eq!((options(&app, g).detect, options(&app, g).color), (true, own), "the group keeps its own color"); + let shown = overlays(&app); + assert!(matches!(&shown[..], [Overlay::Path { color: [0, 0, 0], .. }]), "{shown:?}"); + let err = crate::dialogs::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + crate::dialogs::cancel(&mut app); + let undo = app.session.doc().unwrap().history.undo.len(); + assert_eq!((options(&app, g), undo), (GapOptions::default(), depth), "Cancel rolls the preview back"); + } } diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index 8ba8cf49b4..a1a91ad2b7 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -12,7 +12,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, resolve}; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -74,8 +74,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options, or an error for a `color` that is not a color. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key("color") { + checked(&d.str("color"))?; + } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) } @@ -139,4 +142,24 @@ mod tests { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.bool("selectFills"), d.str("color")), (false, "#4fff4f".to_string())); } + + /// A highlight color with an alpha part is refused and leaves the tool's options as they were; + /// `#rrggbb` still sets them. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!("#ff000080")); + d.fields.insert("width".into(), json!(8)); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let o = app.session.tool_options_of(TOOL); + assert_eq!((o["color"].as_str(), o["width"].as_f64()), (Some("#ff2a2a"), Some(4.0)), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of(TOOL)["color"], json!("#ff0000")); + } } diff --git a/crates/ui-egui/src/dialogs/tile_edge_color.rs b/crates/ui-egui/src/dialogs/tile_edge_color.rs index 3c78543466..62f3c5a4e1 100644 --- a/crates/ui-egui/src/dialogs/tile_edge_color.rs +++ b/crates/ui-egui/src/dialogs/tile_edge_color.rs @@ -32,6 +32,23 @@ pub(super) fn resolve(color: &str) -> Option { } } +/// Whether `color` is an 8-digit hex color, `#rrggbbaa` (with or without `#`). +pub(super) fn has_alpha(color: &str) -> bool { + let color = color.trim(); + let digits = color.strip_prefix('#').unwrap_or(color); + digits.len() == 8 && digits.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// `color` as [`resolve`] reads it, or an error naming the forms it takes. A hex color with an +/// alpha part (`#rrggbbaa` or `#rgba`) is an error. +pub(super) fn checked(color: &str) -> Result { + let refused = || format!("`{color}` is not a colour (#rrggbb or a preset name)"); + if has_alpha(color) { + return Err(refused()); + } + resolve(color).ok_or_else(refused) +} + fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let color = resolve(&d.str("color")).unwrap_or(Color::BLACK); let [r, g, b, _] = color.to_rgba8(1.0); @@ -58,7 +75,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let color = d.str("color"); - let hex = resolve(&color).ok_or_else(|| format!("`{color}` is not a colour (#rrggbb or a preset name)"))?.to_hex(); + let hex = checked(&color)?.to_hex(); run_and_close(app, "prefs.set", json!({ "key": "patternTileEdgeColor", "value": hex })) } @@ -90,4 +107,36 @@ mod tests { app.run("ui.tileEdgeColor", json!({})).unwrap(); assert!(set(&mut app, "nope").is_err()); } + + /// A hex color with an alpha part is refused and leaves the preference as it was; `#rrggbb` + /// still sets it. + #[test] + fn a_color_with_an_alpha_part_is_refused() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.tileEdgeColor", json!({})).unwrap(); + let before = app.session.prefs.pattern_tile_edge_color.clone(); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff000080")); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert_eq!(app.session.prefs.pattern_tile_edge_color, before); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.prefs.pattern_tile_edge_color, "#ff0000"); + } + + /// The swatches the dialogs draw with `resolve` show an 8-digit color by its RGB, while + /// `checked` refuses it; preset names and `#rrggbb` pass both. + #[test] + fn only_checked_refuses_a_color_with_an_alpha_part() { + let red = Color::rgb8(0xff, 0, 0).to_rgba8(1.0); + assert_eq!(resolve("#ff000080").map(|c| c.to_rgba8(1.0)), Some(red)); + assert_eq!(resolve("ff000080").map(|c| c.to_rgba8(1.0)), Some(red)); + assert!(checked("#ff000080").is_err() && checked(" ff000080 ").is_err()); + assert!(checked("#f008").is_err()); + assert_eq!(checked("#ff0000").map(|c| c.to_rgba8(1.0)), Ok(red)); + for (name, [r, g, b]) in LAYER_COLORS.iter() { + assert_eq!(checked(name).map(|c| c.to_rgba8(1.0)), Ok([*r, *g, *b, 255]), "{name}"); + } + } } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 1356a2cef2..3af5f1b9fc 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}), 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}), 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}), 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 (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}), 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", @@ -883,7 +883,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.tileEdgeColor", "Tile Edge Color…", "", - "{} open Tile Edge Color (dialog `tileEdgeColor`, field `color`: #rrggbb or a preset name such as \"Light Blue\"); OK sets the preference patternTileEdgeColor (prefs.set), the colour of the tile edge and swatch bounds in pattern editing mode", + "{} open Tile Edge Color (dialog `tileEdgeColor`, field `color`: #rrggbb or a preset name such as \"Light Blue\"); OK sets the preference patternTileEdgeColor (prefs.set), the colour of the tile edge and swatch bounds in pattern editing mode; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing", ), ( "ui.flattenTransparencyDialog", @@ -1505,7 +1505,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.livePaintGapOptions", "Gap Options…", "", - "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step", + "{} open Gap Options (Object › Live Paint › Gap Options…; dialog `livePaintGapOptions`: detect, size small|medium|large|custom, custom (pt), color (#rrggbb or a layer color's name), closeGaps, preview) on the selected Live Paint groups, filled in from the first; with preview on, the options apply live and the gaps found draw on the canvas in the preview color: OK runs livePaint.gapOptions as one undo step; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing, and with preview on a #rrggbbaa color is not previewed: the groups keep their own color and the gaps draw in black", ), ( "ui.perspectivePlane", diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a6486d6f93..2aa1e3496a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -320,6 +320,7 @@ The User Defined libraries are `window.userBrushLibrary1`…`10` in Window → B Tile Edge Color: Object → Pattern → Tile Edge Color… (`ui.tileEdgeColor`) opens the `tileEdgeColor` dialog (field `color`: `#rrggbb` or a preset name such as "Light Blue"); `ui.dialog.confirm` sets the preference `patternTileEdgeColor` (`prefs.set`), the colour pattern editing mode draws the tile edge and the swatch bounds in. +A `color` with an alpha part (`#rrggbbaa` or `#rgba`) is an error, and the preference does not change. Window title bar: on Windows and Linux the window has no OS decorations and the app bar is the title bar. Its caption buttons (Minimize, Maximize/Restore, Close) sit at the bar's right end, 46 pt each; they are window chrome, diff --git a/docs/mcp.md b/docs/mcp.md index 83e8a3c248..6c181f0dc1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1868,13 +1868,18 @@ already walks Image Trace. Short agent entry points: and `livePaint.info` list the gaps up to `size` wide that no path closes, as `[x0, y0, x1, y1]`. `livePaint.merge` keeps the bottom group's options when its Gap Detection is on, and otherwise turns Gap Detection on with `small` when another merged group has it on. When Gap Detection is off in every merged group, it stays off. + The Gap Options dialog (`ui.livePaintGapOptions`) takes `color` as `#rrggbb` or a layer color's name; its OK gives + an error for a `color` with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. With Preview on, a + `#rrggbbaa` color is not previewed: the groups keep their own color, and the previewed gaps draw in black. `view.livePaintGaps` (View › Show Live Paint Gaps, or Hide Live Paint Gaps while it is on) turns the drawing of those gaps on or off. While it is on and edges show, the canvas draws the gaps of each selected Live Paint group in that group's Gap Preview Color. The reply is the new state (`true` when on). The Live Paint Selection tool's options (`tool.setOption {tool: "livePaintSelection", values}`; double-clicking the tool opens them, dialog `livePaintSelectionOptions`) are `selectFills` and `selectStrokes` (both on), `color` (the highlight color, `#rrggbb` or a layer color's name; `#ff2a2a`) and `width` (the highlight's width, 1 to 20 screen - pixels; 4). With `selectStrokes` off, Alt-click selects the face under the pointer as a click does; with + pixels; 4). The dialog's OK gives an error for a `color` with an alpha part (`#rrggbbaa` or `#rgba`) and changes + nothing. + With `selectStrokes` off, Alt-click selects the face under the pointer as a click does; with `selectFills` off, a click selects the edge nearest the pointer as Alt-click does; with both off, a click selects no face or edge. A drag of 3 screen pixels or more draws a marquee, and the release runs `select.set {ids}` with the faces and edges it touches (a face or edge partly inside counts, and so does a face that holds the whole @@ -1887,7 +1892,8 @@ already walks Image Trace. Short agent entry points: The Live Paint Bucket's options (`tool.setOption {tool: "livePaintBucket", values}`; double-clicking the tool opens them, dialog `livePaintBucketOptions`) are `paintFills` (on), `paintStrokes` (off), `highlight` (on), `color` (the highlight color, `#rrggbb` or a layer color's name; `#ff2a2a`) and `width` (the face highlight's width, 1 to 20 screen - pixels; 4; an edge's highlight is half as wide). With `paintFills` alone on, a click runs `livePaint.fill` and Shift-click runs `livePaint.strokeEdge`. + pixels; 4; an edge's highlight is half as wide). The dialog's OK gives an error for a `color` with an alpha part + (`#rrggbbaa` or `#rgba`) and changes nothing. With `paintFills` alone on, a click runs `livePaint.fill` and Shift-click runs `livePaint.strokeEdge`. With `paintStrokes` alone on, a click runs `livePaint.strokeEdge` on the edge within 4 screen pixels of the pointer, or nothing when none is in reach, and Shift-click runs `livePaint.fill`. With both on, a click runs `livePaint.strokeEdge` when an edge is within 4 screen pixels of the pointer and `livePaint.fill` otherwise, and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 68e17e7487..200bc86d43 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1007,6 +1007,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Live Paint Gap Options (Object › Live Paint › Gap Options…, `livePaint.gapOptions`): with Gap Detection on, paint stops at the gaps that run from a loose end of a path to the nearest path, up to Small (3 pt), Medium (6 pt), Large (12 pt) or a custom size; Close Gaps With Paths adds an unpainted path across each gap; Preview applies the options live and draws the gaps in the Gap Preview Color. The options are saved, copied and undone with the group, and Merge keeps the bottom group's options when its Gap Detection is on, or else turns Gap Detection on with Small when another merged group has it on. When Gap Detection is off in every merged group, it stays off. View › Show Live Paint Gaps (`view.livePaintGaps`) draws the gaps of the selected Live Paint groups up to their Paint Stops At size, each in its group's Gap Preview Color, until Hide Live Paint Gaps or Hide Edges hides them ([Live Paint gaps](https://web.archive.org/web/20260105111201/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/find-and-close-gaps-in-live-paint-groups.html)). Double-clicking the Live Paint Selection tool opens its Tool Options ([Live Paint Selection tool options](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html)): with Select Fills off, a click selects an edge instead of a face; with Select Strokes off, Alt-click selects a face instead of an edge; Color and Width set the color and width of the highlight on the face or edge under the pointer (red and 4 px by default). The options last across tool switches and are saved with the preferences (`tool.setOption {tool: "livePaintSelection"}`). + As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. A drag with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. From d79f5ccb754cf482ea0a1236b6503cb4dafff7e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:14:35 -0800 Subject: [PATCH 037/482] Layers: a layer or gap color with an alpha part is refused instead of losing its alpha layer.setProps, layer.new, layer.newSublayer and livePaint.gapOptions read an 8-digit hex color such as #ff000080 as #ff0000 and set it without its alpha. They now refuse it with the error a bad color already gets, and change nothing. #rgba was already refused. #rrggbb, #rgb, a preset index and a preset name are read as before. --- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/layer.rs | 13 ++++++++++--- crates/engine/src/tests/build.rs | 19 +++++++++++++++++++ crates/engine/src/tests/layers.rs | 26 ++++++++++++++++++++++++++ docs/mcp.md | 7 +++++-- docs/target-app-parity.md | 1 + 6 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index abc828b311..829c3af5df 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Gap Options", [], None, - "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", + "{id?, ids?: [id…] (instead of id; default: the selected Live Paint groups), detect?: bool (Gap Detection: paint stops at gaps up to size wide), size?: \"small\" (3 pt) | \"medium\" (6 pt) | \"large\" (12 pt) | pt (custom, over 0 up to 72) (Paint Stops At), color?: #rrggbb or a layer color's name such as \"Red\" (Gap Preview Color; a hex color with an alpha part, #rrggbbaa or #rgba, is an error), closeGaps?: bool (add an unpainted path across each gap up to size wide to the group's paths)} set the Gap Options of Live Paint groups (what is not given stays as it was; a group starts with detect false, small and Red) and make their faces again, keeping their paint → {ids, faces, gaps: [[x0,y0,x1,y1]…] (the gaps up to size wide that no path closes, from a loose end of a path to where it closes to; detect closes them for paint), closed (paths added)}", has_selection_or_ids, lp_gap_options ), diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3c7d00cb53..fd7d633e4f 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -83,7 +83,7 @@ pub fn specs() -> Vec { "Layer Options…", ["Window", "Layers"], None, - "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", + "{ids?|id? (default: the highlighted rows, else the current layer), name? (with prefs.identifyObjectsBy xmlId: a valid XML ID, stored as the object name), visible?, locked?, template?, printable?, preview?, dimImages?: 0..100|false, color?: index 0..26|\"#rrggbb\"|preset name (a hex color with an alpha part, #rrggbbaa or #rgba, is an error)} Layer Options; rows that are not layers take name, visible and locked. Template on also locks the layer and dims its images to 50% (unless given); off unlocks it and stops dimming. One undo step", has_doc, set_props ), @@ -297,7 +297,8 @@ pub(crate) fn make_layer(d: &mut Document, name: Option<&str>) -> Node { NewLayers::of(d).make(d, name) } -/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). +/// A layer colour: a preset index (0–26), `#rrggbb` or a preset's name (any case). A hex color +/// with an alpha part (`#rrggbbaa` or `#rgba`) is an error. pub(super) fn layer_color_param(v: &Value) -> std::result::Result { match v { Value::Number(n) => match n.as_u64() { @@ -308,7 +309,13 @@ pub(super) fn layer_color_param(v: &Value) -> std::result::Result color, + _ => panic!("not a layer"), + }; + let before = (color(&s), undos(&s)); + for bad in ["#ff000080", "ff000080", " #FF000080 ", "#f008"] { + let err = s.execute("layer.setProps", &json!({"id": layer.0, "color": bad})).unwrap_err().to_string(); + assert!(err.contains(&format!("`{bad}` is not a colour (#rrggbb or a preset name)")), "{bad}: {err}"); + assert!(s.execute("layer.new", &json!({"color": bad})).is_err(), "{bad}"); + assert!(s.execute("layer.newSublayer", &json!({"parent": layer.0, "color": bad})).is_err(), "{bad}"); + } + assert_eq!((color(&s), undos(&s)), before); + run(&mut s, "layer.setProps", json!({"id": layer.0, "color": "#ff0000"})); + assert_eq!(color(&s), LayerColor::Custom([0xff, 0, 0])); + run(&mut s, "layer.setProps", json!({"id": layer.0, "color": "Green"})); + assert_eq!(color(&s), LayerColor::Preset(2)); + let new = id(&run(&mut s, "layer.new", json!({"color": "#00ff00"}))); + assert!(matches!(node(&s, new).kind, NodeKind::Layer { color: LayerColor::Custom([0, 0xff, 0]), .. })); +} + #[test] fn new_layers_go_above_the_current_one_at_its_level() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 6c181f0dc1..b18adfa4b6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1864,7 +1864,9 @@ already walks Image Trace. Short agent entry points: covering source, including compound paths with shared curved boundaries. Expand keeps those face fills. With `detect: true`, paint stops at the gaps that run from a loose end of a path to the nearest path, up to `size` wide (`small` 3 pt, `medium` 6 pt, `large` 12 pt, or a - number of points up to 72); `closeGaps: true` adds an unpainted path across each of them. The options are saved with the group, and the reply + number of points up to 72); `closeGaps: true` adds an unpainted path across each of them. `color` (the Gap Preview + Color) is `#rrggbb` or a layer color's name; a hex color with an alpha part, `#rrggbbaa` or `#rgba`, is an error and + changes nothing. The options are saved with the group, and the reply and `livePaint.info` list the gaps up to `size` wide that no path closes, as `[x0, y0, x1, y1]`. `livePaint.merge` keeps the bottom group's options when its Gap Detection is on, and otherwise turns Gap Detection on with `small` when another merged group has it on. When Gap Detection is off in every merged group, it stays off. @@ -2600,7 +2602,8 @@ and `layerRows`, the rows highlighted in the panel. - **Eye and lock**: `layer.setProps {ids?, visible?, locked?, name?}` for any rows, plus Layer Options for layers: `template` (also locks the layer and dims its images to 50% unless given), `printable`, `preview` (off: the layer draws and is clicked in outline, Ctrl/Cmd-click its eye), `dimImages` (0–100, or false) and `color` (an index 0–26, - `#rrggbb` or a preset name). Several rows change in one undo step (a drag down the eye or lock column). + `#rrggbb` or a preset name; a hex color with an alpha part, `#rrggbbaa` or `#rgba`, is an error, and so it is in + `layer.new` and `layer.newSublayer`). Several rows change in one undo step (a drag down the eye or lock column). - **Dragging rows**: `layer.move {ids, target, place?: above|below|inside, copy?}` moves rows beside a row or into a layer or group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves copies. Layers go only in layers or at the top level and objects in layers and groups (an object placed beside a top-level layer goes diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 200bc86d43..730143c529 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -832,6 +832,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Arrange › Send to Current Layer returns the error "the target layer is locked or hidden" and leaves the selected objects where they are when the current layer is hidden or locked, or is inside a hidden or locked layer. Selected objects are deselected, the key object included, when a row drag moves them into a hidden layer or group, when `node.move` moves them into a hidden or locked layer or group, when Merge Selected moves them into a hidden or locked layer, when Collect in New Layer moves them into a new layer inside a hidden or locked layer, when Flatten Artwork moves them into a locked layer, and when applying a data set hides them. Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). + As VectorCraft's own rule, a layer color (`layer.setProps`, `layer.new`, `layer.newSublayer`) or a Live Paint Gap Preview Color (`livePaint.gapOptions`) given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing, instead of being set without its alpha. Regression tests: `a_layer_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/layers.rs` and `a_gap_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/build.rs`. Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. From a403e758021d5a509762515e7d2e7fd7b62e9492 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 18:29:25 +0700 Subject: [PATCH 038/482] Validate character style numeric dimensions Squashed from #5540 onto main. --- crates/engine/src/cmd/textstyles.rs | 34 +++++-- crates/engine/src/cmd/textstyles/tests.rs | 48 ++++++++++ .../ui-egui/src/dialogs/char_style_options.rs | 92 ++++++++++++++----- crates/ui-egui/src/dialogs/new_text_style.rs | 3 + docs/mcp.md | 7 +- docs/target-app-parity.md | 3 +- 6 files changed, 157 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 517af3a7b6..7e4786ed99 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -51,14 +51,14 @@ const fn spec(id: &'static str, label: &'static str, menu: &'static [&'static st } macro_rules! style_cmds { - ($kind:expr, $p:literal, $menu:literal, $what:literal) => { + ($kind:expr, $p:literal, $menu:literal, $what:literal, $bounds:literal) => { vec![ spec(concat!($p, ".list"), concat!($what, " Styles"), &[], "{} → {styles: [{name, attrs, uses}]}", |s, _| list(s, $kind), false), spec( concat!($p, ".new"), concat!("New ", $what, " Style"), &["Window", "Type", $menu], - "{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start", + concat!("{name? (trimmed, as rename trims `to`), attrs?: {…} (default: selected text), id?, start?: byte, end?: byte} → {name}; a nonempty character range samples its first selected character; start alone keeps insertion affinity; paragraph styles sample start", $bounds), |s, p| new(s, p, $kind), true, ), @@ -82,7 +82,7 @@ macro_rules! style_cmds { concat!($p, ".setAttrs"), concat!($what, " Style Options"), &[], - "{name, attrs: {…}} replace the style's attributes; users keep their overrides", + concat!("{name, attrs: {…}} replace the style's attributes; users keep their overrides", $bounds), |s, p| set_attrs(s, p, $kind), true, ), @@ -116,16 +116,22 @@ macro_rules! style_cmds { } pub fn specs() -> Vec { - let mut v = style_cmds!(Kind::Char, "charStyle", "Character Styles", "Character"); + let mut v = style_cmds!( + Kind::Char, + "charStyle", + "Character Styles", + "Character", + "; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt" + ); v.push(spec( "charStyle.edit", "Edit Character Style", &[], - "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides", + "{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: size 0.1..=1296 pt, explicit leading 0.1..=5000 pt, h/v scale 1..=10000%, baseline shift and Tate-chu-yoko offsets -1296..=1296 pt", |s, p| edit_style(s, p, Kind::Char), true, )); - v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph")); + v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", "")); v } @@ -494,6 +500,22 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma Kind::Char => { let mut st = with_attrs(&CharStyle::default(), m, &c)?; let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key); + for (key, value, lo, hi) in + [("size", st.size, 0.1, 1296.0), ("h_scale", st.h_scale, 1.0, 10000.0), ("v_scale", st.v_scale, 1.0, 10000.0)] + { + if changed(key) && !(lo..=hi).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {lo} to {hi}"))); + } + } + if changed("leading") && st.leading.is_some_and(|value| !(0.1..=5000.0).contains(&value)) { + return Err(bad(&c, "`leading` must be from 0.1 to 5000, or null for Auto")); + } + let shift_max = 1296.0; + for (key, value) in [("baseline_shift", st.baseline_shift), ("tcyUpDown", st.tcy_up_down), ("tcyLeftRight", st.tcy_left_right)] { + if changed(key) && !(-shift_max..=shift_max).contains(&value) { + return Err(bad(&c, format!("`{key}` must be from {} to {shift_max}", -shift_max))); + } + } // A language of the list, stored as its tag (as text.setFormat takes it). if let Some(l) = &st.language && kept.and_then(|k| k.get("language")) != m.get("language") diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 19da4c8ab0..221b09cab6 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -335,6 +335,54 @@ fn character_style_color_and_features_are_checked() { assert_eq!(s.doc().unwrap().history.undo.len(), undo); } +#[test] +fn character_style_dimensions_are_checked_before_a_definition_changes() { + let (mut s, _) = session_with_text("Text"); + s.execute("charStyle.new", &json!({"name": "Body", "attrs": {"size": 24.0}})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for attrs in [ + json!({"size": 0.0}), + json!({"size": 1296.1}), + json!({"leading": 0.0}), + json!({"leading": 5000.1}), + json!({"h_scale": 0.0}), + json!({"h_scale": 0.9}), + json!({"h_scale": 10000.1}), + json!({"v_scale": 0.0}), + json!({"v_scale": 0.9}), + json!({"v_scale": 10000.1}), + json!({"baseline_shift": -1296.1}), + json!({"baseline_shift": 1296.1}), + json!({"tcyUpDown": 1296.1}), + json!({"tcyLeftRight": -1296.1}), + ] { + let key = attrs.as_object().unwrap().keys().next().unwrap(); + for cmd in ["charStyle.edit", "charStyle.setAttrs", "charStyle.new"] { + let params = match cmd { + "charStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}), + "charStyle.new" => json!({"name": "Other", "attrs": attrs}), + _ => json!({"name": "Body", "attrs": attrs}), + }; + let error = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}"); + } + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + + s.execute( + "charStyle.setAttrs", + &json!({"name": "Body", "attrs": { + "size": 1296.0, "leading": 5000.0, + "h_scale": 1.0, "v_scale": 10000.0, + "baseline_shift": -1296.0, + "tcyUpDown": 1296.0, "tcyLeftRight": -1296.0 + }}), + ) + .unwrap(); +} + #[test] fn text_style_rejects_doubly_signed_feature_tags() { let (mut s, id) = session_with_text("Text"); diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 38c425a81b..41530de0e9 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -264,23 +264,29 @@ fn optional_number(d: &Dialog, key: &str) -> Result, String> { .or_else(|| v.as_str().and_then(|s| s.trim().parse::().ok())) .filter(|n| n.is_finite()) .ok_or_else(|| format!("{label} must be a number"))?; + // Character Style fields use the Character panel's visible ranges. + let max = match key { + "size" => 1296.0, + "leading" => 5000.0, + _ => vectorcraft_doc::MAX_COORD, + }; if ["size", "leading"].contains(&key) && n < 0.1 { return Err(format!("{label} must be a number of at least 0.1")); } - // The limits the document model keeps scales and baseline shift in. - let max = vectorcraft_doc::MAX_COORD; - if ["h_scale", "v_scale"].contains(&key) && !(n > 0.0 && n <= max) { - return Err(format!("{label} must be a number above 0 and at most {max}")); + if ["size", "leading"].contains(&key) && n > max { + return Err(format!("{label} must be a number at most {max}")); } - let min = -max; - if key == "baseline_shift" && !(min..=max).contains(&n) { - return Err(format!("{label} must be a number from {min} to {max}")); + if ["h_scale", "v_scale"].contains(&key) && !(1.0..=10000.0).contains(&n) { + return Err(format!("{label} must be a number from 1 to 10000")); + } + if key == "baseline_shift" && !(-1296.0..=1296.0).contains(&n) { + return Err(format!("{label} must be a number from -1296 to 1296")); } // Weight from 0 to the document limit, a tint from 0% to 100%. let (min, max) = match key { - "stroke_width" => (0.0, max), + "stroke_width" => (0.0, vectorcraft_doc::MAX_COORD), "fill_tint" | "stroke_tint" => (0.0, 100.0), - _ => (min, max), + _ => (0.0, 0.0), }; if ["stroke_width", "fill_tint", "stroke_tint"].contains(&key) && !(min..=max).contains(&n) { return Err(format!("{label} must be a number from {min} to {max}")); @@ -912,14 +918,17 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let params = json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs}); form::preview(app, ui, d, tl!("Character Style Options"), "charStyle.edit", params); } - Err(why) => { - ui.add_space(6.0); - ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), &why)); - } + Err(why) => attrs_error(ui, &why), } false } +/// The message `edited_attrs` gave for a field value it does not accept, drawn under the dialog. +pub(crate) fn attrs_error(ui: &mut egui::Ui, why: &str) { + ui.add_space(6.0); + ui.colored_label(crate::theme::Tokens::get(ui.ctx()).error, crate::i18n::message(crate::i18n::current(), why)); +} + fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let attrs = edited_attrs(d)?; form::commit_preview(app, "charStyle.edit", json!({"name": d.str("__style"), "to": d.str("name"), "attrs": attrs})) @@ -1135,13 +1144,15 @@ mod tests { } #[test] - fn advanced_numbers_outside_their_limits_are_errors() { + fn character_style_numbers_outside_their_limits_are_errors() { for (key, value, message) in [ - ("h_scale", "0", "Horizontal Scale must be a number above 0 and at most 4000000"), - ("h_scale", "-5", "Horizontal Scale must be a number above 0 and at most 4000000"), - ("v_scale", "4000001", "Vertical Scale must be a number above 0 and at most 4000000"), - ("baseline_shift", "4000001", "Baseline Shift must be a number from -4000000 to 4000000"), - ("baseline_shift", "-4000001", "Baseline Shift must be a number from -4000000 to 4000000"), + ("size", "1296.1", "Size must be a number at most 1296"), + ("leading", "5000.1", "Leading must be a number at most 5000"), + ("h_scale", "0", "Horizontal Scale must be a number from 1 to 10000"), + ("h_scale", "0.9", "Horizontal Scale must be a number from 1 to 10000"), + ("v_scale", "10000.1", "Vertical Scale must be a number from 1 to 10000"), + ("baseline_shift", "1296.1", "Baseline Shift must be a number from -1296 to 1296"), + ("baseline_shift", "-1296.1", "Baseline Shift must be a number from -1296 to 1296"), ("rotation", "inf", "Character Rotation must be a number"), ("h_scale", "wide", "Horizontal Scale must be a number"), ] { @@ -1150,10 +1161,15 @@ mod tests { assert_eq!(edited_attrs(&d).unwrap_err(), message, "{key} {value}"); } let mut d = dialog_for(json!({})); - for (key, value) in [("h_scale", "0.5"), ("v_scale", "4000000"), ("baseline_shift", "-4000000"), ("rotation", "-200")] { + for (key, value) in + [("size", "1296"), ("leading", "5000"), ("h_scale", "1"), ("v_scale", "10000"), ("baseline_shift", "-1296"), ("rotation", "-200")] + { d.fields.insert(key.into(), json!(value)); } - assert_eq!(edited_attrs(&d).unwrap(), attrs(json!({"h_scale": 0.5, "v_scale": 4000000.0, "baseline_shift": -4000000.0, "rotation": 160.0}))); + assert_eq!( + edited_attrs(&d).unwrap(), + attrs(json!({"size": 1296.0, "leading": 5000.0, "h_scale": 1.0, "v_scale": 10000.0, "baseline_shift": -1296.0, "rotation": 160.0})) + ); } #[test] @@ -1514,6 +1530,40 @@ mod tests { } } + #[test] + fn new_character_style_shows_size_and_leading_errors_before_ok() { + use egui_kittest::kittest::Queryable; + for (key, value) in [("size", json!(0)), ("leading", json!(0.05))] { + let mut app = app(); + app.run("ui.newCharStyle", json!({})).unwrap(); + let why = { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("section".into(), json!("basic")); + d.fields.insert(key.into(), value); + edited_attrs(d).unwrap_err() + }; + let shown = crate::i18n::message(crate::i18n::current(), &why); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + assert!(h.query_by_label(&shown).is_some(), "{key}: {shown} is not shown"); + let app = h.state_mut(); + let styles = app.session.doc().unwrap().doc.char_styles.len(); + assert!(super::super::confirm(app).is_err(), "{key} confirm"); + assert!(app.ui.dialog.is_some(), "{key} dialog stays open"); + assert_eq!(app.session.doc().unwrap().doc.char_styles.len(), styles, "{key} style count"); + } + } + #[test] fn invalid_number_keeps_last_valid_preview() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 3a769670f5..76b280b017 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -80,6 +80,9 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); super::char_style_options::reset_button(ui, d); + if let Err(why) = super::char_style_options::edited_attrs(d) { + super::char_style_options::attrs_error(ui, &why); + } return false; } grid(ui, |ui| { diff --git a/docs/mcp.md b/docs/mcp.md index b18adfa4b6..549b5f6b1c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5615,8 +5615,8 @@ dialog exposes `name`, `font_family`, `font_style`, `size`, `leading`, `kerning` `ot_figure`, `ot_position`, `ot_liga`, `ot_calt`, `ot_dlig`, `ot_swsh`, `ot_salt`, `ot_titl`, `ot_ordn`, `ot_frac`, `ot_sets`, `section` (`general`, `basic`, `advanced`, `color` or `opentype`), and `preview`. An empty field leaves its attribute unset. `leading` and `kerning` also accept `Auto` to store an explicit automatic value. -Advanced Character Formats holds `h_scale` and `v_scale` (percent, above 0 and at most 4000000), -`baseline_shift` (points, -4000000 to 4000000), `rotation` (degrees, stored from -180 to 180) and `language` (a name or tag from Document +Advanced Character Formats holds `h_scale` and `v_scale` (percent, 1 to 10000), +`baseline_shift` (points, -1296 to 1296), `rotation` (degrees, stored from -180 to 180) and `language` (a name or tag from Document Setup's languages; English: USA stores the explicit default `null`, and a tag not in the list that the style already has is kept). Language sets the language the characters are shaped in; it does not change hyphenation or spelling. @@ -5637,6 +5637,9 @@ its features turned off, distinct from unset. `charStyle.new`, `charStyle.setAttrs` and `charStyle.edit` reject a tint outside 0 to 1, a link to a swatch that is not a global swatch of the document, a stroke weight outside 0 to 4000000, more than 256 feature tags and an OpenType feature tag the shaper does not know, unless the style or the text it is made from already has that value. +They also reject a size outside 0.1 to 1296, explicit leading outside 0.1 to 5000, horizontal or vertical scale +outside 1 to 10000, and baseline shift or Tate-chu-yoko offsets outside -1296 to 1296. `leading: null` keeps +Auto leading. An invalid value leaves the style, its text, and Undo history unchanged. The New Character Style dialog accepts the same character fields and starts with the selected text's captured attributes. Without selected text, it starts with the character defaults for the interface language (including `charAlign: "emBoxCenter"` in Japanese); changing a Basic field keeps other seeded attributes. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 730143c529..1027fc25aa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -518,8 +518,9 @@ since 2026-10-01. - **COLR colour fonts:** v0 and v1 glyphs draw as vector layers (solid colours, linear and radial gradients, clips, blend modes, the foreground colour from the run's fill) on the canvas, as paths in SVG, EPS, legacy `.ai` and PDF with outlined text, as Type 3 text in PDF, and as editable groups with Create Outlines; sweep gradients and Porter-Duff compositing draw the glyph as an image. Measured by `tests_colr`, `render::tests_colrglyphs`, `pdf::tests::colr_glyphs_export_as_vector_art`, `svg/tests/it/colour_glyphs.rs`, `eps` `colr_glyphs_*`, `tests_pathops::create_outlines_turns_colr_glyphs_into_layer_groups`. Scores unchanged (estimated). - **OpenType SVG colour fonts:** each glyph's SVG document is read by the SVG importer (registered by the engine) into vector art in the run's colours, then drawn, exported and outlined as COLR glyphs are; PDF real text writes them as text that draws nothing and draws their art where they sit. Measured by `tests_svg_glyphs`, `svg/tests/it/svg_glyphs.rs`, `tests_colourfonts::create_outlines_turns_svg_glyphs_into_groups`, `tests_colourfonts::pdf_real_text_draws_svg_glyphs_as_art_and_keeps_their_characters`. Scores unchanged (estimated). - **Character-style Auto leading:** capture and explicit style attributes retain Auto as a reset, distinct from omitted leading. Redefine and later numeric updates preserve local leading overrides; the Character Styles marker recognizes Auto correctly. Regression assertions cover partial definitions, Undo/Redo and native save/load serialization. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Leading](https://helpx.adobe.com/illustrator/using/line-character-spacing.html). +- **Character-style numeric bounds:** `charStyle.new`, `charStyle.edit`, and `charStyle.setAttrs` accept size from 0.1 to 1296 pt, explicit leading from 0.1 to 5000 pt, horizontal and vertical scale from 1% to 10,000%, and baseline shift and Tate-chu-yoko offsets from -1296 to 1296 pt. Out-of-range input leaves the style and Undo history unchanged; Auto leading remains available. These limits match the Character panel controls. - **Character Style Options, General and Basic Character Formats:** the dialog edits a style's name and stored character formats together. Empty fields remain unset, checkboxes show an indeterminate unset state, Basic's Reset Panel clears its explicit settings, and Preview can be canceled without changing history. OK saves one undo step; New Character Style offers the same fields from captured text or the interface language's defaults without a selection. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). -- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (above 0% and at most 4,000,000%), Baseline Shift (-4,000,000 pt to 4,000,000 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). +- **Character Style Options, Advanced Character Formats:** Character Style Options and New Character Style set a style's Horizontal Scale and Vertical Scale (1% to 10,000%), Baseline Shift (-1296 pt to 1296 pt), Character Rotation (stored from -180° to 180°) and Language; text that uses the style takes them and keeps its local overrides. Empty fields remain unset, an explicit 100%, 0° or English: USA stays distinct from unset, and the section's Reset Panel clears only these five. Language sets the language the characters are shaped in, not hyphenation or spelling. Public reference: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Character Style Options, Character Color and OpenType Features:** Character Style Options and New Character Style set a style's fill and stroke (None or a document swatch; a global swatch stays linked, with a Tint from 0% to 100%), stroke Weight, Overprint Fill and Overprint Stroke, and its Figure, Position, Standard and Discretionary Ligatures, Contextual, Stylistic and Titling Alternates, Swash, Ordinals, Fractions and Stylistic Sets 1 to 20; text that uses the style takes them and keeps its local overrides, and editing a global swatch later updates the style and its text. Empty controls remain unset, an explicit None, off, Default Figure or Default Position stays distinct from unset, each stylistic set is on, off or unset, a gradient or pattern paint stays until another paint is chosen, a changed OpenType control keeps the style's other feature tags, and each section's Reset Panel clears only its own attributes. Public references: [Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html) and [Format text with OpenType features](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/format-text-with-opentype-features.html). - **Text styles redefined to the defaults:** New and Redefine Character Style and Paragraph Style capture every attribute of the selected text, including those at their defaults (Auto kerning, Roman baseline alignment, the default Hyphenation options, the Every-line Composer, no tab stops), and `charStyle.setAttrs` and `paraStyle.setAttrs` keep an attribute set to its default value. After a redefinition, text whose value still equals the old definition's takes the new value, a default included; local overrides stay, and text that still has the old value of an attribute the new definition leaves out goes back to the Normal style's value. The style panels show "+" only where the text differs from its style, including type with Auto alignment. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Text styles dragged onto the panel's buttons:** a style dragged from the Character Styles or Paragraph Styles panel onto Create New Style is copied (`charStyle.duplicate`, `paraStyle.duplicate`, which name the copy ` copy`) and the copy is highlighted; dragged onto Delete it is deleted (`charStyle.delete`, `paraStyle.delete`); the Normal style is not deleted. Each drop is one undo step. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). From 30f903bf602df8270850192ef69f971198927c1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 23:32:53 -0800 Subject: [PATCH 039/482] Navigator: Panel Options sets the view box color and draws dashed lines as solid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Navigator panel menu's Panel Options… is enabled and opens a dialog with the view box color (a preset or a custom color; Light Red, today's color, is the default) and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only. The options are kept with the UI state, and ui.navigatorPanelOptions sets them. RenderOptions::solid_dashes draws dashed strokes as solid lines, including type strokes and the silhouettes of stroke effects. --- crates/render/src/frame.rs | 12 +- crates/render/src/fx/pixels.rs | 1 + crates/render/src/options.rs | 4 + crates/render/src/renderer/paint.rs | 7 + crates/render/src/tests.rs | 31 +++ crates/ui-egui/src/dialogs.rs | 2 + .../src/dialogs/navigator_panel_options.rs | 101 ++++++++ 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 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panels/navigator.rs | 225 ++++++++++++++++-- crates/ui-egui/src/state.rs | 4 + docs/mcp.md | 15 ++ docs/target-app-parity.md | 1 + 39 files changed, 447 insertions(+), 15 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/navigator_panel_options.rs diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 0009957625..81b7198937 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, SymbolBoxes, TextObject, live}; +use super::{Affine, Arc, BezPath, Document, FillRule, HashMap, Ink, Node, Rect, RenderContext, StrokeLayer, SymbolBoxes, TextObject, live}; /// Hasher for pointer-keyed caches: a multiply-xorshift (SipHash showed up in frame profiles). #[derive(Default, Clone, Copy)] @@ -145,6 +145,16 @@ impl Frame<'_> { (self.opts.anti_alias == AntiAlias::Type).then(|| self.view * t.xf) } + /// Stroke `st` as this frame draws it: a copy without its dashes when the frame draws dashed + /// lines as solid lines ([`RenderOptions::solid_dashes`]), else `st` itself. + pub(crate) fn stroke<'s>(&self, st: &'s StrokeLayer) -> std::borrow::Cow<'s, StrokeLayer> { + if self.opts.solid_dashes && st.dash.is_some() { + std::borrow::Cow::Owned(StrokeLayer { dash: None, ..st.clone() }) + } else { + std::borrow::Cow::Borrowed(st) + } + } + /// A render context for drawing this frame's art offscreen (on the calling thread), with its /// edge smoothing: hard edges must not depend on where the art is drawn. pub(crate) fn offscreen_context(&self, w: u16, h: u16) -> RenderContext { diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index e89f2bddac..1f1b160ac7 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -640,6 +640,7 @@ impl Renderer { let outline = match item { AppearanceItem::Fill(_) => ig.clone(), AppearanceItem::Stroke(st) => { + let st = &*f.stroke(st); let w = effects::stroke::aligned_width(st, effects::stroke::is_closed(ig)); effects::stroke::line_outline(&effects::stroke::stroke_pieces(ig, st).line, st, w, f.px * 0.25) } diff --git a/crates/render/src/options.rs b/crates/render/src/options.rs index 595f9797b3..93d0f07b9a 100644 --- a/crates/render/src/options.rs +++ b/crates/render/src/options.rs @@ -134,6 +134,9 @@ pub struct RenderOptions { /// Appearance of Black's Rich Black: pure CMYK black (black ink alone at 100%) shows as RGB /// black. Off, it shows through the CMYK profile, a dark grey, as other colours do. pub rich_black: bool, + /// Dashed strokes draw as solid lines, without their dashes (the Navigator's Draw Dashed Lines + /// as Solid Lines). Off, they draw their dashes. + pub solid_dashes: bool, } /// The opacity of the art around an isolated group or layer. @@ -219,6 +222,7 @@ impl Default for RenderOptions { interacting: false, dragging: false, rich_black: false, + solid_dashes: false, } } } diff --git a/crates/render/src/renderer/paint.rs b/crates/render/src/renderer/paint.rs index e39f106e8c..00d9153c1b 100644 --- a/crates/render/src/renderer/paint.rs +++ b/crates/render/src/renderer/paint.rs @@ -97,6 +97,13 @@ impl Renderer { chars: Option<(&Arc, usize)>, bounds: Rect, ) { + // A stroke drawn without its dashes is a copy, not the document's stroke: its outline is + // made here and not kept with the document's outlines. + let drawn = f.stroke(st); + let (st, chars) = match &drawn { + std::borrow::Cow::Owned(solid) => (solid, None), + std::borrow::Cow::Borrowed(st) => (*st, chars), + }; let pieces = effects::stroke::stroke_pieces(bp, st); // The line and its heads overlap: they take the opacity once, in one layer, instead of // each folding it into its paint. diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index a723c4da8d..2a6a4872d1 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1292,6 +1292,37 @@ fn invalid_dash_pattern_strokes_solid() { } } +/// With `solid_dashes` a dashed stroke draws as the same stroke without dashes, on its own and as +/// the silhouette of a drop shadow; without it the dashes stay. +#[test] +fn solid_dashes_draw_dashed_strokes_as_solid_lines() { + let line = |dash: bool, shadow: bool| { + let mut d = Document::new(100.0, 100.0); + let mut bp = BezPath::new(); + bp.move_to((10.0, 50.0)); + bp.line_to((90.0, 50.0)); + let id = d.alloc_id(); + let mut n = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 6.0)); + let st = n.appearance.stroke_mut().unwrap(); + st.dash = dash.then(|| vectorcraft_doc::Dash { pattern: vec![8.0, 8.0], ..Default::default() }); + if shadow { + let params = serde_json::json!({"x": 4, "y": 4, "blur": 1, "opacity": 100}); + st.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params, visible: true }); + } + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d + }; + let opts = |solid_dashes: bool| RenderOptions { background: Some([255, 255, 255, 255]), solid_dashes, ..Default::default() }; + let draw = |d: &Document, solid: bool| Renderer::new().render(d, 100, 100, Affine::IDENTITY, &opts(solid)); + for shadow in [false, true] { + let solid = draw(&line(false, shadow), false); + assert_ne!(draw(&line(true, shadow), false).pixels, solid.pixels, "the dashes show without the option (shadow: {shadow})"); + assert_eq!(draw(&line(true, shadow), true).pixels, solid.pixels, "the dashes go with the option (shadow: {shadow})"); + assert_eq!(draw(&line(false, shadow), true).pixels, solid.pixels, "a solid stroke is unchanged (shadow: {shadow})"); + } +} + /// An image that can't be decoded is counted on the thread that tried to decode it: an export /// compares [`decode_failures`] before and after it draws, so another thread's failure meanwhile is /// not its own. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 67219de40a..250f18647c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -63,6 +63,7 @@ pub mod live_paint_selection; pub mod missing_fonts; pub mod missing_links; pub(crate) mod modal; +pub mod navigator_panel_options; pub mod new_brush; pub mod new_color_group; mod new_document; @@ -405,6 +406,7 @@ registry! { PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC, LayerOptions: [layer_options::KIND] => layer_options::SPEC, LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC, + NavigatorPanelOptions: [navigator_panel_options::KIND] => navigator_panel_options::SPEC, PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC, RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs new file mode 100644 index 0000000000..c3582ae59a --- /dev/null +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -0,0 +1,101 @@ +//! Navigator panel › Panel Options…: the color the view box is drawn in, a preset or a custom +//! color, and Draw Dashed Lines as Solid Lines for the thumbnail. +//! +//! Fields: `color` (`#rrggbb`, or a preset's name such as "Light Red") and `solidDashes`. OK runs +//! `ui.navigatorPanelOptions` with them (kept with the UI state). + +use serde_json::{Value, json}; +use vectorcraft_color::Color; + +use super::swatch_options::{grid, label}; +use super::{DialogSpec, run_and_close}; +use crate::panels::navigator::{VIEW_BOX_RED, resolve, view_box_colors}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of the Navigator Panel Options. +pub const KIND: &str = "navigatorPanelOptions"; + +pub(super) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Navigator Panel Options").into(), body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// `ui.navigatorPanelOptions` without options: open the dialog on the panel's options. +pub fn open(app: &mut VectorcraftApp) -> Result { + let o = &app.ui.navigator_panel; + app.ui.dialog = Some(Dialog::new(KIND, json!({ "color": o.color, "solidDashes": o.solid_dashes }))); + Ok(Value::Null) +} + +fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let [r, g, b] = resolve(&d.str("color")).unwrap_or(VIEW_BOX_RED); + let presets: Vec<(&str, [u8; 3])> = view_box_colors().collect(); + let preset = presets.iter().position(|(_, c)| *c == [r, g, b]); + let names: Vec<&str> = presets.iter().map(|(n, _)| *n).chain(["Custom"]).collect(); + grid(ui, |ui| { + label(ui, tl!("Color:")); + ui.horizontal(|ui| { + if let Some((_, [r, g, b])) = + widgets::dropdown(ui, "navigator-view-box", names[preset.unwrap_or(presets.len())], &names, 140.0).and_then(|i| presets.get(i)) + { + d.fields.insert("color".into(), json!(Color::rgb8(*r, *g, *b).to_hex())); + } + // Any other color (the preset list shows Custom then). + let mut rgb = [r, g, b]; + if ui.color_edit_button_srgb(&mut rgb).changed() { + d.fields.insert("color".into(), json!(Color::rgb8(rgb[0], rgb[1], rgb[2]).to_hex())); + } + }); + ui.end_row(); + }); + ui.add_space(8.0); + let solid = d.bool("solidDashes"); + if widgets::check(ui, tl!("Draw Dashed Lines as Solid Lines"), solid, true) { + d.fields.insert("solidDashes".into(), json!(!solid)); + } + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = json!({ "color": d.fields.get("color").cloned().unwrap_or(Value::Null), "solidDashes": d.bool("solidDashes") }); + run_and_close(app, "ui.navigatorPanelOptions", params) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// The dialog opens on the panel's options (Light Red and solid dashes off by default), and OK + /// sets a preset's or a custom color and Draw Dashed Lines as Solid Lines, kept with the UI + /// state; a value that is not a color is refused and leaves the options as they were. + #[test] + fn panel_options_set_the_view_box_color_and_solid_dashes() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.navigatorPanelOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), d.str("color"), d.bool("solidDashes")), (KIND, "#ff3030".to_string(), false)); + // Drawn headlessly in the shared frame: the preset's name shows. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let set = |app: &mut VectorcraftApp, color: &str, solid: bool| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("color".into(), json!(color)); + d.fields.insert("solidDashes".into(), json!(solid)); + super::super::confirm(app) + }; + assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true})); + assert!(app.ui.dialog.is_none()); + app.run("ui.navigatorPanelOptions", json!({})).unwrap(); + set(&mut app, "#0000FF", true).unwrap(); + assert_eq!(app.ui.navigator_panel.color, "#0000ff"); + app.run("ui.navigatorPanelOptions", json!({})).unwrap(); + assert!(set(&mut app, "nope", false).is_err()); + assert!(app.ui.navigator_panel.solid_dashes && app.ui.navigator_panel.color == "#0000ff", "a refused value changes nothing"); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert_eq!(back.navigator_panel, app.ui.navigator_panel, "kept with the UI state"); + let old: crate::UiState = serde_json::from_value(json!({})).unwrap(); + assert_eq!(old.navigator_panel, crate::panels::navigator::PanelOptions::default(), "UI state saved without them"); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index cce9ebd4ef..ed5017b230 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1920,6 +1920,8 @@ font-technology Variable Променливи Name: Име: Navigate Навигация Navigator Навигатор + Navigator Panel Options Опции за панела „Навигатор“ + Draw Dashed Lines as Solid Lines Изчертаване на прекъснатите линии като плътни Needs the desktop app Изисква десктоп приложение Neutral Gradients Неутрални градиенти New Нов diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 098c02cd40..0d0806fb1d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -683,6 +683,8 @@ Update Changed Links Ažuriraj promijenjene veze Magic Wand Čarobni štapić Navigator Navigator + Navigator Panel Options Opcije panela navigatora + Draw Dashed Lines as Solid Lines Crtaj isprekidane linije kao pune Pattern Options Opcije uzorka Properties Svojstva Separations Preview Pregled separacija diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 93fe3cb2b6..8f4fc17099 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2495,6 +2495,8 @@ digits Malayalam Malaiàlam Names the script builds as it runs: {count} Noms que l’script crea mentre s’executa: {count} Navigate Navega Navigator Navegador + Navigator Panel Options Opcions del panell Navegador + Draw Dashed Lines as Solid Lines Dibuixa les línies discontínues com a contínues Needs a choice Necessita una tria Needs a key Necessita una clau Needs Attention Only Només necessita atenció diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3d287457e5..5e63bd7359 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -691,6 +691,8 @@ Update Changed Links Aktualizovat změněná propojení Magic Wand Kouzelná hůlka Navigator Navigátor + Navigator Panel Options Možnosti panelu Navigátor + Draw Dashed Lines as Solid Lines Kreslit čárkované čáry jako plné Pattern Options Možnosti vzorku Properties Vlastnosti Separations Preview Náhled separací diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index e45c0a364c..7902408012 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -640,6 +640,8 @@ Update Changed Links Opdatér ændrede links Magic Wand Magisk tryllestav Navigator Navigator + Navigator Panel Options Indstillinger for navigatorpanelet + Draw Dashed Lines as Solid Lines Tegn stiplede linjer som hele linjer Pattern Options Mønsterindstillinger Properties Egenskaber Separations Preview Separationsforhåndsvisning diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 8db779ee49..6494f51c95 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1982,6 +1982,8 @@ file-filter Templates Vorlagen Name: Name: Navigate Navigieren Navigator Navigator + Navigator Panel Options Optionen für das Navigatorbedienfeld + Draw Dashed Lines as Solid Lines Gestrichelte Linien als durchgezogene Linien zeichnen Needs the desktop app Erfordert die Desktop-App Neutral Gradients Neutrale Verläufe New Neu diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 071628cc8c..a1a7586409 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1696,6 +1696,8 @@ font-technology Variable Μεταβλητές Name Όνομα Name: Όνομα: Navigator Πλοήγηση + Navigator Panel Options Επιλογές πίνακα πλοήγησης + Draw Dashed Lines as Solid Lines Σχεδίαση διακεκομμένων γραμμών ως συνεχών New Νέο Scatter: Διασπορά: Rotation: Περιστροφή: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c63c6a07bd..2b6207e904 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1985,6 +1985,8 @@ font-technology Variable Variables Name: Nombre: Navigate Navegar Navigator Navegador + Navigator Panel Options Opciones del panel Navegador + Draw Dashed Lines as Solid Lines Dibujar líneas discontinuas como continuas Needs the desktop app Requiere la aplicación de escritorio Neutral Gradients Degradados neutros New Nuevo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 03f290305b..099ba3aabc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -682,6 +682,8 @@ Update Changed Links Päivitä muuttuneet linkit Magic Wand Taikasauva Navigator Navigaattori + Navigator Panel Options Navigaattori-paneelin asetukset + Draw Dashed Lines as Solid Lines Piirrä katkoviivat yhtenäisinä viivoina Pattern Options Kuvion asetukset Properties Ominaisuudet Separations Preview Erottelujen esikatselu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a0f15e3ccd..d5135983e0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1979,6 +1979,8 @@ font-technology Variable Variables Name: Nom : Navigate Naviguer Navigator Navigation + Navigator Panel Options Options du panneau Navigation + Draw Dashed Lines as Solid Lines Dessiner les pointillés en traits pleins Needs the desktop app Nécessite l’application de bureau Neutral Gradients Dégradés neutres New Nouveau diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e727d6abac..c97cfd5f9b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2505,6 +2505,8 @@ file-filter Templates Sablonok Name: Név: Navigate Navigálás Navigator Navigátor + Navigator Panel Options Navigátor panel beállításai + Draw Dashed Lines as Solid Lines Szaggatott vonalak rajzolása folytonosként Needs the desktop app Az asztali alkalmazás kell hozzá Negative Negatív Neutral Gradients Semleges színátmenetek diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index a15eddbb0a..af2504c742 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -640,6 +640,8 @@ Update Changed Links Perbarui tautan yang berubah Magic Wand Tongkat ajaib Navigator Navigator + Navigator Panel Options Opsi panel navigator + Draw Dashed Lines as Solid Lines Gambar garis putus-putus sebagai garis utuh Pattern Options Opsi pola Properties Properti Separations Preview Pratinjau separasi diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 4f93e78961..ef5b0f3bd5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2014,6 +2014,8 @@ file-filter Templates Modelli Name: Nome: Navigate Naviga Navigator Navigatore + Navigator Panel Options Opzioni pannello Navigatore + Draw Dashed Lines as Solid Lines Disegna le linee tratteggiate come linee continue Needs the desktop app Richiede l'app desktop Neutral Gradients Sfumature neutre New Nuovo diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 806f1bcc3f..0a70417548 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -692,6 +692,8 @@ digits Malayalam マラヤーラム数字 Links リンク Magic Wand 自動選択 Navigator ナビゲーター + Navigator Panel Options ナビゲーターパネルオプション + Draw Dashed Lines as Solid Lines 破線を実線で表示 Pattern Options パターンオプション Properties プロパティ Separations Preview 分版プレビュー diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 855a8f6fc6..0071c0cd96 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -590,6 +590,8 @@ Update Changed Links შეცვლილი ბმულების განახლება Magic Wand ჯადოსნური ჯოხი Navigator ნავიგატორი + Navigator Panel Options ნავიგატორის პანელის პარამეტრები + Draw Dashed Lines as Solid Lines ტირეებიანი ხაზების უწყვეტ ხაზებად დახატვა Pattern Options პატერნის პარამეტრები Properties თვისებები Separations Preview სეპარაციის წინასწარი ნახვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 04006d209f..335f3f61d0 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -685,6 +685,8 @@ digits Malayalam 말라얄람어 Links 링크 Magic Wand 마술봉 Navigator 내비게이터 + Navigator Panel Options 내비게이터 패널 옵션 + Draw Dashed Lines as Solid Lines 점선을 실선으로 그리기 Pattern Options 패턴 옵션 Properties 속성 Separations Preview 분판 미리 보기 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 671f78da3d..a0bd063ec0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -654,6 +654,8 @@ Update Changed Links Gewijzigde koppelingen bijwerken Magic Wand Magische toverstaf Navigator Navigator + Navigator Panel Options Opties voor het paneel Navigator + Draw Dashed Lines as Solid Lines Streepjeslijnen als doorgetrokken lijnen tekenen Pattern Options Patroonopties Properties Eigenschappen Separations Preview Scheidingsvoorbeeld diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index cf9c4edf82..1859749883 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -639,6 +639,8 @@ Update Changed Links Aktualizuj zmienione łącza Magic Wand Różdżka Navigator Nawigator + Navigator Panel Options Opcje panelu Nawigator + Draw Dashed Lines as Solid Lines Rysuj linie przerywane jako ciągłe Pattern Options Opcje wzorka Properties Właściwości Separations Preview Podgląd rozbarwień diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index d29cac871f..6158558189 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1676,6 +1676,8 @@ Name: Nome: Navigate Navegar Navigator Navegador + Navigator Panel Options Opções do painel Navegador + Draw Dashed Lines as Solid Lines Desenhar linhas tracejadas como linhas sólidas Needs the desktop app Requer o aplicativo de desktop Neutral Gradients Gradientes Neutros New Novo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 13948efde2..b4cdb4da37 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2011,6 +2011,8 @@ file-filter Templates Шаблоны Name: Имя: Navigate Навигация Navigator Навигатор + Navigator Panel Options Параметры панели «Навигатор» + Draw Dashed Lines as Solid Lines Рисовать штриховые линии сплошными Needs the desktop app Требуется настольное приложение Neutral Gradients Нейтральные градиенты New Создать diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index babde2822c..50c91f44ea 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1926,6 +1926,8 @@ font-technology Variable Variabla Name: Namn: Navigate Navigera Navigator Navigator + Navigator Panel Options Alternativ för panelen Navigator + Draw Dashed Lines as Solid Lines Rita streckade linjer som heldragna linjer Needs the desktop app Kräver skrivbordsappen Neutral Gradients Neutrala gradienter New Nytt diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f2850ce927..2e618b1032 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1815,6 +1815,8 @@ font-technology Variable Değişken Name: İsim: Navigate Gezin Navigator Gezgin + Navigator Panel Options Gezgin Paneli Seçenekleri + Draw Dashed Lines as Solid Lines Kesikli Çizgileri Düz Çizgi Olarak Çiz Needs the desktop app Masaüstü uygulaması gerekiyor Neutral Gradients Nötr Degradeler New Yeni diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 21b77da4be..5d8e2f3b5b 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2008,6 +2008,8 @@ file-filter Templates Шаблони Name: Назва: Navigate Навігація Navigator Навігатор + Navigator Panel Options Параметри панелі «Навігатор» + Draw Dashed Lines as Solid Lines Малювати штрихові лінії суцільними Needs the desktop app Потрібен настільний додаток Neutral Gradients Нейтральні градієнти New Створити diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index c456663aa1..b0d51a9de9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2315,6 +2315,8 @@ digits Hindi Hindi Name: Tên: Navigate Dẫn hướng Navigator Bộ dẫn hướng + Navigator Panel Options Tùy chọn bảng bộ dẫn hướng + Draw Dashed Lines as Solid Lines Vẽ đường nét đứt thành đường liền Needs the desktop app Cần ứng dụng máy tính để bàn Neutral Gradients Chuyển sắc trung tính New Mới diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index a55c343f25..f4446b27b1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1897,6 +1897,8 @@ file-filter Templates 模板 Name: 名称: Navigate 导航 Navigator 导航器 + Navigator Panel Options 导航器面板选项 + Draw Dashed Lines as Solid Lines 将虚线绘制为实线 Needs the desktop app 需要桌面应用 Neutral Gradients 中性渐变 New 新建 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 3eab26ac64..9c28472149 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2867,6 +2867,8 @@ file-filter Templates 範本 Name: 名稱: Navigate 導覽 Navigator 導覽器 + Navigator Panel Options 導覽器面板選項 + Draw Dashed Lines as Solid Lines 將虛線繪製為實線 Needs the desktop app 需要桌面版應用程式 Neutral Gradients 中性漸層 New 新增 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index f54153cbdf..c20e3b6504 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -694,6 +694,7 @@ fn run_ui_part8(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::layer_options::open_new(app, p), "ui.newArtboard" => crate::dialogs::artboard_options::open_new(app), "ui.layersPanelOptions" => crate::dialogs::layers_panel_options::open(app), + "ui.navigatorPanelOptions" => crate::panels::navigator::set_options(app, p), "ui.layersExpand" => crate::panels::layers::expand(app, p), "ui.layersFilter" => crate::panels::layers::set_filter(app, p), "ui.flattenTransparencyDialog" => { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 3af5f1b9fc..5e9c10e355 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -867,6 +867,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open the Layers panel's Panel Options: dialog `layersPanelOptions`, fields layersOnly, locateSelected (Locate Selected Objects, off by default: when the last selected object changes outside the panel, on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as after layer.locate, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off; a change made during a drag is located when the drag ends), rowSize (small|medium|large|other), otherSize (12–100 pt), thumbLayers, thumbGroups, thumbObjects; OK applies them (kept with the UI state)", ), + ( + "ui.navigatorPanelOptions", + "Panel Options…", + "", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + ), ( "ui.layersExpand", "Expand Layers Panel Rows", diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 2b53ee61a6..da8048407b 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -1,12 +1,16 @@ //! Navigator panel: a thumbnail of the document (rendered with `Renderer::render_region_with`, //! cached by document revision, off the UI thread for heavy documents and not during drags: see -//! [`crate::thumb_worker`]) with the red view box you drag to pan, zoom out/in buttons, a zoom slider -//! and a zoom field. +//! [`crate::thumb_worker`]) with the view box you drag to pan, zoom out/in buttons, a zoom slider +//! and a zoom field. Panel Options… sets the view box's color and whether the thumbnail draws +//! dashed lines as solid lines ([`PanelOptions`]). use std::sync::Arc; use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; -use serde_json::json; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::LAYER_COLORS; use vectorcraft_geom::{Point, Rect as DRect}; use super::{pstate, set_pstate}; @@ -15,7 +19,77 @@ use crate::theme::Tokens; use crate::thumb_worker::{Settle, ThumbWorker}; use crate::widgets::{self, menu_item}; -/// What a navigator image shows: document `uid` at `revision`, `w`×`h` pixels, the artboards only. +/// The view box's color by default (Light Red, the first of [`view_box_colors`]). +pub const VIEW_BOX_RED: [u8; 3] = [0xff, 0x30, 0x30]; + +/// The view box color presets of Panel Options: Light Red, the default, then the layer colors. +pub fn view_box_colors() -> impl Iterator { + std::iter::once(("Light Red", VIEW_BOX_RED)).chain(LAYER_COLORS.iter().copied()) +} + +/// `color` (a preset's name, in any case, or `#rrggbb`) as RGB; `None` for anything else, +/// including a color with an alpha or a short `#rgb`. +pub fn resolve(color: &str) -> Option<[u8; 3]> { + let color = color.trim(); + if let Some((_, rgb)) = view_box_colors().find(|(name, _)| name.eq_ignore_ascii_case(color)) { + return Some(rgb); + } + let hex = color.strip_prefix('#').filter(|h| h.len() == 6 && h.bytes().all(|b| b.is_ascii_hexdigit()))?; + let byte = |at: usize| u8::from_str_radix(hex.get(at..at + 2)?, 16).ok(); + Some([byte(0)?, byte(2)?, byte(4)?]) +} + +/// Navigator panel options (≡ › Panel Options…), kept with the UI state. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct PanelOptions { + /// The view box's color, `#rrggbb`. + pub color: String, + /// Draw Dashed Lines as Solid Lines (off by default): the thumbnail draws dashed strokes + /// without their dashes. The canvas, printing and exports keep the dashes. + pub solid_dashes: bool, +} + +impl Default for PanelOptions { + fn default() -> Self { + let [r, g, b] = VIEW_BOX_RED; + Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false } + } +} + +impl PanelOptions { + /// The color the view box is drawn in: [`Self::color`], or Light Red when it is not a color. + pub fn view_box(&self) -> Color32 { + let [r, g, b] = resolve(&self.color).unwrap_or(VIEW_BOX_RED); + Color32::from_rgb(r, g, b) + } +} + +/// `ui.navigatorPanelOptions {color?, solidDashes?}`: with neither, open Panel Options on the +/// panel's options; otherwise set the ones given and answer the options. +pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result { + let (color, solid) = (p.get("color"), p.get("solidDashes")); + if color.is_none() && solid.is_none() { + return crate::dialogs::navigator_panel_options::open(app); + } + let mut o = app.ui.navigator_panel.clone(); + if let Some(c) = color { + let [r, g, b] = c.as_str().and_then(resolve).ok_or_else(|| { + let color = c.as_str().map_or_else(|| c.to_string(), str::to_string); + format!("`{color}` is not a colour (#rrggbb or a preset name)") + })?; + o.color = Color::rgb8(r, g, b).to_hex(); + } + if let Some(s) = solid { + let key = "solidDashes"; + o.solid_dashes = s.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; + } + app.ui.navigator_panel = o; + Ok(serde_json::to_value(&app.ui.navigator_panel).unwrap_or_default()) +} + +/// What a navigator image shows: document `uid` at `revision`, `w`×`h` pixels, the artboards only, +/// dashed lines drawn as solid lines. #[derive(Clone, Copy, Debug, PartialEq)] struct ImageKey { uid: u64, @@ -23,6 +97,7 @@ struct ImageKey { w: u32, h: u32, artboard_only: bool, + solid_dashes: bool, } #[derive(Default)] @@ -118,27 +193,44 @@ impl Cache { return; } let s = (key.w as f64 / region.width()).min(key.h as f64 / region.height()); - // As exported (template layers and guides left out), transparent; images far smaller than - // they are sample their mip levels. - let opts = vectorcraft_render::RenderOptions { skip_templates: true, image_mips: true, ..Default::default() }; + let opts = image_options(key); let heavy = self.last_ms > HEAVY_MS && have; if heavy && let Some(w) = &self.worker { let (doc, opts) = (doc.clone(), opts.clone()); - if w.submit((), (key, region), Box::new(move |r| Some(r.render_region_with(&doc, region, s, &opts)))) { + let job = move |r: &mut vectorcraft_render::Renderer| { + if opts.solid_dashes { + SOLID_RENDERER.with(|solid| solid.borrow_mut().render_region_with(&doc, region, s, &opts)) + } else { + r.render_region_with(&doc, region, s, &opts) + } + }; + if w.submit((), (key, region), Box::new(move |r| Some(job(r)))) { self.pending = Some(key); return; } self.worker = None; } let t0 = crate::now_ms(); - let img = NAV_RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, s, &opts)); + let renderer = if key.solid_dashes { &SOLID_RENDERER } else { &NAV_RENDERER }; + let img = renderer.with(|r| r.borrow_mut().render_region_with(doc, region, s, &opts)); self.upload(ctx, key, region, &img, crate::now_ms() - t0); } } +/// How the image `key` names is drawn: as exported (template layers and guides left out), +/// transparent, with images far smaller than they are sampling their mip levels, and with Draw +/// Dashed Lines as Solid Lines, dashed strokes without their dashes. +fn image_options(key: ImageKey) -> vectorcraft_render::RenderOptions { + vectorcraft_render::RenderOptions { skip_templates: true, image_mips: true, solid_dashes: key.solid_dashes, ..Default::default() } +} + thread_local! { /// Renders light documents' images on the UI thread. static NAV_RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); + /// Renders the images with Draw Dashed Lines as Solid Lines on, on the thread that renders + /// them: each renderer draws every image it makes with one setting, so the art it keeps from + /// one image is drawn the same way in the next. + static SOLID_RENDERER: std::cell::RefCell = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } /// Map a document point into the thumbnail rect (region → rect, aspect preserved). @@ -157,7 +249,7 @@ pub fn thumb_to_doc(region: DRect, thumb: Rect, p: egui::Pos2) -> Point { Point::new(region.x0 + (p.x as f64 - ox) / s, region.y0 + (p.y as f64 - oy) / s) } -/// The red view box in the thumbnail: the corners of the canvas `canvas` showing view `v`, mapped +/// The view box in the thumbnail: the corners of the canvas `canvas` showing view `v`, mapped /// into the document (turned with the view) and then into the thumbnail, cut to the thumbnail /// grown by a point. Fewer than three points when the view is outside the thumbnail. fn view_box(region: DRect, thumb: Rect, canvas: Rect, v: &crate::state::View) -> Vec { @@ -215,7 +307,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.painter().rect_filled(thumb, 0.0, t.pasteboard); let ppp = ui.ctx().pixels_per_point(); let (pw, ph) = ((w * ppp) as u32, (h * ppp) as u32); - let key = ImageKey { uid, revision, w: pw, h: ph, artboard_only }; + let key = ImageKey { uid, revision, w: pw, h: ph, artboard_only, solid_dashes: app.ui.navigator_panel.solid_dashes }; let (tex, tex_region) = CACHE.with(|c| { let mut c = c.borrow_mut(); c.update(ui.ctx(), &doc, key, region, busy); @@ -240,7 +332,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if let (Some(v), Some(cr)) = (view, app.canvas_rect) { let box_points = view_box(region, thumb, cr, &v); if box_points.len() > 2 { - ui.painter().with_clip_rect(thumb).add(egui::Shape::closed_line(box_points, Stroke::new(1.5, Color32::from_rgb(0xff, 0x30, 0x30)))); + let color = app.ui.navigator_panel.view_box(); + ui.painter().with_clip_rect(thumb).add(egui::Shape::closed_line(box_points, Stroke::new(1.5, color))); } if (resp.dragged() || resp.clicked()) && let Some(p) = resp.interact_pointer_pos() @@ -278,12 +371,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); } -pub fn menu(_app: &mut VectorcraftApp, ui: &mut Ui) { +pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let ab: bool = pstate(ui.ctx(), "nav-ab-only"); if menu_item(ui, tl!("View Artboard Only"), true, ab) { set_pstate(ui.ctx(), "nav-ab-only", !ab); } - menu_item(ui, tl!("Panel Options…"), false, false); + if menu_item(ui, tl!("Panel Options…"), true, false) { + app.run("ui.navigatorPanelOptions", json!({})).ok(); + } } #[cfg(test)] @@ -354,6 +449,108 @@ mod tests { assert!(points.iter().zip(&want).all(|(a, b)| a.distance(*b) < 0.5), "{points:?} is not {want:?}"); } + /// The panel menu's Panel Options… is enabled, and a click opens the Navigator Panel Options. + #[test] + fn panel_options_opens_from_the_panel_menu() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + // Menu rows pad their label where a check mark would go. + assert!(!named(&tree(|ui| menu(&mut app, ui)), " Panel Options…").is_disabled()); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 400.0))); + let raw = |events| egui::RawInput { events, screen_rect: screen, ..Default::default() }; + let mut out = ctx.run_ui(raw(vec![]), |ui| menu(&mut app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().trim_start() == "Panel Options…" => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu item"); + let button = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ctx.run_ui(raw(vec![egui::Event::PointerMoved(item), button(true), button(false)]), |ui| menu(&mut app, ui)).textures_delta.clear(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::navigator_panel_options::KIND)); + } + + /// `ui.navigatorPanelOptions` sets the view box color and Draw Dashed Lines as Solid Lines: the + /// view box is drawn in that color (Light Red by default), and the thumbnail is made again with + /// the dashes left out. A value that is not a color, or not true or false, is refused and + /// changes nothing. + #[test] + fn panel_options_set_the_view_box_color_and_solid_dashes() { + use vectorcraft_engine::Session; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.canvas_rect = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(600.0, 400.0))); + app.run("view.setZoom", json!({"zoom": 400, "center": [200, 150]})).unwrap(); + let ctx = egui::Context::default(); + // The view boxes drawn in `color` in one frame. + let boxes = |app: &mut VectorcraftApp, color: Color32| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + let want = egui::epaint::ColorMode::Solid(color); + out.shapes.into_iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.closed && p.stroke.color == want)).count() + }; + let (red, blue) = (Color32::from_rgb(0xff, 0x30, 0x30), Color32::from_rgb(0x4f, 0x80, 0xff)); + assert_eq!((boxes(&mut app, red), boxes(&mut app, blue)), (1, 0), "Light Red by default"); + let shown = || CACHE.with(|c| c.borrow().shown.map(|(k, _)| k.solid_dashes)); + assert_eq!(shown(), Some(false)); + let set = app.run("ui.navigatorPanelOptions", json!({"color": "light blue", "solidDashes": true})).unwrap(); + assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true})); + assert_eq!((boxes(&mut app, red), boxes(&mut app, blue)), (0, 1)); + for _ in 0..12 { + boxes(&mut app, blue); + } + assert_eq!(shown(), Some(true), "the thumbnail is made again with solid dashes"); + let bad = [ + json!({"color": 12}), + json!({"color": "#zz0000"}), + json!({"color": "#ff000080"}), + json!({"color": "#f00"}), + json!({"color": null}), + json!({"color": "Red", "solidDashes": "yes"}), + ]; + for bad in bad { + assert!(app.run("ui.navigatorPanelOptions", bad.clone()).is_err(), "{bad}"); + } + assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), json!({"color": "#4f80ff", "solidDashes": true}), "nothing changed"); + app.run("ui.navigatorPanelOptions", json!({"color": "#123456"})).unwrap(); + assert!(app.ui.navigator_panel.solid_dashes, "an option left out keeps its value"); + } + + /// The thumbnail's render options drop a dashed stroke's dashes with Draw Dashed Lines as Solid + /// Lines, so it draws as the same stroke without dashes; without the option the dashes stay. + #[test] + fn the_thumbnail_draws_dashed_lines_as_solid_lines_with_the_option() { + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Node}; + let line = |dash: bool| { + let mut d = Document::new(100.0, 100.0); + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((10.0, 50.0)); + bp.line_to((90.0, 50.0)); + let id = d.alloc_id(); + let mut n = + Node::path(id, vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 6.0)); + n.appearance.stroke_mut().unwrap().dash = dash.then(|| vectorcraft_doc::Dash { pattern: vec![8.0, 8.0], ..Default::default() }); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d + }; + let key = ImageKey { uid: 1, revision: 1, w: 100, h: 100, artboard_only: false, solid_dashes: false }; + let draw = |d: &Document, key: ImageKey| { + vectorcraft_render::Renderer::new().render_region_with(d, DRect::new(0.0, 0.0, 100.0, 100.0), 1.0, &image_options(key)).pixels + }; + let solid = draw(&line(false), key); + assert_ne!(draw(&line(true), key), solid, "the dashes show without the option"); + let on = ImageKey { solid_dashes: true, ..key }; + assert!(image_options(on).solid_dashes && !image_options(key).solid_dashes); + assert_eq!(draw(&line(true), on), solid, "the dashes go with the option"); + assert_eq!(draw(&line(false), on), solid, "a solid stroke draws as it did"); + } + #[test] fn zoom_slider_roundtrip() { assert!((zoom_to_slider(3.13)).abs() < 1e-9); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 294b5bb4d2..84cf014c86 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -645,6 +645,9 @@ pub struct UiState { /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, + /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines). + #[serde(default)] + pub navigator_panel: crate::panels::navigator::PanelOptions, /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the /// Search All text does. #[serde(skip)] @@ -1007,6 +1010,7 @@ impl Default for UiState { home: None, trace_hold_source: None, layers_panel: Default::default(), + navigator_panel: Default::default(), layers_filter: Default::default(), image_trace_advanced: true, image_trace_preview: true, diff --git a/docs/mcp.md b/docs/mcp.md index 549b5f6b1c..837b0ad245 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1574,6 +1574,21 @@ enabled while the document has a saved view. In the desktop app the views are li checked when it opens: past 25, blank or repeated names, and views without a finite centre and a positive zoom are dropped. +## Navigator panel options + +The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), +and `ui.navigatorPanelOptions {color?, solidDashes?}` sets the options without it → `{color, solidDashes}`; with +neither key it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. +The presets are VectorCraft's own list: Light Red (`#ff3030`, the default), then the layer colors ("Light Blue", +"Red", "Green" and the rest). `solidDashes` (Draw Dashed Lines as Solid Lines, off by default) makes the panel's +thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. Both are kept +with the UI state. A `color` that is not a color, or a `solidDashes` that is not true or false, is an error and +changes neither option. Behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html). + +```json +{"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"color":"Light Blue","solidDashes":true}}} +``` + ## Ruler guides Ruler guides are numbered in the order they were made. `guide.add {vertical, pos, artboard?}` makes one (the x of a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1027fc25aa..ed036d189c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -845,6 +845,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Snap to Glyph options (#4232, [Snap to Glyph options](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph-options.html)): the Character panel menu's Show Snap to Glyph Options (Hide Snap to Glyph Options) shows a Snap to Glyph section in the panel, with or without type selected, with a checkbox for each kind of guide: Baseline, x-height, Glyph Bounds, Proximity Guides (the edges of each character's width), Angular Guides and Anchor Point. Each off takes its guides away and leaves the others (`view.snapToGlyph.options`, the `glyphSnap` preference group, all on by default). Angular Guides covers a glyph's slanted strokes and every guide of rotated type, which runs at its angle; the boxes are dimmed while View › Snap to Glyph is off (VectorCraft choices; the page settles neither). Tested in `crates/tools/src/guides/tests.rs`, `crates/ui-egui/src/panels/character/tests.rs` and `crates/engine/src/tests/prefs.rs`. - **Artboard click-to-fit (#1227):** a plain click fits the topmost editable object or group to a new artboard, including its stroke like Fit to Selected Art, and makes the new artboard active. Art and its selection stay unchanged; creation is one undo step. Handles, modified clicks, drags, Escape and tool changes retain their meaning. Tested inside an artboard and on the pasteboard (`crates/engine/tests/it/artboard_click.rs`); the public [CS6 Printing Guide](https://helpx.adobe.com/content/dam/help/en/indesign/pdf/CS6_PrintGuide.pdf) documents the object-click gesture. This legacy gesture adds evidence without regrading the 2026 canvas controls. - **Rotated views:** with the view rotated, Fit Artboard in Window, Fit All in Window and the status bar's artboard navigator fit the artboard or the art as the view turns it, and a Zoom tool marquee (Animated Zoom or GPU Performance off) zooms to the area dragged across. Ruler guides on no artboard turn with the view. The canvas draws the selection marquee where the tools select, Show Hidden Characters draws the marks of type partly inside the canvas, the Contextual Task Bar stays under the selection, and the Navigator's red box outlines what the window shows. +- **Navigator panel options:** the Navigator panel menu's Panel Options… sets the color the view box is drawn in, from a preset list (VectorCraft's own: Light Red, the default, then the layer colors) or a custom color, and Draw Dashed Lines as Solid Lines, off by default, which draws dashed strokes without their dashes in the panel's thumbnail only (`ui.navigatorPanelOptions`; kept with the UI state; behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). - **Views:** the status bar's artboard navigator (first, previous, next, last; `view.goToArtboard`) goes to an artboard, fits it and synchronizes the Artboard tool selection when that tool is active; ordinary object selection is preserved. Its four buttons are also commands of their own (`view.firstArtboard`, `view.previousArtboard`, `view.nextArtboard`, `view.lastArtboard`), listed in Edit › Keyboard Shortcuts without a default key, so a user can give them keys such as Page Up and Page Down (#5218). Actual Next-button regressions cover keyboard/Properties deletion and Undo in `chrome.rs`. Fit Artboard in Window and Actual Size show the navigator's artboard. The Artboards panel highlights that active artboard: clicking a row makes it active (the Artboard tool's too, while it is chosen) as does clicking an artboard with the Artboard tool, double-clicking its number also fits it in the window and double-clicking its name renames it. Duplicate Artboards, or a row dragged onto New Artboard, copies the artboard with its art (#446). Escape leaves Presentation Mode, `view.screenMode` from it goes back to Normal Screen Mode, and the screen mode isn't saved with the preferences: the app always starts in Normal Screen Mode with its menus and panels (#472). View › Pixel Preview shows the art as the document pixels it rasterizes to, one per point and hard-edged when magnified, turning with a rotated view (it used to draw the smooth vectors, with only the pixel grid over them). In Outline view a template layer keeps drawing in Preview, dimmed, so a picture placed to be traced stays visible under the outlines (#1505, fixes #1486). In Presentation Mode, → and ← go to the next and the previous artboard, and a click anywhere goes to the next one, as the status bar navigator's Next and Previous do (`view.goToArtboard`): on the last artboard → and a click leave the view as it is, and so does ← on the first. The arrow keys do not move the selection there, and the tool does not receive a click, so a click selects and draws nothing (behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). Full Screen Mode and Presentation Mode put the window full screen, covering the taskbar and the window's frame, and Normal Screen Mode or Full Screen Mode with Menu Bar puts it back (#4365); a window the user made full screen stays so. From ddf3373cf05b878153630f3fd834860c77df5f4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:17:35 -0800 Subject: [PATCH 040/482] Navigator: translate the Light Red view box preset Add a Light Red row next to Light Blue in all 26 catalogs, so the preset name in Panel Options shows in the interface language. --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 26 files changed, 26 insertions(+) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ed5017b230..4f7feb3ee0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1702,6 +1702,7 @@ font-technology Variable Променливи Ligatures are off while the text is tracked. Лигатурите са изключени, докато текстът е с проследяване. Light Светло Light Blue Светлосиньо + Light Red Светлочервено Lighten Изсветляване Lightness Светлина Limit Color Guide to Library Ограничаване на цветния справочник до библиотека diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0d0806fb1d..fa7f049f6c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2398,6 +2398,7 @@ digits Malayalam Malajalam “{file}” is protected by a password. „{file}” je zaštićen lozinkom. Dim Images to: Zatamni slike na: Light Blue Svijetloplava + Light Red Svijetlocrvena Layers Panel Options Opcije panela slojeva Row Size: Veličina reda: Show Layers Only Prikaži samo slojeve diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8f4fc17099..05d058dbcb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2166,6 +2166,7 @@ digits Malayalam Malaiàlam Light Clar Light behind the object Llum darrere de l’objecte Light Blue Blau clar + Light Red Vermell clar Light Direction Direcció de la llum Light Gray Gris clar Light Intensity Intensitat de la llum diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 5e63bd7359..03c6020b8d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2428,6 +2428,7 @@ digits Malayalam Malajálamské “{file}” is protected by a password. Soubor „{file}“ je chráněn heslem. Dim Images to: Ztlumit obrázky na: Light Blue Světle modrá + Light Red Světle červená Layers Panel Options Možnosti panelu Vrstvy Row Size: Velikost řádků: Show Layers Only Zobrazit pouze vrstvy diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7902408012..37cfc96474 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2216,6 +2216,7 @@ digits Malayalam Malayalam “{file}” is protected by a password. »{file}« er beskyttet med en adgangskode. Dim Images to: Nedton billeder til: Light Blue Lyseblå + Light Red Lys rød Layers Panel Options Indstillinger for lagpanelet Row Size: Rækkestørrelse: Show Layers Only Vis kun lag diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6494f51c95..9658d57295 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1764,6 +1764,7 @@ file-filter Templates Vorlagen Ligatures are off while the text is tracked. Ligaturen sind aus, solange für den Text eine Laufweite eingestellt ist. Light Hell Light Blue Hellblau + Light Red Hellrot Lighten Aufhellen Lightness Helligkeit Limit Color Guide to Library Farbhilfe auf Bibliothek beschränken diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index a1a7586409..eca62bdb96 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1652,6 +1652,7 @@ font-technology Variable Μεταβλητές Libraries Βιβλιοθήκες Light Ανοιχτό Light Blue Ανοιχτό μπλε + Light Red Ανοιχτό κόκκινο Lighten Φώτισμα Lightness Φωτεινότητα Line Γραμμή diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2b6207e904..e739c742c2 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1767,6 +1767,7 @@ font-technology Variable Variables Ligatures are off while the text is tracked. Las ligaduras se desactivan mientras el texto tiene espaciado. Light Claro Light Blue Azul claro + Light Red Rojo claro Lighten Aclarar Lightness Luminosidad Limit Color Guide to Library Limitar guía de color a la biblioteca diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 099ba3aabc..e277504979 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2372,6 +2372,7 @@ digits Malayalam Malajalam “{file}” is protected by a password. ”{file}” on suojattu salasanalla. Dim Images to: Himmennä kuvat: Light Blue Vaaleansininen + Light Red Vaalea punainen Layers Panel Options Tasot-paneelin asetukset Row Size: Rivin koko: Show Layers Only Näytä vain tasot diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d5135983e0..bac0097a6a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1761,6 +1761,7 @@ font-technology Variable Variables Ligatures are off while the text is tracked. Les ligatures sont désactivées tant qu’une approche est appliquée au texte. Light Clair Light Blue Bleu clair + Light Red Rouge clair Lighten Éclaircir Lightness Luminosité Limit Color Guide to Library Limiter le guide des couleurs à la bibliothèque diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c97cfd5f9b..225fa709f2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2223,6 +2223,7 @@ file-filter Templates Sablonok Ligatures are off while the text is tracked. Ha a szövegnek betűköze van, a ligatúrák ki vannak kapcsolva. Light Fény Light Blue Világoskék + Light Red Világospiros Light Direction Fény iránya Light Gray Világosszürke Light Intensity Fény erőssége diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index af2504c742..d0d09e8390 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2216,6 +2216,7 @@ digits Malayalam Malayalam “{file}” is protected by a password. “{file}” dilindungi kata sandi. Dim Images to: Redupkan gambar menjadi: Light Blue Biru muda + Light Red Merah terang Layers Panel Options Opsi panel lapisan Row Size: Ukuran baris: Show Layers Only Tampilkan lapisan saja diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ef5b0f3bd5..a4a7d547a0 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1796,6 +1796,7 @@ file-filter Templates Modelli Ligatures are off while the text is tracked. Le legature sono disattivate quando al testo è applicata una spaziatura caratteri. Light Chiaro Light Blue Azzurro + Light Red Rosso chiaro Lighten Schiarisci Lightness Luminosità Limit Color Guide to Library Limita guida colori alla libreria diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0a70417548..3d04b70ce5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3619,6 +3619,7 @@ file-filter Templates テンプレート Left-Justified Tab 左揃えタブ Letter レター Light Blue ライトブルー + Light Red ライトレッド Lightness 明度 Link リンク Low 低 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0071c0cd96..d0c69c179d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2119,6 +2119,7 @@ digits Malayalam მალაიალამური “{file}” is protected by a password. „{file}“ დაცულია პაროლით. Dim Images to: გამოსახულებების ჩაბნელება: Light Blue ღია ლურჯი + Light Red ღია წითელი Layers Panel Options შრეების პანელის პარამეტრები Row Size: სტრიქონის ზომა: Show Layers Only მხოლოდ შრეების ჩვენება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 335f3f61d0..926896ebb8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3607,6 +3607,7 @@ file-filter Templates 템플릿 Left-Justified Tab 왼쪽 정렬 탭 Letter 레터 Light Blue 연한 파랑 + Light Red 연한 빨강 Lightness 명도 Link 링크 Low 낮음 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a0bd063ec0..8e23b89e8d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2230,6 +2230,7 @@ digits Malayalam Malayalam “{file}” is protected by a password. „{file}” is beveiligd met een wachtwoord. Dim Images to: Afbeeldingen dimmen tot: Light Blue Lichtblauw + Light Red Lichtrood Layers Panel Options Opties voor het paneel Lagen Row Size: Rijgrootte: Show Layers Only Alleen lagen weergeven diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1859749883..6fd390d6d9 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2343,6 +2343,7 @@ digits Malayalam Malajalam “{file}” is protected by a password. Plik „{file}” jest chroniony hasłem. Dim Images to: Przyciemnij obrazy do: Light Blue Jasnoniebieski + Light Red Jasnoczerwony Layers Panel Options Opcje panelu Warstwy Row Size: Rozmiar wiersza: Show Layers Only Pokaż tylko warstwy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 6158558189..331edd6bc1 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4645,6 +4645,7 @@ axis Both Ambos Left-Justified Tab Parada de Tabulação à Esquerda Letter Carta Light Blue Azul Claro + Light Red Vermelho Claro Lightness Luminosidade Link Vincular Low Baixo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index b4cdb4da37..654e0a1435 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1793,6 +1793,7 @@ file-filter Templates Шаблоны Ligatures are off while the text is tracked. Лигатуры отключены, пока для текста задан трекинг. Light Светлый Light Blue Голубой + Light Red Светло-красный Lighten Замена светлым Lightness Светлота Limit Color Guide to Library Ограничить цветовой гид библиотекой diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 50c91f44ea..58a91b8884 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1708,6 +1708,7 @@ font-technology Variable Variabla Ligatures are off while the text is tracked. Ligaturer är avstängda när texten har spärrning. Light Ljus Light Blue Ljusblå + Light Red Ljusröd Lighten Ljusare Lightness Ljushet Limit Color Guide to Library Begränsa färgguiden till bibliotek diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 2e618b1032..5f41a51986 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1604,6 +1604,7 @@ font-technology Variable Değişken Ligatures are off while the text is tracked. Metin izlenirken bitişik harfler kapalıdır. Light Işık Light Blue Açık Mavi + Light Red Açık Kırmızı Lighten hafifletmek Lightness hafiflik Limit Color Guide to Library Renk Kılavuzunu Kitaplıkla Sınırlandır diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5d8e2f3b5b..ad511f3ed5 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1790,6 +1790,7 @@ file-filter Templates Шаблони Ligatures are off while the text is tracked. Лігатури вимкнено, поки для тексту заданий трекінг. Light Світлий Light Blue Блакитний + Light Red Світло-червоний Lighten Освітлення Lightness Світлота Limit Color Guide to Library Обмежити колірний гід бібліотекою diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index b0d51a9de9..fb24f7d044 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2051,6 +2051,7 @@ digits Hindi Hindi Ligatures are off while the text is tracked. Chữ ghép tắt khi văn bản được giãn chữ. Light Sáng Light Blue Xanh lam nhạt + Light Red Đỏ nhạt Light Direction Hướng ánh sáng Light Gray Xám nhạt Light Intensity Cường độ ánh sáng diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index f4446b27b1..bf2a49b374 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1679,6 +1679,7 @@ file-filter Templates 模板 Ligatures are off while the text is tracked. 设置字距时连字会关闭。 Light 浅色 Light Blue 浅蓝色 + Light Red 浅红色 Lighten 变亮 Lightness 亮度 Limit Color Guide to Library 将色彩参考限制于库 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9c28472149..5f48b43071 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2637,6 +2637,7 @@ file-filter Templates 範本 Ligatures are off while the text is tracked. 文字套用字距時,連字功能會關閉。 Light 淺色 Light Blue 淺藍色 + Light Red 淺紅色 Lighten 變亮 Lightness 亮度 Limit Color Guide to Library 將色彩參考限制於資料庫 From 6fa0d6e4e0b520e05518ca6b017ea4fc3e550ca5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:55:40 -0800 Subject: [PATCH 041/482] Navigator: cached raster effects follow Draw Dashed Lines as Solid Lines The raster-effect cache key now includes the setting, so a renderer that draws the same art with it on and then off no longer reuses a drop shadow or other raster effect made with the other setting. --- crates/render/src/fx/pixels.rs | 4 +++- crates/render/src/tests.rs | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 1f1b160ac7..a49817cd06 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -382,7 +382,7 @@ impl Renderer { } /// The inputs a raster of `n`'s content, which reads `reads`, is drawn with in frame `f`: the - /// color settings, the edge smoothing, the document's raster effects resolution (which a + /// color settings, the edge smoothing, whether dashed strokes draw as solid lines, the document's raster effects resolution (which a /// Rasterize or De-Interlace anywhere in the content follows), the knockout `n` inherits and, /// while `n` holds the isolated group, isolation mode; the pattern definitions, symbols and /// brush library it reads; for images and placed documents their pixels and files, the @@ -398,6 +398,8 @@ impl Renderer { (doc.cms, f.opts.anti_alias.threshold(), self.knockout, f.doc.raster_effects_ppi.to_bits()).hash(&mut h); // Cached effects on containers can include paths made into guides. f.opts.hide_guides.hash(&mut h); + // Cached effects can include dashed strokes drawn as solid lines. + f.opts.solid_dashes.hash(&mut h); if let Some((isolated, path)) = self.isolation_path(f) && n.id != isolated && path.contains(&n.id) diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2a6a4872d1..e171eecf6e 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -1321,6 +1321,12 @@ fn solid_dashes_draw_dashed_strokes_as_solid_lines() { assert_eq!(draw(&line(true, shadow), true).pixels, solid.pixels, "the dashes go with the option (shadow: {shadow})"); assert_eq!(draw(&line(false, shadow), true).pixels, solid.pixels, "a solid stroke is unchanged (shadow: {shadow})"); } + // One renderer that draws the shadow both ways makes its raster again for each setting. + let (dashed, mut r) = (line(true, true), Renderer::new()); + let fresh = |solid: bool| draw(&dashed, solid).pixels; + for solid in [false, true, false] { + assert_eq!(r.render(&dashed, 100, 100, Affine::IDENTITY, &opts(solid)).pixels, fresh(solid), "reused renderer, solid: {solid}"); + } } /// An image that can't be decoded is counted on the thread that tried to decode it: an export From a7266dd10a97faef50c460a9b63c9a0ef77b8234 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:29:44 -0800 Subject: [PATCH 042/482] Character: Kerning reads (10+5)*2 as nothing instead of 10+5*2 Numeric fields dropped every parenthesis before reading a value, so (10+5)*2 typed into a field committed 20. Only the Kerning field, which shows its automatic value as (12), now drops one pair of parentheses around the whole text. Parentheses anywhere else are refused, and fields without that display refuse them too. --- crates/ui-egui/src/widgets.rs | 26 +++++++++++++++++++++++++- crates/ui-egui/src/widgets/numeric.rs | 23 ++++++++++++++++------- 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 2e139d0131..c74a78a0f7 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -57,7 +57,7 @@ pub use numeric::{ spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning, spin_plain, spin_plain_named, }; #[cfg(test)] -use numeric::{decimal_point, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; +use numeric::{decimal_point, field_number, share_of, spinner_step, step_through, step_to_multiple, within_a_millionth}; pub use panel_chrome::{bottom_bar, layout_button, list_box, orientation_button, tab_bar}; pub(crate) use text::{ arm_field_focus, dialog_focus_flag, dialog_reject_commit_flag, disarm_field_focus, enter_modifiers, focus_field, own_field_shift_enter, @@ -464,6 +464,30 @@ mod decimal_point_tests { } } +#[cfg(test)] +mod field_number_tests { + use super::*; + + /// Kerning drops one pair of parentheses around its whole text, so its automatic value `(12)` + /// reads as 12. Parentheses inside the text are refused rather than dropped, which would read + /// `(10+5)*2` as `10+5*2`, and fields without the Kerning flag refuse parentheses too. + #[test] + fn only_kerning_drops_one_pair_of_parentheses_around_the_text() { + assert_eq!(field_number("(12)", "", true), Some(12.0)); + assert_eq!(field_number(" (-25) ", "", true), Some(-25.0)); + assert_eq!(field_number("(10+5)", "", true), Some(15.0)); + assert_eq!(field_number("12", "", true), Some(12.0)); + for text in ["(10+5)*2", "2*(10+5)", "(10)+(5)", "((12))", "(12", "12)"] { + assert_eq!(field_number(text, "", true), None, "{text}"); + } + for text in ["(12)", "(10+5)*2"] { + assert_eq!(field_number(text, "", false), None, "{text} without the Kerning flag"); + } + assert_eq!(field_number("45*2°", "°", false), Some(90.0)); + assert_eq!(field_number("50% / 2", "%", false), Some(25.0)); + } +} + #[cfg(test)] mod menu_room_tests { use super::*; diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 91cd18eebc..56ace75b85 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -454,13 +454,7 @@ fn bounded_field( let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); let show = |value: f64| field_text(value, suffix, decimals); - // The suffix (and %, °) may follow any operand: `45*2°`, `50% / 2`. - let read = |buf: &str| { - let suffix = suffix.trim(); - let buf = decimal_point(buf); - let bare = if suffix.is_empty() { buf.to_string() } else { buf.replace(suffix, "") }; - vectorcraft_doc::parse_number(&bare.replace(['%', '°', '(', ')'], "")) - }; + let read = |buf: &str| field_number(buf, suffix, parentheses); let shown = value.map(|v| if parentheses { format!("({})", show(v)) } else { show(v) }).unwrap_or_default(); take_dialog_focus(ui, id, &shown); if armed { @@ -491,6 +485,21 @@ fn bounded_field( } } +/// The number text typed into a [`bounded_field`] with `suffix` reads as. The suffix, `%` and `°` +/// may follow any operand: `45*2°`, `50% / 2`. With `parentheses` (Kerning, which shows its +/// automatic value as `(12)`), one pair of parentheses around the whole text is dropped first, so +/// `(12)` reads as 12. Any other parentheses are refused: `(10+5)*2` reads as nothing, not as +/// `10+5*2`. +pub(super) fn field_number(buf: &str, suffix: &str, parentheses: bool) -> Option { + let suffix = suffix.trim(); + let buf = decimal_point(buf); + let bare = if suffix.is_empty() { buf.to_string() } else { buf.replace(suffix, "") }; + let bare = bare.replace(['%', '°'], ""); + let bare = bare.trim(); + let bare = if parentheses { bare.strip_prefix('(').and_then(|b| b.strip_suffix(')')).unwrap_or(bare) } else { bare }; + vectorcraft_doc::parse_number(bare) +} + /// The text [`plain_field`] shows for `value`: at most `decimals` places, without trailing zeros, /// then `suffix`. pub(super) fn field_text(value: f64, suffix: &str, decimals: usize) -> String { From af14fe3d5904c4659b8891068fe0c46824583c9a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:19:23 -0800 Subject: [PATCH 043/482] Align Text Tweaker ranges to character boundaries --- crates/engine/src/cmd/addons/typetools.rs | 3 ++- crates/engine/src/cmd/addons/typetools/tests.rs | 10 ++++++++++ docs/mcp.md | 1 + 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/addons/typetools.rs b/crates/engine/src/cmd/addons/typetools.rs index 320dce6b9f..a478b8c00b 100644 --- a/crates/engine/src/cmd/addons/typetools.rs +++ b/crates/engine/src/cmd/addons/typetools.rs @@ -46,7 +46,7 @@ pub fn specs() -> Vec { "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, 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}", + "{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 )] @@ -97,6 +97,7 @@ fn text_tweaker(s: &mut Session, p: &Value) -> Result { for (id, a, b, _) in ranges { let t = text_ref(s, id)?; let text = t.plain_text(); + let (a, b) = (edit::floor_char(&text, a), edit::floor_char(&text, b)); let chars: Vec = text.char_indices().filter(|&(i, c)| (a..b).contains(&i) && !(skip && (c.is_whitespace() || c.is_control()))).map(|(i, _)| i).collect(); seen += chars.len(); diff --git a/crates/engine/src/cmd/addons/typetools/tests.rs b/crates/engine/src/cmd/addons/typetools/tests.rs index 6c56f67694..7f05cb823a 100644 --- a/crates/engine/src/cmd/addons/typetools/tests.rs +++ b/crates/engine/src/cmd/addons/typetools/tests.rs @@ -124,6 +124,16 @@ fn a_range_changes_only_its_characters() { assert_eq!(tracking, [0.0, 100.0, 200.0, 300.0, 0.0]); } +#[test] +fn a_range_inside_a_multibyte_character_uses_character_boundaries() { + let mut s = session(); + let id = text(&mut s, "éx"); + let out = s.execute(C, &json!({"id": id.0, "start": 1, "end": 2, "attribute": "tracking", "from": 100, "to": 300})).unwrap(); + assert_eq!(out["count"], 1); + let tracking: Vec = styles(&s, id).iter().map(|(_, st)| st.tracking).collect(); + assert_eq!(tracking, [100.0, 0.0]); +} + #[test] fn random_values_stay_in_range_and_repeat_with_the_seed() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 837b0ad245..6cfb9dd572 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6921,6 +6921,7 @@ type it is the size shown. It changes the range of `id` (`start`/`end` bytes), else all the text of the type objects in `ids`, else the text the Type tool has selected (at a caret: all of that object's text), else all the text of every selected type object; each object gets its own ramp, and at most 100000 characters change in one run. A run that changes nothing makes no step. +A `start` or `end` byte inside a character rounds down to that character's start. | Parameter | Values (default) | |---|---| From 7a3c09c05d66d0fcfbcea33d19cd6aaa8a5c3825 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:34:00 -0800 Subject: [PATCH 044/482] Keyboard Shortcuts: the backtick key's label ignores the next key's text on the web eframe's web build sends each key's text before its press. When several keys arrive in one frame, the editor paired the backtick press with the text typed by the key after it, so a shortcut on that key could show the next key's character. The editor now pairs each text with its press through `shortcuts::typing_presses`, which shortcut dispatch already uses, for both event orders. --- crates/ui-egui/src/shortcut_editor.rs | 30 ++++++++++++++++----------- crates/ui-egui/src/shortcuts.rs | 2 +- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 3b46710240..50026209e8 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -274,19 +274,18 @@ pub fn chord_from_event(key: Key, m: Modifiers) -> Option { ui_mirror!(fn backtick_store() -> Option); -/// Notes what the backtick key (left of 1) typed in `events`: the one-character text whose key, a -/// press of it without modifiers, comes right before it (egui-winit) or, when no press comes -/// before, right after it (eframe's web build with no text field focused). egui reports that key -/// as [`Key::Backtick`] on layouts where it types a character egui has no key for, such as `"` on -/// Turkish Q. +/// Notes what the backtick key (left of 1) typed in `events`: the last one-character text that +/// [`crate::shortcuts::typing_presses`] pairs with a press of that key without modifiers, whether +/// the press comes before its text (egui-winit) or after it (eframe's web build with no text field +/// focused). egui reports that key as [`Key::Backtick`] on layouts where it types a character egui +/// has no key for, such as `"` on Turkish Q. pub(crate) fn note_backtick_text(events: &[egui::Event]) { - let is_press = |e: Option<&egui::Event>| matches!(e, Some(egui::Event::Key { pressed: true, .. })); - let is_backtick = - |e: Option<&egui::Event>| matches!(e, Some(egui::Event::Key { key: Key::Backtick, pressed: true, modifiers, .. }) if modifiers.is_none()); - let typed = events.iter().enumerate().rev().find_map(|(j, e)| match e { - egui::Event::Text(t) if t.chars().count() == 1 && !t.chars().any(char::is_whitespace) => { - let before = j.checked_sub(1).and_then(|j| events.get(j)); - (is_backtick(before) || (!is_press(before) && is_backtick(events.get(j + 1)))).then(|| t.clone()) + let typed_by = crate::shortcuts::typing_presses(events); + let typed = events.iter().zip(typed_by).rev().find_map(|(e, by)| match (e, by.and_then(|k| events.get(k))) { + (egui::Event::Text(t), Some(egui::Event::Key { key: Key::Backtick, modifiers, .. })) + if modifiers.is_none() && t.chars().count() == 1 && !t.chars().any(char::is_whitespace) => + { + Some(t.clone()) } _ => None, }); @@ -1322,6 +1321,13 @@ mod tests { assert_eq!(backtick_text().as_deref(), Some("\"")); note_backtick_text(&[text("`"), press(Key::Backtick)]); assert_eq!(backtick_text(), None); + // Several keys typed in one frame on the web: each text goes with the press after it. + let web = [text("a"), press(Key::A), text("\""), press(Key::Backtick), text("b"), press(Key::B)]; + note_backtick_text(&web); + assert_eq!(backtick_text().as_deref(), Some("\"")); + note_backtick_text(&[text("`"), press(Key::Backtick)]); + note_backtick_text(&[press(Key::A), text("a"), press(Key::Backtick), text("\""), press(Key::B), text("b")]); + assert_eq!(backtick_text().as_deref(), Some("\"")); // Only the unshifted key types that character. assert_eq!(on_layout("Shift+~".into(), Some("\"")), "Shift+~"); assert_eq!(on_layout("Cmd+~".into(), Some("\"")), "Cmd+\""); diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index b551b758d2..f8aaf2dd2f 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -929,7 +929,7 @@ fn latin(text: &str, physical: Option) -> String { /// types at most one text. A text takes the press after it only when every later text in the same /// run of alternating texts and presses has a press after it too; otherwise the text after that /// press takes it as the press before it, and this text has none. -fn typing_presses(events: &[egui::Event]) -> Vec> { +pub(crate) fn typing_presses(events: &[egui::Event]) -> Vec> { let is_press = |k: usize| matches!(events.get(k), Some(egui::Event::Key { key, pressed: true, .. }) if !is_modifier(*key)); let is_text = |k: usize| matches!(events.get(k), Some(egui::Event::Text(_))); // Whether the run of alternating texts and presses that starts with the text at `j` ends From bc2af8df351ca027e9b430c71042c2fb96ea0e75 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:00:32 -0800 Subject: [PATCH 045/482] Appearance: the active row is matched in each selected object on its own Reduce to Basic Appearance and Add New Fill matched the Appearance panel's active row only when every selected object had an equal row. With three objects whose third had a different lower fill, the second object lost the match too: Reduce kept its top fill instead of the active one, and Add New Fill put the copy on top instead of above the active row. items_per_target now matches each object against the first one separately, so an object keeps the match whenever it has an equal row. --- crates/engine/src/cmd/appearance.rs | 20 +++++++++++--- crates/engine/src/tests/appearance.rs | 39 +++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 990a4d97de..5ba393f588 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -357,11 +357,23 @@ pub(crate) fn appearances_differ(d: &vectorcraft_doc::Document, ids: &[NodeId]) /// Indices `idx` of the first target's items (aligned with `aligned`) in each of `ids`: the first /// target's own, and in each other one the items equal to them there (see [`SharedStack`]), each -/// index on its own: one the targets don't share is left out of the others (never taken as the -/// same index there). Not aligned, or one target: the same indices in each. +/// index and each target on its own: an index a target doesn't share with the first is left out +/// of that target (never taken as the same index there), whatever the other targets have. Not +/// aligned, or one target: the same indices in each. pub(crate) fn items_per_target(d: &vectorcraft_doc::Document, ids: &[NodeId], idx: &[usize], aligned: bool) -> Vec> { - match shared_stack(d, ids).filter(|_| aligned) { - Some(sh) => (0..ids.len()).map(|k| if k == 0 { idx.to_vec() } else { idx.iter().filter_map(|i| sh.item_in(*i, k)).collect() }).collect(), + let aps: Option> = ids.iter().map(|id| d.node(*id).map(|n| &*n.appearance)).collect(); + match aps.filter(|aps| aligned && aps.len() >= 2) { + Some(aps) => aps + .iter() + .enumerate() + .map(|(k, ap)| match aps.first() { + Some(first) if k > 0 => { + let sh = SharedStack::of(&[*first, *ap]); + idx.iter().filter_map(|i| sh.item_in(*i, 1)).collect() + } + _ => idx.to_vec(), + }) + .collect(), None => vec![idx.to_vec(); ids.len()], } } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index a49bae19a3..284a809de2 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -463,6 +463,45 @@ fn reduce_to_basic_keeps_the_active_row_of_the_first_selected_object() { assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#0000ff"); } +/// Three objects with equal stacks, the third's lower fill changed; the lower, green fill row of +/// the first is active, selected a, b, c. +fn three_with_one_changed(s: &mut Session) -> [NodeId; 3] { + let ids = [rect(s, 50.0), rect(s, 200.0), rect(s, 300.0)]; + run(s, "select.set", json!({"ids": ids.map(|id| id.0)})); + run(s, "appearance.addFill", json!({})); + run(s, "appearance.setItem", json!({"index": 0, "color": "#00ff00"})); + run(s, "appearance.setItem", json!({"index": 2, "color": "#ff0000"})); // [Fill green, Stroke, Fill red] + run(s, "appearance.setItem", json!({"index": 0, "color": "#0000ff", "ids": [ids[2].0]})); + run(s, "appearance.setActiveItem", json!({"index": 0})); + ids +} + +/// The active row is matched in each other object on its own: one object without an equal row +/// does not stop another that has one from keeping it. +#[test] +fn reduce_to_basic_keeps_the_active_row_in_each_object_that_has_it() { + let mut s = session(); + let [a, b, c] = three_with_one_changed(&mut s); + run(&mut s, "appearance.reduceToBasic", json!({})); + assert_eq!(fill_paint(&node(&s, a), 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(fill_paint(&node(&s, b), 0).color().unwrap().to_hex(), "#00ff00"); + assert_eq!(fill_paint(&node(&s, c), 0).color().unwrap().to_hex(), "#ff0000"); +} + +/// Add New Fill puts its copy of the active row right above that row in each object that has an +/// equal row, even when another selected object has none. +#[test] +fn add_fill_copies_the_active_row_in_each_object_that_has_it() { + let mut s = session(); + let [a, b, _] = three_with_one_changed(&mut s); + run(&mut s, "appearance.addFill", json!({})); + for id in [a, b] { + let n = node(&s, id); + assert_eq!(fill_paint(&n, 1).color().unwrap().to_hex(), "#00ff00", "{:?}", n.appearance); + assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#ff0000", "{:?}", n.appearance); + } +} + /// b `[Fill red, Fill white, Stroke]` above a `[Fill white, Stroke]`, selected b first: b's rows 1 /// and 2 equal a's rows 0 and 1. fn reversed_pair(s: &mut Session) -> (NodeId, NodeId) { From 95b3fbfec956f8047d512faa103c86b966cefc03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:03:37 -0800 Subject: [PATCH 046/482] Type: the font warning leaves out characters Missing Glyph Protection kept text.setStyle and text.setRangeStyle collected the fonts for their warning after Missing Glyph Protection had run. A character the new font has no glyph for keeps its earlier font, and when that font was not available the warning named it, although the command did not set it. protect_missing_glyphs now returns the byte ranges that kept their font, and both commands leave those ranges out of the warning's fonts. --- crates/engine/src/cmd/textedit.rs | 37 +++++++++++++++++++++++++------ crates/engine/src/cmd/typecmd.rs | 12 +++++----- crates/engine/src/tests/prefs.rs | 23 +++++++++++++++++++ 3 files changed, 59 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 03943029ea..6406fcf5b7 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -930,8 +930,8 @@ impl CharChange { /// Type › Enable Missing Glyph Protection: after a font change, the characters of `runs` their new /// font has no glyph for, but their font `before` the change had, keep that font: its family, -/// style, version and Variable Font settings. -pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec) { +/// style, version and Variable Font settings. Returns the byte ranges that kept their font, in order. +pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec) -> Vec<(usize, usize)> { fn chars(runs: &[TextRun]) -> impl Iterator { runs.iter() .scan(0, |at, r| { @@ -963,6 +963,7 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec _ => keep.push((at, end, old)), } } + let kept = keep.iter().map(|(a, b, _)| (*a, *b)).collect(); for (a, b, old) in keep { edit::style_range(runs, a, b, |st| { st.font_family.clone_from(&old.font_family); @@ -971,6 +972,30 @@ pub(crate) fn protect_missing_glyphs(before: &[TextRun], runs: &mut Vec st.font_axes.clone_from(&old.font_axes); }); } + kept +} + +/// The runs of `runs` from byte `a` to `b`, leaving out the ranges `kept` (in order) that Missing +/// Glyph Protection gave their earlier font: the characters a font command set its font on. +pub(crate) fn unprotected_runs(runs: &[TextRun], a: usize, b: usize, kept: &[(usize, usize)]) -> Vec { + let mut out = vec![]; + let mut at = a; + for &(k0, k1) in kept { + if k1 <= at { + continue; + } + if k0 >= b { + break; + } + if k0 > at { + out.extend(edit::slice_runs(runs, at, k0)); + } + at = k1; + } + if at < b { + out.extend(edit::slice_runs(runs, at, b)); + } + out } fn set_range_style(s: &mut Session, p: &Value) -> Result { @@ -1021,12 +1046,10 @@ fn set_range_style(s: &mut Session, p: &Value) -> Result { } let before = protect.then(|| t.runs.clone()); edit::style_range(&mut t.runs, a, b, |st| change.apply(st)); - if let Some(before) = before { - protect_missing_glyphs(&before, &mut t.runs); - } + let kept = before.map(|before| protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default(); if sets_font { - // Empty text has one run, which the empty range styles. - let styled = if a == b { t.runs.clone() } else { edit::slice_runs(&t.runs, a, b) }; + // Empty text has one run, which the empty range styles. Characters that kept their font aren't the command's. + let styled = if a == b { t.runs.clone() } else { unprotected_runs(&t.runs, a, b, &kept) }; set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); } refresh_bounds(t); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index d4a58c34d3..a24be32523 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -874,16 +874,16 @@ fn set_style(s: &mut Session, p: &Value) -> Result { st.features = super::textedit::change_features(&st.features, c); } }); - if let Some(before) = before { - super::textedit::protect_missing_glyphs(&before, &mut t.runs); - } + let kept = before.map(|before| super::textedit::protect_missing_glyphs(&before, &mut t.runs)).unwrap_or_default(); if font.is_some() || style.is_some() { - // All the text: every run, the one run of empty text included. + // All the text: every run, the one run of empty text included. Characters that kept their font aren't the + // command's. let styled = match range { - None => t.runs.clone(), + None if kept.is_empty() => t.runs.clone(), + None => super::textedit::unprotected_runs(&t.runs, 0, vectorcraft_text::edit::runs_len(&t.runs), &kept), Some(r) => { let (a, b) = r.bytes(t); - vectorcraft_text::edit::slice_runs(&t.runs, a, b) + super::textedit::unprotected_runs(&t.runs, a, b, &kept) } }; set.extend(styled.iter().map(|r| super::fonts::font_of(&r.style))); diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index b590e3c289..87b943d6c1 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -1474,6 +1474,29 @@ fn missing_glyph_protection_keeps_the_version_of_the_font_kept() { assert_eq!(versions, [moved.clone(), kept, moved]); } +/// The font warning of `text.setStyle` and `text.setRangeStyle` names only the fonts the command +/// set: a character that keeps an unavailable font through Missing Glyph Protection isn't reported. +#[test] +fn missing_glyph_protection_leaves_the_font_kept_out_of_the_warning() { + let (from, to, c) = ("No Such Font Family", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + // The unavailable family is drawn in the fallback font, which has the character; the new font is installed and lacks it. + let installed = db.resolve(to, "Regular").is_some_and(|(_, m)| m == vectorcraft_text::FontMatch::Exact); + if !installed || !db.face(from, "Regular").is_some_and(|f| f.covers(c)) || db.face(to, "Regular").is_some_and(|f| f.covers(c)) { + return; // The fonts installed here cover other characters. + } + let mut s = new_doc(); + let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + for change in [json!({"font": to}), json!({"id": id.0, "start": 0, "end": 4, "font": to})] { + let cmd = if change.get("id").is_some() { "text.setRangeStyle" } else { "text.setStyle" }; + let out = s.execute(cmd, &change).unwrap(); + assert_eq!(style_at(&s, id, 1).font_family, from, "{cmd}: the character keeps its font"); + assert_eq!(out.get("warning"), None, "{cmd}: {out}"); + s.execute("edit.undo", &json!({})).unwrap(); + } +} + // ---------- #394, fourth batch ---------- /// Type › Type Object Selection by Path Only (#394): on, a click among point type's glyphs no From a3aae55ceb6db3ac7481fe07e11d41de61a01f22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:06:22 -0800 Subject: [PATCH 047/482] Docs: list PDF spot gradients written as images in process colors PDF export writes a dithered gradient fill with spot stops, and a Perceptual spot gradient with RGB or Lab stops other than white or more than 4,096 stops on its curve, as an image in process colors. Add these cases to the M3 roadmap rows and the color area's remaining work, and correct the evidence line that said every Perceptual spot gradient becomes an image. --- docs/roadmap.md | 4 ++-- docs/target-app-parity.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index d4bf3859c7..c75e857b0c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -99,10 +99,10 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537); no View submenu | 12–18 | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M2 | Drawing tools + smart guides | ✅ mostly done (Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending) | 12–18 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish | 3–6 (existing scope; Affinity export unestimated) | -| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; confirm the Scale Strokes & Effects default | 4–8 | +| M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs, OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; tab leaders, spell check, vertical type pending | 45–60 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ed036d189c..534aff2069 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -141,7 +141,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, and PDF gradients mixing a spot color with RGB or Lab stops | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | | Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (four generated libraries, User Defined, Other Library…, Save Brushes); remaining: Art brush Overlap, Pattern brush auto corners, pen pressure on macOS, tilt/bearing/rotation | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, 3D Classic, Turntable views, 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12) | @@ -409,7 +409,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of similar groups, transform nuances (the rotated persistent bounding box is done) | 4–6 | | Drawing tools | 7 | 86% | rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | -| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | +| Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | | Strokes, brushes, width profiles | 5 | 90% | the Art brush's Overlap, auto-generated Pattern brush corners and new tile art in Pattern Brush Options (Brush Options for every brush type done), more built-in brush libraries (four generated in code are done), pen pressure on macOS (the windowing layer reports none there), brushes driven by pen tilt, bearing and barrel rotation (6D art pens) | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | @@ -1120,7 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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. - 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, and a gradient with the Perceptual method is written as an image, without the spot ink. 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 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). 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). From 5626a1614c65279384524a36b470b44380ed3a0b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:31:58 -0800 Subject: [PATCH 048/482] Gradient: method help names the PDF Separation and DeviceN shadings The `method` text of `paint.editGradient` and the Method paragraph in docs/mcp.md said SVG and PDF exports draw a Perceptual gradient as an image. PDF writes an eligible one natively: tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading. Gradients without spot stops, with RGB or Lab stops, dithered fills and curves with too many stops still become images there. Both texts now say so. --- crates/engine/src/cmd/gradient.rs | 2 +- docs/mcp.md | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 52daa9b747..b2996aa72a 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even, which SVG and PDF exports draw as an image, except that PDF writes one with spot color stops in its inks when every other stop is paper white, CMYK or gray; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), diff --git a/docs/mcp.md b/docs/mcp.md index 6cfb9dd572..ea6d1dd371 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -918,8 +918,11 @@ SVG and PDF exports write such a fill as an image at the Document Raster Effects ``` Method (the Gradient panel's menu): `classic` (the default) mixes the colours between stops in display RGB, -`perceptual` mixes a linear or radial gradient's colours in OKLab so the steps look even. SVG and PDF exports write a +`perceptual` mixes a linear or radial gradient's colours in OKLab so the steps look even. SVG exports write a Perceptual gradient as an image at the Document Raster Effects resolution (a dithered Perceptual fill with its noise). +PDF exports write it the same way, except for a gradient with spot color stops whose other stops are all paper white, +CMYK or gray, that is not a dithered fill and whose curve does not have too many stops. PDF writes tints of one spot +ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading. `paint.setFill`/`paint.setStroke` take it in `gradient` too: ```json From db468928d4e291983e70452a9d1c3a7827a70da0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:44:21 -0800 Subject: [PATCH 049/482] Appearance: Add New Fill copies the whole active fill row With a fill row active, Add New Fill copied only the row's paint and reset its opacity, blend mode, visibility, overprint and effects. The new row is now a copy of the whole active row, as the command's description says. --- crates/engine/src/cmd/appearance.rs | 4 ++-- crates/engine/src/tests/appearance.rs | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 5ba393f588..4531f22cde 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -551,9 +551,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { for (id, row) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { if let Some(i) = n.appearance.item_of_kind(*row, true) - && let Some(paint) = n.appearance.paint_at(Some(i), true).cloned() + && let Some(row) = n.appearance.fill_at(Some(i)).cloned() { - n.appearance.insert_item(i + 1, AppearanceItem::Fill(FillLayer::new(paint))); + n.appearance.insert_item(i + 1, AppearanceItem::Fill(row)); if active == Some(*id) { above = Some(i + 1); } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 284a809de2..c07fc8eb7f 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -323,6 +323,28 @@ fn add_fill_copies_the_active_fill_row_right_above_it() { assert_eq!(s.appearance_item(), Some(0)); } +/// The copy of the active fill row keeps the row's opacity, blend mode, visibility, overprint and +/// effects as well as its paint. +#[test] +fn add_fill_copies_the_whole_active_fill_row() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "appearance.setItem", json!({"index": 0, "opacity": 40, "blend": "multiply", "visible": false})); + run(&mut s, "effect.apply", json!({"effect": "distort.roughen", "item": 0})); + run(&mut s, "object.setOverprint", json!({"fill": true, "item": 0})); + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.addFill", json!({})); + let n = node(&s, id); + assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::>(), ["fill", "fill", "stroke"]); + let (AppearanceItem::Fill(row), AppearanceItem::Fill(copy)) = (&n.appearance.items[0], &n.appearance.items[1]) else { + panic!("the first two rows are not fills") + }; + assert_eq!((copy.opacity, copy.blend, copy.visible, copy.overprint), (0.4, BlendMode::Multiply, false, true)); + assert_eq!(copy.effects.len(), 1); + assert_eq!(copy, row); +} + /// In a mixed selection the active fill row goes above itself in the first object; an object that /// doesn't share that row gets a copy of its top fill on top, as without an active row. #[test] From 27fc8552468c7e1095233fe69be35ca875ad9132 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:22:04 -0800 Subject: [PATCH 050/482] Appearance: Add New Fill takes the active row's paint, as before Add New Fill again copies only the active fill row's paint; Duplicate Item copies a whole row. The params text of appearance.addFill and appearance.addStroke now says the new fill or stroke takes the paint (and for a stroke, the weight) of the row it starts from, and a test pins the paint-only copy. --- crates/engine/src/cmd/appearance.rs | 12 ++++++------ crates/engine/src/tests/appearance.rs | 20 ++++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 4531f22cde..27f5aee810 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row (a copy of its top fill; type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill is a copy of that row, right above it, and becomes the active row", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row", has_doc, |s, p| add_item(s, p, true) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row (a copy of its top stroke, else the default stroke)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint and weight (else the default stroke)", has_doc, |s, p| add_item(s, p, false) ), @@ -519,8 +519,8 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; let defaults = s.paint.clone(); - // The panel's active Fill row, when the new fill goes on the selection: the new fill is a copy - // of that row, right above it in each target that has it (others get a copy of their top fill). + // The panel's active Fill row, when the new fill goes on the selection: the new fill takes that + // row's paint, right above it in each target that has it (others take their top fill's paint). // Where the new item went in on the active item's object, when it is an image. let active = s.active_appearance_item.as_ref().and_then(|a| a.objects.first().copied()); // The active row is a row of the active object's stack, which need not come first in `ids` @@ -551,9 +551,9 @@ fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { for (id, row) in ids.iter().zip(&per) { if let Some(n) = d.node_mut(*id) { if let Some(i) = n.appearance.item_of_kind(*row, true) - && let Some(row) = n.appearance.fill_at(Some(i)).cloned() + && let Some(paint) = n.appearance.paint_at(Some(i), true).cloned() { - n.appearance.insert_item(i + 1, AppearanceItem::Fill(row)); + n.appearance.insert_item(i + 1, AppearanceItem::Fill(FillLayer::new(paint))); if active == Some(*id) { above = Some(i + 1); } diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index c07fc8eb7f..4fea39bdfb 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, GradientKind, Paint}; -use vectorcraft_doc::{AppearanceItem, Node}; +use vectorcraft_doc::{AppearanceItem, FillLayer, Node}; use crate::*; @@ -288,8 +288,8 @@ fn add_fill_and_stroke_copy_the_top_ones() { assert_eq!(node(&s, id).appearance.items.len(), 3); } -/// With a fill row active, Add New Fill puts a copy of that row right above it and makes the copy -/// the active row; the rows above it stay where they are. +/// With a fill row active, Add New Fill puts a fill with that row's paint right above it and makes +/// the new fill the active row; the rows above it stay where they are. #[test] fn add_fill_copies_the_active_fill_row_right_above_it() { let mut s = session(); @@ -323,10 +323,10 @@ fn add_fill_copies_the_active_fill_row_right_above_it() { assert_eq!(s.appearance_item(), Some(0)); } -/// The copy of the active fill row keeps the row's opacity, blend mode, visibility, overprint and -/// effects as well as its paint. +/// The new fill above the active fill row takes only the row's paint: the row's opacity, blend +/// mode, visibility, overprint and effects are not copied (Duplicate Item copies those). #[test] -fn add_fill_copies_the_whole_active_fill_row() { +fn add_fill_takes_only_the_active_fill_rows_paint() { let mut s = session(); let id = rect(&mut s, 100.0); run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); @@ -340,13 +340,13 @@ fn add_fill_copies_the_whole_active_fill_row() { let (AppearanceItem::Fill(row), AppearanceItem::Fill(copy)) = (&n.appearance.items[0], &n.appearance.items[1]) else { panic!("the first two rows are not fills") }; - assert_eq!((copy.opacity, copy.blend, copy.visible, copy.overprint), (0.4, BlendMode::Multiply, false, true)); - assert_eq!(copy.effects.len(), 1); - assert_eq!(copy, row); + assert_eq!((row.opacity, row.blend, row.visible, row.overprint), (0.4, BlendMode::Multiply, false, true)); + assert_eq!(row.effects.len(), 1); + assert_eq!(copy, &FillLayer::new(row.paint.clone())); } /// In a mixed selection the active fill row goes above itself in the first object; an object that -/// doesn't share that row gets a copy of its top fill on top, as without an active row. +/// doesn't share that row gets a fill with its top fill's paint on top, as without an active row. #[test] fn add_fill_above_an_unshared_active_row_tops_the_other_objects() { let mut s = session(); From d9499bc0a38ef819335eece34153a85bf2ba506e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 3 Nov 2026 16:56:24 -0800 Subject: [PATCH 051/482] Handle font wheel input in native viewports --- crates/ui-egui/src/doc_windows.rs | 12 +- crates/ui-egui/src/font_menu.rs | 80 ++++- crates/ui-egui/src/panel_docking.rs | 11 +- .../ui-egui/src/panel_docking/native_tests.rs | 293 +++++++++++++++++- 4 files changed, 384 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index d1984536fe..2f620a7dfa 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -677,18 +677,22 @@ mod input { "vectorcraft document windows input" } - fn input_hook(&mut self, _: &egui::Context, input: &mut egui::RawInput) { - if let Some(hook) = self.hook.as_ref().filter(|_| self.windows.contains(&input.viewport_id)) { - hook(input); + fn input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) { + if self.windows.contains(&input.viewport_id) { + if let Some(hook) = &self.hook { + hook(input); + } + crate::font_menu::take_raw_wheel(ctx, input); } } } /// Run `hook` on the input of `windows` from their next frame on. pub(super) fn register(ctx: &egui::Context, hook: Option, windows: HashSet) { - if hook.is_none() && ctx.with_plugin(|_: &mut DocumentWindowInput| ()).is_none() { + if windows.is_empty() && ctx.with_plugin(|_: &mut DocumentWindowInput| ()).is_none() { return; } + crate::font_menu::ensure_native_wheel_layers(ctx); ctx.add_plugin(DocumentWindowInput::default()); ctx.with_plugin(|p: &mut DocumentWindowInput| { p.hook = hook; diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 7366cc1a37..5fbca5a2e9 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -447,6 +447,57 @@ struct WheelFields { pending: HashMap>, } +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone)] +struct WheelLayers(Arc Option + Send + Sync>); + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Default)] +struct WheelLayerSnapshot; + +#[cfg(not(target_arch = "wasm32"))] +impl egui::Plugin for WheelLayerSnapshot { + fn debug_name(&self) -> &'static str { + "font wheel viewport layers" + } + + fn on_end_pass(&mut self, ui: &mut Ui) { + let ctx = ui.ctx(); + let viewport = ctx.viewport_id(); + if viewport == egui::ViewportId::ROOT || ctx.data(|d| d.get_temp::(wheel_fields_id(viewport))).is_none() { + return; + } + let current_layers = ctx.viewport(|viewport| { + viewport.this_pass.widgets.layers().filter_map(|(layer, widgets)| (!widgets.is_empty()).then_some(*layer)).collect::>() + }); + let layers = ctx.memory(|m| { + m.layer_ids() + .filter(|layer| current_layers.contains(layer)) + .filter(|layer| m.areas().is_visible(layer)) + .filter_map(|layer| m.area_rect(layer.id).map(|rect| (layer, rect))) + .collect::>() + }); + let layers = layers + .into_iter() + .filter(|(layer, _)| egui::AreaState::load(ctx, layer.id).is_some_and(|state| state.interactable)) + .map(|(layer, rect)| (layer, ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect))) + .collect::>(); + ctx.data_mut(|d| { + d.insert_temp( + wheel_fields_id(viewport).with("layers"), + WheelLayers(Arc::new(move |p| layers.iter().rev().find(|(_, rect)| rect.contains(p)).map(|(layer, _)| *layer))), + ) + }); + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn ensure_native_wheel_layers(ctx: &egui::Context) { + if ctx.with_plugin(|_: &mut WheelLayerSnapshot| ()).is_none() { + ctx.add_plugin(WheelLayerSnapshot); + } +} + fn wheel_fields_id(viewport: egui::ViewportId) -> egui::Id { egui::Id::unique("font-wheel-fields").with(viewport) } @@ -535,6 +586,10 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { let Some(mut fields) = ctx.data(|d| d.get_temp::(key)) else { return }; if !ctx.input(|i| i.raw.viewports.contains_key(&raw.viewport_id)) { ctx.data_mut(|d| d.remove::(key)); + #[cfg(not(target_arch = "wasm32"))] + ctx.data_mut(|d| { + d.remove::(key.with("layers")); + }); return; } let frame = ctx.cumulative_frame_nr_for(raw.viewport_id); @@ -548,9 +603,28 @@ pub(crate) fn take_raw_wheel(ctx: &egui::Context, raw: &mut egui::RawInput) { fields.pending.clear(); } let line = ctx.options(|o| o.input_options.line_scroll_speed).max(1.0); - let mut pointer = fields.pointer.or_else(|| ctx.input(|i| i.pointer.latest_pos())); - let over = - |field: &WheelField, point: Option| point.is_some_and(|p| field.rect.contains(p) && ctx.layer_id_at(p) == Some(field.layer)); + let mut pointer = fields.pointer.or_else(|| ctx.input_for(raw.viewport_id, |i| i.pointer.latest_pos())); + #[cfg(not(target_arch = "wasm32"))] + let native_layers = ctx.data(|d| d.get_temp::(key.with("layers"))); + let over = |field: &WheelField, point: Option| { + point.is_some_and(|p| { + if !field.rect.contains(p) { + return false; + } + if ctx.viewport_id() == raw.viewport_id { + ctx.layer_id_at(p) == Some(field.layer) + } else { + #[cfg(not(target_arch = "wasm32"))] + { + native_layers.as_ref().is_some_and(|layers| (layers.0)(p) == Some(field.layer)) + } + #[cfg(target_arch = "wasm32")] + { + false + } + } + }) + }; // An activation batch belongs to the popup, including a release after a prior press. if fields.activation_pass != pass { fields.activation_pass = pass; diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0deb2c3c0e..cc177a4de1 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1123,8 +1123,15 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) { .input_blocked(modal) .auto_collapse_iconic(app.session.prefs.auto_collapse_icon_panels); #[cfg(not(target_arch = "wasm32"))] - if let Some(hook) = app.services.native_input_hook.clone() { - dock = dock.native_input_hook(move |_, raw| hook(raw)); + { + crate::font_menu::ensure_native_wheel_layers(ui.ctx()); + let hook = app.services.native_input_hook.clone(); + dock = dock.native_input_hook(move |ctx, raw| { + if let Some(hook) = &hook { + hook(raw); + } + crate::font_menu::take_raw_wheel(ctx, raw); + }); } // Tab and Shift+Tab (`window.dock`, `window.panels`) and the full screen modes hide the panels; // the canvas stays. diff --git a/crates/ui-egui/src/panel_docking/native_tests.rs b/crates/ui-egui/src/panel_docking/native_tests.rs index 61eb0e2f2b..77e3d08bc6 100644 --- a/crates/ui-egui/src/panel_docking/native_tests.rs +++ b/crates/ui-egui/src/panel_docking/native_tests.rs @@ -29,6 +29,11 @@ struct Window { struct Host { windows: HashMap, + child_overlay: Option<(ViewportId, Rect)>, + child_transparent_overlay: Option<(ViewportId, Rect)>, + child_transition_overlay: Option<(ViewportId, Rect, bool)>, + child_empty_overlay: Option<(ViewportId, Rect)>, + child_pass_through_overlay: Option<(ViewportId, Rect)>, /// The window with the keyboard. focus: ViewportId, time: f64, @@ -87,7 +92,54 @@ impl Host { ..Default::default() } }; - let mut full = ctx.run_ui(input, |ui| (viewport.viewport_ui_cb)(ui)); + let child_overlay = host.borrow().child_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); + let child_transparent_overlay = host.borrow().child_transparent_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); + let child_transition_overlay = + host.borrow().child_transition_overlay.filter(|(viewport, _, _)| *viewport == id).map(|(_, rect, painted)| (rect, painted)); + let child_empty_overlay = host.borrow().child_empty_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); + let child_pass_through_overlay = host.borrow().child_pass_through_overlay.filter(|(viewport, _)| *viewport == id).map(|(_, rect)| rect); + let mut full = ctx.run_ui(input, |ui| { + (viewport.viewport_ui_cb)(ui); + if let Some(rect) = child_overlay { + egui::Window::new("Child overlay").fixed_pos(rect.min).fixed_size(rect.size()).show(ui.ctx(), |ui| { + ui.label("Child overlay"); + }); + } + if let Some(rect) = child_transparent_overlay { + egui::Area::new(egui::Id::unique("Child transparent overlay")).order(egui::Order::Foreground).fixed_pos(rect.min).show( + ui.ctx(), + |ui| { + ui.allocate_space(rect.size()); + }, + ); + } + if let Some((rect, painted)) = child_transition_overlay { + egui::Area::new(egui::Id::unique("Child transition overlay")).order(egui::Order::Foreground).fixed_pos(rect.min).show( + ui.ctx(), + |ui| { + ui.allocate_space(rect.size()); + if painted { + ui.label("Child transition overlay"); + } + }, + ); + } + if let Some(rect) = child_empty_overlay { + egui::Area::new(egui::Id::unique("Child empty overlay")).order(egui::Order::Foreground).fixed_pos(rect.min).show(ui.ctx(), |ui| { + ui.set_min_size(rect.size()); + }); + } + if let Some(rect) = child_pass_through_overlay { + egui::Area::new(egui::Id::unique("Child pass-through overlay")) + .order(egui::Order::Foreground) + .fixed_pos(rect.min) + .interactable(false) + .show(ui.ctx(), |ui| { + let (paint, _) = ui.allocate_exact_size(rect.size(), egui::Sense::hover()); + ui.painter().rect_filled(paint, 0.0, egui::Color32::TRANSPARENT); + }); + } + }); full.textures_delta.clear(); fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) { match s { @@ -110,18 +162,29 @@ struct Harness { app: VectorcraftApp, ctx: egui::Context, host: Rc>, + root_overlay: Option, } impl Harness { fn new() -> Self { - let host = Rc::new(RefCell::new(Host { windows: HashMap::new(), focus: ViewportId::ROOT, time: 0.0, commands: Vec::new() })); + let host = Rc::new(RefCell::new(Host { + windows: HashMap::new(), + child_overlay: None, + child_transparent_overlay: None, + child_transition_overlay: None, + child_empty_overlay: None, + child_pass_through_overlay: None, + focus: ViewportId::ROOT, + time: 0.0, + commands: Vec::new(), + })); let shared = host.clone(); egui::Context::set_immediate_viewport_renderer(move |ctx, viewport| Host::render(&shared, ctx, viewport)); let ctx = egui::Context::default(); ctx.set_embed_viewports(false); let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); - let mut h = Self { app, ctx, host }; + let mut h = Self { app, ctx, host, root_overlay: None }; h.frames(3); h } @@ -135,9 +198,15 @@ impl Harness { let mut input = egui::RawInput { time: Some(time), events, screen_rect: Some(SCREEN), viewports, focused, ..Default::default() }; self.app.raw_input_hook(&self.ctx, &mut input); let app = &mut self.app; + let root_overlay = self.root_overlay; let mut full = self.ctx.run_ui(input, |ui| { app.logic(ui.ctx()); app.ui(ui); + if let Some(rect) = root_overlay { + egui::Window::new("Root overlay").fixed_pos(rect.min).fixed_size(rect.size()).show(ui.ctx(), |ui| { + ui.label("Root overlay"); + }); + } }); full.textures_delta.clear(); self.host.borrow_mut().apply(&full); @@ -399,3 +468,221 @@ fn ui_docking_leaves_out_the_controls_of_os_windows() { assert!(!hits.iter().any(swatches), "none of the OS window's: {hits:?}"); assert!(report["layout"]["floating"][0]["native"].is_array(), "its place is the window's native rect"); } + +#[test] +fn wheel_over_a_floating_character_font_field_changes_the_font() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.root_overlay = Some(field.expand(10.0)); + h.frames(2); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frames(2); + let fonts = h.app.run("text.fonts", json!({})).unwrap(); + assert_ne!(fonts[0]["family"], "Source Sans 3", "{fonts}"); + + h.host.borrow_mut().child_overlay = Some((viewport, field.expand(10.0))); + h.frames(2); + let covered = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), covered); + + h.host.borrow_mut().child_overlay = None; + h.frame(vec![]); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), covered); + + h.host.borrow_mut().child_transparent_overlay = Some((viewport, field.expand(10.0))); + h.frames(2); + let covered = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), covered); + + h.host.borrow_mut().child_transparent_overlay = None; + h.host.borrow_mut().child_pass_through_overlay = Some((viewport, field.expand(10.0))); + h.frames(2); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), covered); +} + +#[test] +fn a_modal_blocks_font_wheel_input_in_a_floating_panel() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.app.ui.about = true; + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); + h.app.ui.about = false; + h.frames(2); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), before); +} + +#[test] +fn wheel_stays_under_an_overlay_that_stops_painting() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_transition_overlay = Some((viewport, field.expand(10.0), true)); + h.frames(2); + let covered = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().child_transition_overlay = Some((viewport, field.expand(10.0), false)); + h.frame(vec![]); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), covered); +} + +#[test] +fn wheel_stays_under_an_empty_interactive_overlay() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().child_empty_overlay = Some((viewport, field.expand(10.0))); + h.frames(2); + let covered = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.extend([ + Event::PointerMoved(pointer), + Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }, + ]); + h.frame(vec![]); + assert_eq!(h.app.run("text.fonts", json!({})).unwrap(), covered); +} + +#[test] +fn wheel_without_a_move_uses_the_floating_viewports_pointer() { + let mut h = Harness::new(); + h.app.run("text.create", json!({"x": 30, "y": 50, "text": "Hi", "font": "Source Sans 3"})).unwrap(); + let viewport = h.float("character"); + let field = h + .host + .borrow() + .windows + .get(&viewport) + .and_then(|w| w.texts.iter().find(|(text, _)| text == "Source Sans 3").map(|(_, rect)| *rect)) + .expect("the Character panel's font family field"); + let pointer = pos2(field.min.x + 4.0, field.center().y); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.push(Event::PointerMoved(pointer)); + h.frame(vec![Event::PointerMoved(pos2(1200.0, 800.0))]); + h.app.run("text.create", json!({"x": 30, "y": 90, "text": "New", "font": "Source Sans 3"})).unwrap(); + h.frames(2); + let before = h.app.run("text.fonts", json!({})).unwrap(); + h.host.borrow_mut().windows.get_mut(&viewport).unwrap().events.push(Event::MouseWheel { + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }); + h.frame(vec![]); + assert_ne!(h.app.run("text.fonts", json!({})).unwrap(), before); +} From 3f9545c9620768521af1c326382aa36d71ed1a17 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 00:51:35 -0800 Subject: [PATCH 052/482] Native files: documents from before 0.21.0 keep their Twist turning as saved #5139 (in 0.21.0) made a positive Twist angle turn clockwise, but documents saved by earlier releases stored their angles with the other sign and reopened twisted the other way. The document version (FORMAT_VERSION) goes from 1 to 2. Opening a version 1 document negates its Twist angles (in layers, opacity-mask art, Shaper edits, symbols, graph designs, pattern swatches, graphic styles and brush definitions), unless the file is of the current file version and its generator is VectorCraft 0.21.0 or later. The document opens and saves as version 2. A save for an older file version, which only apps before 0.21.0 read, writes a version 1 document with the angles negated back. Graphic style libraries (.vcstyles) go to version 2: a version 1 library's Twist angles are negated when it is read. Readers do not check either version, so older builds open the new files as before. --- crates/doc/src/lib.rs | 1 + crates/doc/src/limits.rs | 4 +- crates/doc/src/style_libs.rs | 12 +- crates/doc/src/twist.rs | 231 ++++++++++++++++++++++++++ crates/doc/src/twist/tests.rs | 186 +++++++++++++++++++++ crates/engine/src/tests/nativefile.rs | 34 ++++ crates/format/src/lib.rs | 112 ++++++++++++- 7 files changed, 576 insertions(+), 4 deletions(-) create mode 100644 crates/doc/src/twist.rs create mode 100644 crates/doc/src/twist/tests.rs diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 49ba5465a1..84a66220f1 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -68,6 +68,7 @@ mod symbols; pub use symbols::SymbolBoxes; pub mod text; pub mod trace; +pub mod twist; pub mod variables; pub mod xml_id; diff --git a/crates/doc/src/limits.rs b/crates/doc/src/limits.rs index 027148ade2..86c2e802a7 100644 --- a/crates/doc/src/limits.rs +++ b/crates/doc/src/limits.rs @@ -13,7 +13,9 @@ pub enum DocError { Invalid(String), } -pub const FORMAT_VERSION: u32 = 1; +/// The document version new documents get. Version 2: a positive Twist angle turns clockwise +/// ([`crate::twist`]). +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/doc/src/style_libs.rs b/crates/doc/src/style_libs.rs index 30aae49e1e..6eda3acef1 100644 --- a/crates/doc/src/style_libs.rs +++ b/crates/doc/src/style_libs.rs @@ -98,6 +98,10 @@ impl GraphicStyle { /// The extension (and `format` header) of graphic style library files. pub const STYLES_EXT: &str = "vcstyles"; +/// The version of the `.vcstyles` files [`write`] writes. Version 2: a positive Twist angle turns +/// clockwise ([`crate::twist`]). +const STYLES_VERSION: u32 = crate::twist::TWIST_CLOCKWISE_SINCE; + /// The file: a header around the library. #[derive(Serialize, Deserialize)] struct NativeFile { @@ -109,17 +113,21 @@ struct NativeFile { /// `lib` as a `.vcstyles` file. pub fn write(lib: &StyleLibrary) -> String { - let file = NativeFile { format: STYLES_EXT.into(), version: 1, library: lib.clone() }; + let file = NativeFile { format: STYLES_EXT.into(), version: STYLES_VERSION, library: lib.clone() }; serde_json::to_string_pretty(&file).unwrap_or_default() } -/// Read a `.vcstyles` file; an unnamed library is called `name`. +/// Read a `.vcstyles` file; an unnamed library is called `name`. A version 1 file was written by +/// an app that turned Twist counterclockwise: its Twist angles are negated. pub fn read(text: &str, name: &str) -> Result { let f: NativeFile = serde_json::from_str(text.trim_start_matches('\u{feff}')).map_err(|e| format!("not a graphic style library: {e}"))?; if f.format != STYLES_EXT { return Err(format!("not a graphic style library (format `{}`)", f.format)); } let mut lib = f.library; + if f.version < STYLES_VERSION { + crate::twist::negate_library(&mut lib); + } if lib.name.trim().is_empty() { lib.name = name.into(); } diff --git a/crates/doc/src/twist.rs b/crates/doc/src/twist.rs new file mode 100644 index 0000000000..8865fd2a9b --- /dev/null +++ b/crates/doc/src/twist.rs @@ -0,0 +1,231 @@ +//! The Twist effect's angle in saved documents. A positive angle turns clockwise on the page in +//! VectorCraft 0.21.0 and later; earlier releases turned it counterclockwise. Documents of version +//! 2 ([`TWIST_CLOCKWISE_SINCE`]) turn clockwise. Version 1 documents written before 0.21.0 have +//! their Twist angles negated when they open, so they draw as they were saved +//! ([`Document::migrate_twist_angles`], [`written_clockwise`]), and a save for an earlier app +//! negates them back ([`Document::store_legacy_twist_angles`]). Graphic style library files +//! (`.vcstyles`) of version 1 have their Twist angles negated when they are read +//! ([`crate::style_libs::read`]); [`crate::style_libs::write`] writes version 2. + +use std::sync::Arc; + +use serde_json::{Map, Value, json}; + +use crate::style_libs::StyleLibrary; +use crate::{Appearance, Document, Effect, Node}; + +/// The Twist effect's id. +pub const TWIST: &str = "distort.twist"; + +/// The first document version whose Twist angles turn clockwise for a positive value. +pub const TWIST_CLOCKWISE_SINCE: u32 = 2; + +/// The first release (major, minor) whose Twist turned clockwise for a positive angle. +const CLOCKWISE_RELEASE: (u64, u64) = (0, 21); + +/// Did the app named by a native file's `generator` (`"VectorCraft 0.21.0"`) turn Twist effects +/// clockwise for a positive angle? It did from 0.21.0. Any other value, or none, is an earlier +/// app (DrawCraft included). +pub fn written_clockwise(generator: Option<&str>) -> bool { + let Some(version) = generator.and_then(|g| g.strip_prefix("VectorCraft ")) else { return false }; + let mut parts = version.split('.').map(|p| p.parse::().ok()); + match (parts.next().flatten(), parts.next().flatten()) { + (Some(major), Some(minor)) => (major, minor) >= CLOCKWISE_RELEASE, + _ => false, + } +} + +/// The angle a Twist effect without a readable one draws with (`vectorcraft-effects` reads a +/// missing or unreadable `angle` as this). +const DEFAULT_ANGLE: f64 = 10.0; + +/// The key of `Document::unknown` that holds the brush definitions (`vectorcraft-brush`'s +/// `DOC_KEY`), whose art can carry effects. +const BRUSHES_KEY: &str = "brushes"; + +/// The angle a Twist effect with `params` draws with, read as `vectorcraft-effects` reads it: a +/// number, the number a string starts with, or a boolean as 1 or 0; anything else (or a value +/// that is not finite) is [`DEFAULT_ANGLE`]. +fn angle(params: &Value) -> f64 { + let v = match params.get("angle") { + Some(Value::Number(n)) => n.as_f64(), + Some(Value::String(s)) => { + let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect(); + t.parse().ok() + } + Some(Value::Bool(b)) => Some(if *b { 1.0 } else { 0.0 }), + _ => None, + }; + v.filter(|v| v.is_finite()).unwrap_or(DEFAULT_ANGLE) +} + +/// Write the negated angle a Twist effect with `params` draws with into `params`, as a number. +fn negate_params(params: &mut Value) { + // `0.0 - a` rather than `-a`: an angle of 0 stays 0, not -0. + let turned = Value::from(0.0 - angle(params)); + match params { + Value::Object(m) => { + m.insert("angle".into(), turned); + } + p => *p = json!({ "angle": turned }), + } +} + +fn has_twist(fx: &[Effect]) -> bool { + fx.iter().any(|e| e.id == TWIST) +} + +fn appearance_has_twist(a: &Appearance) -> bool { + has_twist(&a.effects) || a.items.iter().any(|i| has_twist(i.effects())) +} + +fn negate_appearance(a: &mut Appearance) { + for e in a.effects.iter_mut().chain(a.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) { + if e.id == TWIST { + negate_params(&mut e.params); + } + } +} + +/// The appearances a Shaper Group's face and edge edits paint with. +fn shaper_appearances(n: &Node) -> impl Iterator { + let s = n.extras().shaper.as_deref(); + let faces = s.into_iter().flat_map(|s| s.faces.iter().filter_map(|f| f.paint.as_ref())); + let edges = s.into_iter().flat_map(|s| s.edges.iter().filter_map(|e| e.paint.as_ref())); + faces.chain(edges) +} + +/// Does `n`'s subtree (opacity-mask art and Shaper edits included) hold a Twist effect? +fn node_has_twist(n: &Node) -> bool { + appearance_has_twist(&n.appearance) + || n.extras().mask.as_ref().is_some_and(|m| node_has_twist(&m.art)) + || shaper_appearances(n).any(appearance_has_twist) + || n.children().is_some_and(|c| c.iter().any(|c| node_has_twist(c))) +} + +/// Negate the Twist angles of `a`'s subtree, copying only the nodes on the way to them. +fn negate_node(a: &mut Arc) { + if !node_has_twist(a) { + return; + } + let n = Arc::make_mut(a); + if appearance_has_twist(&n.appearance) { + negate_appearance(&mut n.appearance); + } + if let Some(x) = n.extras_if_any() { + if let Some(m) = x.mask.as_mut() { + negate_node(&mut m.art); + } + 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())) { + negate_appearance(p); + } + } + } + for c in n.children_mut().into_iter().flatten() { + negate_node(c); + } +} + +fn is_twist_json(m: &Map) -> bool { + m.get("id").and_then(Value::as_str) == Some(TWIST) +} + +/// Does JSON `v` (brush definitions) hold a Twist effect? +fn json_has_twist(v: &Value) -> bool { + match v { + Value::Object(m) => is_twist_json(m) || m.values().any(json_has_twist), + Value::Array(a) => a.iter().any(json_has_twist), + _ => false, + } +} + +/// Negate the Twist angles in JSON `v`: every object whose `id` is [`TWIST`] is a serialized +/// [`Effect`] (object ids are numbers). +fn negate_json(v: &mut Value) { + match v { + Value::Object(m) if is_twist_json(m) => negate_params(m.entry("params").or_insert(Value::Null)), + Value::Object(m) => m.values_mut().for_each(negate_json), + Value::Array(a) => a.iter_mut().for_each(negate_json), + _ => {} + } +} + +/// Negate every Twist angle of a graphic style library: its styles' and its patterns' art. +pub(crate) fn negate_library(lib: &mut StyleLibrary) { + for g in &mut lib.styles { + negate_appearance(&mut g.appearance); + } + for p in &mut lib.patterns { + p.art.iter_mut().for_each(negate_node); + } +} + +impl Document { + /// A document before version [`TWIST_CLOCKWISE_SINCE`] that holds a Twist effect: when + /// `written_clockwise` (asked only then; see [`written_clockwise`]) says the app that saved it + /// turned Twist counterclockwise, negate its Twist angles, so it draws as it was saved. A later + /// version is left as it is, and the document's version is not changed. It recurses through + /// the art, once per level of nesting. + pub fn migrate_twist_angles(&mut self, written_clockwise: impl FnOnce() -> bool) { + if self.version >= TWIST_CLOCKWISE_SINCE || !self.has_twist() || written_clockwise() { + return; + } + self.negate_twist_angles(); + } + + /// The reverse of [`Document::migrate_twist_angles`], for saving for an app that turned Twist + /// counterclockwise: negate the Twist angles and mark the document version 1. Call it on a + /// document whose angles turn clockwise, as every opened or new document's do, whatever + /// version another conversion for that save has marked it already. + pub fn store_legacy_twist_angles(&mut self) { + self.version = TWIST_CLOCKWISE_SINCE - 1; + if self.has_twist() { + self.negate_twist_angles(); + } + } + + /// Does any Twist effect sit where [`Document::negate_twist_angles`] negates them? + fn has_twist(&self) -> bool { + let mut roots = self + .layers + .iter() + .chain(self.symbols.iter().map(|s| &s.art)) + .chain(self.graph_designs.iter().map(|g| &g.art)) + .chain(self.patterns.iter().flat_map(|p| p.art.iter())) + .chain(self.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()).flat_map(|p| p.art.iter())); + roots.any(|r| node_has_twist(r)) + || self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance)) + || self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist) + } + + /// Negate every Twist angle: in the art of the layers, symbols, graph designs, pattern + /// swatches and the pattern definition that pattern editing's Cancel puts back (opacity-mask + /// art and Shaper edits included), in the graphic styles and in the brush definitions. + fn negate_twist_angles(&mut self) { + let roots = self + .layers + .iter_mut() + .chain(self.symbols.iter_mut().map(|s| &mut s.art)) + .chain(self.graph_designs.iter_mut().map(|g| &mut g.art)) + .chain(self.patterns.iter_mut().flat_map(|p| p.art.iter_mut())) + .chain(self.pattern_edit.iter_mut().filter_map(|pe| pe.original.as_mut()).flat_map(|p| p.art.iter_mut())); + for root in roots { + negate_node(root); + } + if self.graphic_styles.iter().any(|g| appearance_has_twist(&g.appearance)) { + for g in self.graphic_styles.iter_mut() { + negate_appearance(&mut g.appearance); + } + } + if self.unknown.get(BRUSHES_KEY).is_some_and(json_has_twist) + && let Some(b) = self.unknown.get_mut(BRUSHES_KEY) + { + negate_json(b); + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/doc/src/twist/tests.rs b/crates/doc/src/twist/tests.rs new file mode 100644 index 0000000000..699be66cb4 --- /dev/null +++ b/crates/doc/src/twist/tests.rs @@ -0,0 +1,186 @@ +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect, shapes}; + +use super::*; +use crate::shaper::{FaceEdit, FaceSelector, ShaperSpec}; +use crate::{GraphicStyle, OpacityMask, PatternDef, Symbol}; + +fn fx(id: &str, params: Value) -> Effect { + Effect { id: id.into(), params, visible: true } +} + +/// An appearance with a Twist of `params` on the object and on its fill, and a Roughen. +fn twisted_appearance(params: &Value) -> Appearance { + let mut a = Appearance::default_art(); + a.effects.push(fx(TWIST, params.clone())); + a.effects.push(fx("distort.roughen", json!({"size": 5}))); + a.items[0].effects_mut().push(fx(TWIST, params.clone())); + a +} + +fn twisted(d: &mut Document, params: &Value) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), twisted_appearance(params)) +} + +/// A version 1 document with Twist effects of `params` everywhere one is stored: on a path, in a +/// group, in an opacity mask's art, in a Shaper edit, in a symbol, a pattern swatch and a graphic +/// style, and `brush` in a brush definition. Its first layer holds the art; its last has no +/// Twist. +fn document(params: &Value, brush: &Value) -> Document { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let path = twisted(&mut d, params); + d.insert(Some(l), 0, path).unwrap(); + let inner = twisted(&mut d, params); + let group = Node::group(d.alloc_id(), vec![Arc::new(inner)]); + d.insert(Some(l), 1, group).unwrap(); + let mask_art = twisted(&mut d, params); + let mut masked = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + masked.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, true))); + d.insert(Some(l), 2, masked).unwrap(); + let mut shaper = Node::group(d.alloc_id(), vec![]); + let face = FaceEdit { + selector: FaceSelector { sources: vec![0], anchor: Point::ZERO }, + erase: false, + erase_edges: false, + paint_source: None, + merge: None, + paint: Some(twisted_appearance(params)), + }; + shaper.extras_mut().shaper = Some(Box::new(ShaperSpec { faces: vec![face], edges: vec![] })); + d.insert(Some(l), 3, shaper).unwrap(); + let art = twisted(&mut d, params); + d.symbols.push(Symbol { name: "S".into(), art: Arc::new(art), dynamic: false }); + let art = twisted(&mut d, params); + d.patterns.push(PatternDef::new("P", vec![Arc::new(art)])); + d.graphic_styles.push(GraphicStyle::new("G", twisted_appearance(params))); + d.unknown.insert(BRUSHES_KEY.into(), json!([{"name": "B", "art": {"id": 99, "appearance": {"effects": [brush]}}}])); + d.add_layer(None); + d.version = 1; + d +} + +/// The angle each Twist effect of the saved document draws with, in the order the JSON lists them. +fn angles(d: &Document) -> Vec { + fn walk(v: &Value, out: &mut Vec) { + match v { + Value::Object(m) => { + if is_twist_json(m) { + out.push(angle(m.get("params").unwrap_or(&Value::Null))); + } + m.values().for_each(|c| walk(c, out)); + } + Value::Array(a) => a.iter().for_each(|c| walk(c, out)), + _ => {} + } + } + let mut out = vec![]; + walk(&serde_json::to_value(d).unwrap(), &mut out); + out +} + +#[test] +fn a_version_1_document_from_before_0_21_has_its_twist_angles_negated() { + let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST})); + let before = angles(&d); + // Two per path, shaper edit and style; one in the brush. + assert_eq!(before.len(), 15, "{before:?}"); + assert_eq!(before.iter().filter(|&&a| a == DEFAULT_ANGLE).count(), 1, "{before:?}"); + d.migrate_twist_angles(|| false); + assert_eq!(d.version, 1, "the caller sets the version"); + assert_eq!(angles(&d), before.iter().map(|a| -a).collect::>()); + let roughen = serde_json::to_string(&d).unwrap().matches(r#""id":"distort.roughen","params":{"size":5}"#).count(); + assert_eq!(roughen, 7, "other effects are left alone"); +} + +#[test] +fn a_document_that_turned_clockwise_is_left_as_it_is() { + let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST, "params": {"angle": 30}})); + let before = d.clone(); + d.migrate_twist_angles(|| true); + assert_eq!(d, before, "version 1, written by 0.21.0 or later"); + d.version = 2; + let before = d.clone(); + d.migrate_twist_angles(|| panic!("a version 2 document's writer is not asked about")); + assert_eq!(d, before, "version 2"); +} + +#[test] +fn the_writer_is_asked_about_only_when_a_twist_is_stored() { + let mut d = Document::new(10.0, 10.0); + d.version = 1; + let before = d.clone(); + d.migrate_twist_angles(|| panic!("a document without a Twist needs no answer")); + assert_eq!(d, before); +} + +#[test] +fn angles_are_read_as_the_effect_reads_them() { + let read = |params: Value| { + let mut e = fx(TWIST, params); + negate_params(&mut e.params); + e.params + }; + assert_eq!(read(json!({"angle": 30, "x": 1})), json!({"angle": -30.0, "x": 1})); + assert_eq!(read(json!({"angle": "45 deg"})), json!({"angle": -45.0})); + assert_eq!(read(json!({"angle": true})), json!({"angle": -1.0})); + assert_eq!(read(json!({})), json!({"angle": -10.0})); + assert_eq!(read(Value::Null), json!({"angle": -10.0})); + let zero = read(json!({"angle": 0})); + assert!(zero["angle"].as_f64().is_some_and(|a| a == 0.0 && a.is_sign_positive()), "{zero}"); +} + +#[test] +fn only_the_art_holding_a_twist_is_copied() { + let mut d = document(&json!({"angle": 30}), &json!({"id": TWIST})); + let plain = d.layers.last().cloned().unwrap(); + let twisted = d.layers[0].clone(); + d.migrate_twist_angles(|| false); + assert!(Arc::ptr_eq(d.layers.last().unwrap(), &plain), "a layer without a Twist is not copied"); + assert!(!Arc::ptr_eq(&d.layers[0], &twisted)); +} + +#[test] +fn storing_for_an_earlier_app_and_reading_back_round_trips() { + let original = document(&json!({"angle": 30.0}), &json!({"id": TWIST, "params": {"angle": -12.5}})); + let mut d = original.clone(); + d.migrate_twist_angles(|| false); + d.version = 2; + let current = d.clone(); + assert_eq!(angles(¤t), angles(&original).iter().map(|a| -a).collect::>()); + d.store_legacy_twist_angles(); + assert_eq!(d, original); + d.migrate_twist_angles(|| false); + d.version = 2; + assert_eq!(d, current); + // Another conversion for the same save may have marked the document version 1 already. + d.version = 1; + d.store_legacy_twist_angles(); + assert_eq!(d, original); +} + +#[test] +fn a_version_1_style_library_has_its_twist_angles_negated() { + let lib = StyleLibrary { name: "L".into(), styles: vec![GraphicStyle::new("G", twisted_appearance(&json!({"angle": 30.0})))], patterns: vec![] }; + let text = crate::style_libs::write(&lib); + assert!(text.contains(r#""version": 2"#), "{text}"); + assert_eq!(crate::style_libs::read(&text, "x").unwrap(), lib, "a version 2 file reads as written"); + let old = crate::style_libs::read(&text.replacen(r#""version": 2"#, r#""version": 1"#, 1), "x").unwrap(); + let fx = &old.styles[0].appearance.effects; + assert_eq!(fx[0].params, json!({"angle": -30.0})); + assert_eq!(fx[1], lib.styles[0].appearance.effects[1]); + assert_eq!(old.styles[0].appearance.items[0].effects()[0].params, json!({"angle": -30.0})); +} + +#[test] +fn releases_from_0_21_turned_twist_clockwise() { + for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.4", "VectorCraft 0.22.0-dev", "VectorCraft 1.0.0"] { + assert!(written_clockwise(Some(g)), "{g}"); + } + for g in ["VectorCraft 0.20.0", "VectorCraft 0.9.12", "DrawCraft 0.1.0", "VectorCraft", "VectorCraft x.y", "vectorcraft 0.21.0"] { + assert!(!written_clockwise(Some(g)), "{g}"); + } + assert!(!written_clockwise(None)); +} diff --git a/crates/engine/src/tests/nativefile.rs b/crates/engine/src/tests/nativefile.rs index 4f67890b17..5b9973e563 100644 --- a/crates/engine/src/tests/nativefile.rs +++ b/crates/engine/src/tests/nativefile.rs @@ -186,6 +186,40 @@ fn newer_keys_and_legacy_profiles_survive_open_and_save() { assert_eq!(v2["document"]["unknown"]["colorProfiles"]["rgb"], "sRGB IEC61966-2.1"); } +/// A version 1 document saved before VectorCraft 0.21.0 turned its Twist effects counterclockwise +/// for a positive angle. It opens with the angles negated, so its art turns as it did; saved +/// again it is a version 2 document, and saved for an older file version it is version 1 again. +#[test] +fn a_version_1_documents_twist_turns_as_it_was_saved() { + use vectorcraft_doc::{Appearance, Document, Effect, Node}; + use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let right = PathData::single(SubPath::polyline(&[Point::new(55.0, 50.0), Point::new(56.0, 50.0)], false)); + let mut a = Appearance::default_art(); + a.effects.push(Effect { id: "distort.twist".into(), params: json!({"angle": 45}), visible: true }); + d.insert(Some(l), 0, Node::path(id, right.clone(), a)).unwrap(); + let mut j = json_of(&vectorcraft_format::save(&d, false)); + j["document"]["version"] = json!(1); + j["generator"] = json!("VectorCraft 0.20.0"); + let mut s = Session::new(); + open(&mut s, "old.vectorcraft", &serde_json::to_vec(&j).unwrap()); + let doc = &s.doc().unwrap().doc; + let n = doc.layers[0].children().and_then(|c| c.first()).cloned().unwrap(); + let turned = vectorcraft_render::effects::apply_geometry(&n.appearance.effects, &right, Rect::new(0.0, 0.0, 100.0, 100.0)); + // Counterclockwise on the page takes a point right of the center up (y runs down). + let p = turned.subpaths[0].anchors[0].p; + assert!(p.y < 49.5, "{p:?}"); + let again = json_of(&saved(&mut s, json!({}))); + assert_eq!(again["document"]["version"], 2); + assert!(again.to_string().contains(r#""angle":-45.0"#), "{again}"); + // Saved for an older file version, it is version 1 with its angle as 0.20.0 saved it. + let older = json_of(&saved(&mut s, json!({"version": 3}))); + assert_eq!(older["document"]["version"], 1); + assert!(older.to_string().contains(r#""angle":45.0"#), "{older}"); +} + /// A save records the date the document was made in, so the same commands twice gave different /// bytes (#2880). A pinned date makes them identical — `file.new {created}` here, and /// `SOURCE_DATE_EPOCH` for an export that takes no date param. diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 57a5cfc952..6ed3e68407 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -29,6 +29,13 @@ //! `data`. Every version loads, and [`save_with`] writes any of them for older apps (under the //! format name `drawcraft`, which every version reads). Readers reject files whose `version` is //! newer than they support. +//! +//! The document has a version of its own (`document.version`, [`vectorcraft_doc::FORMAT_VERSION`]), +//! which readers do not check. A version 2 document's Twist effects turn clockwise for a positive +//! angle. A version 1 document's Twist angles are negated when it opens, unless the file is of +//! [`VERSION`] and its `generator` is VectorCraft 0.21.0 or later, which turned them clockwise +//! already; [`save_with`] writes a version 1 document with them negated back for an older file +//! version ([`vectorcraft_doc::twist`]). #![forbid(unsafe_code)] #[cfg(not(target_arch = "wasm32"))] @@ -244,6 +251,10 @@ fn body(doc: &Document, o: &SaveOptions) -> Result { if version < 3 { d.store_legacy_color_profiles(); } + // Apps that read only older file versions predate 0.21.0 and turn Twist the other way. + if version < VERSION { + d.store_legacy_twist_angles(); + } let v1 = if version == 1 { let mut v = serde_json::to_value(&d).map_err(encode_err)?; legacy::anchors_to_v1(&mut v); @@ -489,7 +500,7 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result vectorcraft_doc::node::with_buffered_value_budget(max_values, || Contents::::read(file.json())) }) }; - let f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { + let mut f = vectorcraft_doc::geom::path::with_anchor_budget(vectorcraft_doc::geom::path::MAX_READ_ANCHORS, read).map_err(|e| match e { ReadError::Json(e) => { let why = if e.to_string().contains("recursion limit") { format!("its objects are nested too deep ({e})") } else { e.to_string() }; FormatError::NotVectorcraft(why) @@ -498,6 +509,12 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result e => FormatError::NotVectorcraft(e.to_string()), })?; let info = FileInfo { version: f.version, legacy: f.format == LEGACY_EXTENSION }; + // A version 1 document saved before VectorCraft 0.21.0, or for an app before it (an older file + // version): its Twist angles turned the other way. The app that wrote it is read from the JSON + // before the data after it is taken; the walk's depth is bounded by the JSON reader's nesting + // limit. + let current_file = f.version >= VERSION; + f.document.migrate_twist_angles(|| current_file && vectorcraft_doc::twist::written_clockwise(generator(file.json()).as_deref())); // The bytes after the JSON, read in one pass: the images' first, then the profiles'. let entries: Vec<[u64; 2]> = f.images.values().chain(f.profiles.values()).filter_map(|i| i.blob).collect(); let tail = file.entries(&entries)?; @@ -559,6 +576,8 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result // labels and the character styles, within the ranges `document.setup` takes (after the depth // limit: the walk recurses). doc.keep_scripts_in_range(); + // The conversions above bring an older document to today's version. + doc.version = doc.version.max(vectorcraft_doc::FORMAT_VERSION); let profiles = f .profiles .into_iter() @@ -574,6 +593,37 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result Ok(NativeFile { doc, depth_notes, info, profiles }) } +/// The file's first `generator` member, the app that wrote it (`None`: it has none, it is not a +/// string, or the file is not an object of members). The other members, and any further +/// `generator`, are skipped without being kept, as reading the file skips them. +fn generator(json: &[u8]) -> Option { + struct Generator(Option); + struct Members; + impl<'de> serde::de::Visitor<'de> for Members { + type Value = Generator; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a file's members") + } + fn visit_map>(self, mut m: A) -> Result { + let mut first: Option = None; + while let Some(key) = m.next_key::>()? { + if key == "generator" && first.is_none() { + first = Some(m.next_value()?); + } else { + m.next_value::()?; + } + } + Ok(Generator(first.and_then(|v| v.as_str().map(str::to_owned)))) + } + } + impl<'de> serde::Deserialize<'de> for Generator { + fn deserialize>(d: D) -> Result { + d.deserialize_map(Members) + } + } + serde_json::from_slice::(json).ok()?.0 +} + /// The bytes of the member of the file's head `pick` picks (only that entry of the data after /// the JSON is kept). fn head_member(bytes: &[u8], pick: impl FnOnce(Head) -> Option) -> Option> { @@ -853,6 +903,66 @@ mod tests { assert!(why.contains("more than 100 values before its type"), "{why}"); } + /// A version 1 document written before VectorCraft 0.21.0 (or by an app the file does not + /// name) has its Twist angles negated when it opens; one written by 0.21.0 or later, and a + /// version 2 document, keep them. Each opens as version 2. A save for an older file version + /// negates them back. + #[test] + fn twist_angles_follow_the_document_version_and_generator() { + use vectorcraft_doc::Effect; + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let id = d.alloc_id(); + let mut a = Appearance::default_art(); + a.effects.push(Effect { id: "distort.twist".into(), params: serde_json::json!({"angle": 30.0}), visible: true }); + d.insert(Some(l), 0, Node::path(id, shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0)), a)).unwrap(); + let angle = |d: &Document| d.node(id).and_then(|n| n.appearance.effects[0].params["angle"].as_f64()); + let current = save(&d, false); + let back = load(¤t).unwrap(); + assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "a version 2 document is read as saved"); + let opened = |generator: Option<&str>| { + let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + v["document"]["version"] = 1.into(); + match generator { + Some(g) => v["generator"] = g.into(), + None => { + v.as_object_mut().unwrap().remove("generator"); + } + } + let d = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + (d.version, angle(&d)) + }; + for g in [Some("VectorCraft 0.20.0"), Some("VectorCraft 0.9.12"), Some("DrawCraft 0.1.0"), Some("VectorCraft"), None] { + assert_eq!(opened(g), (2, Some(-30.0)), "{g:?}"); + } + for g in ["VectorCraft 0.21.0", "VectorCraft 0.21.3", "VectorCraft 1.0.0"] { + assert_eq!(opened(Some(g)), (2, Some(30.0)), "{g}"); + } + // A file may repeat `generator`: the first one names the app. + let mut v: serde_json::Value = serde_json::from_slice(¤t).unwrap(); + v["document"]["version"] = 1.into(); + v["generator"] = "VectorCraft 0.21.0".into(); + let text = serde_json::to_string(&v).unwrap(); + let first = r#""generator":"VectorCraft 0.21.0""#; + let twice = text.replacen(first, &format!(r#"{first},"generator":"DrawCraft 0.1.0""#), 1); + assert_ne!(twice, text); + assert_eq!(angle(&load(twice.as_bytes()).unwrap()), Some(30.0)); + v["generator"] = "VectorCraft 0.20.0".into(); + let old = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + let again = load(&save(&old, false)).unwrap(); + assert_eq!((again.version, angle(&again)), (2, Some(-30.0)), "saved again, it is version 2"); + // Saved for an older file version (apps before 0.21.0): version 1 with the angle negated + // back, whatever the generator, and it reopens as it was. + for version in MIN_VERSION..VERSION { + let bytes = save_with(&d, &SaveOptions { version, ..SaveOptions::default() }).unwrap(); + let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["document"]["version"], 1, "file version {version}"); + assert!(String::from_utf8_lossy(&bytes).contains(r#""angle":-30.0"#), "file version {version}"); + let back = load(&bytes).unwrap(); + assert_eq!((back.version, angle(&back)), (2, Some(30.0)), "file version {version}"); + } + } + #[test] fn rejects_foreign_and_future() { assert!(load(b"{}").is_err()); From 9275b902a9d441546262289f04e66b2cee80be91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:01:20 -0800 Subject: [PATCH 053/482] PDF/.ai import: a file whose type all comes from its text document opens without its PDF part A PDF-compatible .ai (or a PDF saved with the editing data) now opens from its layers without its PDF part being imported, and without being compared with its page, when: - its text document makes the type of every text object, hidden ones included, at least one text object shows, and none is drawn by the appearance of the layer or group it is in; - its layers hold no unread object, no placed file with a second placement and no live envelope with drawn art to fall back on, and no image too large to read; - it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's UserUnit. A file whose layers draw differently from its page then opens from its layers instead of its PDF part. The bleed comes from the pages' bleed boxes. The check runs only when no pages are picked, layers and the editing data are on, the crop box is asked for and type comes in as text. Files saved without PDF compatibility, files whose PDF part draws only type or nothing, and files whose PDF part's content can't be read take the same path when they qualify: their bleed comes from the pages' bleed boxes, pages in units larger than a point draw them at their size in points, and the note that the PDF part couldn't be read is not given, since its content is not read. Files that don't qualify open as before, and the editing data decoded and read for the check is reused after the PDF part is imported (layered_ai_from). When a file whose PDF part can't be read is scaled up to its size in points, its text wraps are now laid out again at that size, and the default graphic styles of a file without graphic styles of its own are no longer scaled. The same applies on the new path. --- crates/engine/src/cmd/fileio/load.rs | 113 ++++++++++------ .../engine/src/cmd/fileio/tests_aiimport.rs | 124 +++++++++++++++++- crates/eps/src/import.rs | 2 +- crates/eps/src/import/native.rs | 6 +- crates/eps/src/import/native/build.rs | 88 ++++++++++++- crates/eps/src/import/native/layers.rs | 67 +++++++++- crates/eps/src/lib.rs | 3 +- crates/pdf/Cargo.toml | 2 +- crates/pdf/src/import.rs | 2 + crates/pdf/src/import/entry.rs | 15 +++ crates/pdf/src/lib.rs | 6 +- crates/pdf/src/pages.rs | 30 +++++ docs/file-format-parity.md | 2 +- 13 files changed, 404 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index eca365ca16..2b1de2eda4 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -165,18 +165,18 @@ pub fn load(name: &str, bytes: &[u8]) -> Result { /// of its art, which it carries: its layers and hidden objects as they were, and the art outside /// its artboard (its PDF part has only what is on the artboards), as an EPS of the editor is read. /// Anything else as it was. `unit`: the size in points of a unit of the PDF part's user space (its -/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `private`: the -/// editor's copy ([`editing_copy`]). +/// first page's `UserUnit`) → (document, warnings, whether its layers were read). `layers`: the +/// editor's copy ([`editing_copy`]), as far as it was decoded and read. fn through_editing_data( - private: Option<&[u8]>, + layers: Option, opts: &LoadOptions, doc: Document, warnings: Vec, unit: f64, ) -> (Document, Vec, bool) { - let Some(private) = private else { return (doc, warnings, false) }; + let Some(layers) = layers else { return (doc, warnings, false) }; let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines; - let (doc, mut warnings, read) = vectorcraft_eps::layered_ai(private, doc, warnings, outlined, opts.trust_editing_data, unit); + let (doc, mut warnings, read) = vectorcraft_eps::layered_ai_from(layers, doc, warnings, outlined, opts.trust_editing_data, unit); // The layers weren't read (or couldn't be): the notes of reading the PDF part still hold. if !read { return (doc, warnings, false); @@ -216,6 +216,14 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool { opts.pages.is_none() && opts.layers && opts.editing_data } +/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part +/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages' +/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its +/// type as text? +fn reads_layers_alone(opts: &LoadOptions) -> bool { + reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines +} + /// The editor's own copy of its art that `opened` carries (as [`vectorcraft_pdf::illustrator_data`] /// reads it), when `opts` read it ([`reads_editing_copy`]). fn editing_copy(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) -> Option> { @@ -365,41 +373,68 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Ok(o) => super::pdfimport::import(bytes, o, opts, format.id != "pdf"), Err(e) => Err(err(e)), }; - let read = restore_or_import(editing, || match imported() { - Ok(r) => { - // The editor's copy, read once the import is done with the pages. - let private = opened.as_ref().ok().and_then(|o| editing_copy(o, opts)); - // Pages of text alone: the editing copy alone where it reads, as for a file - // saved without its PDF part (#1387: else the page, which is the art). So too - // pages that draw nothing at all: there is no page art to check the layers - // against, and the empty page would lose all of it. - // A page is empty only when nothing on it was skipped (an image that can't be - // decoded draws nothing either): its notes are at most the page's own. - let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); - let alone = (r.only_text || empty) - .then(|| private.as_deref().map(editing_copy_alone)) - .flatten() - .and_then(|read| read.ok()) - .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)); - let (doc, warnings, read) = match alone { - Some((doc, warnings)) => (doc, warnings, true), - None => through_editing_data(private.as_deref(), opts, r.document, r.warnings, r.user_unit), - }; - editing_data = read; - Ok((doc, warnings)) + let read = restore_or_import(editing, || { + // Type all from the text document and nothing that needs the PDF part: the layers + // alone, the PDF part not imported. Else what was read of the layers is kept for + // reading them with the PDF part. + let mut layers = None; + if let Some((o, private)) = opened.as_ref().ok().filter(|_| reads_layers_alone(opts)).and_then(|o| Some((o, editing_copy(o, opts)?))) + { + let pages = o.trim_pages(); + match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit) { + Ok((mut doc, warnings)) => { + doc.setup.bleed = pages.bleed; + editing_data = true; + return Ok((doc, warnings)); + } + Err(read) => layers = Some(read), + } + } + match imported() { + Ok(r) => { + // The editor's copy, read once the import is done with the pages, unless + // its layers were read before it. + let private = layers.is_none().then(|| opened.as_ref().ok().and_then(|o| editing_copy(o, opts))).flatten(); + // Pages of text alone: the editing copy alone where it reads, as for a file + // saved without its PDF part (#1387: else the page, which is the art). So too + // pages that draw nothing at all: there is no page art to check the layers + // against, and the empty page would lose all of it. + // A page is empty only when nothing on it was skipped (an image that can't be + // decoded draws nothing either): its notes are at most the page's own. + let empty = draws_nothing(&r.document) && r.warnings.iter().all(|w| is_page_note(w)); + let copy_alone = || match &private { + Some(private) => Some(editing_copy_alone(private)), + None if layers.is_some() => opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p)), + None => None, + }; + let alone = (r.only_text || empty) + .then(copy_alone) + .flatten() + .and_then(|read| read.ok()) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)); + let (doc, warnings, read) = match alone { + Some((doc, warnings)) => (doc, warnings, true), + None => { + let layers = layers.or_else(|| private.as_deref().map(vectorcraft_eps::AiLayers::decode)); + through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) + } + }; + editing_data = read; + Ok((doc, warnings)) + } + // Saved without its PDF part: the editing copy is all the file has (`pages` that + // name every page read it as the whole file). + Err(e) if is_placeholder(&e) => opened + .as_ref() + .ok() + .and_then(|o| from_editing_data_alone(o, opts)) + .unwrap_or(Err(e)) + .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) + .inspect(|_| editing_data = true), + // A PDF part that can't be read (a stream the import refuses): the editing copy + // alone where it reads, else the error. + Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), } - // Saved without its PDF part: the editing copy is all the file has (`pages` that - // name every page read it as the whole file). - Err(e) if is_placeholder(&e) => opened - .as_ref() - .ok() - .and_then(|o| from_editing_data_alone(o, opts)) - .unwrap_or(Err(e)) - .map(|(doc, warnings)| outlined_if_asked(doc, warnings, opts)) - .inspect(|_| editing_data = true), - // A PDF part that can't be read (a stream the import refuses): the editing copy - // alone where it reads, else the error. - Err(e) => without_pdf_part(bytes, opts, &e).inspect(|_| editing_data = true).ok_or(e), })?; // The File Info of a file read from its pages or its editing copy. if !read.2 { diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 16049850c0..0f97a58627 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -1221,10 +1221,16 @@ fn half_outlined_line(y: f64, rest: &str, mode: u8) -> String { /// text document (a line starting at (14, 65)), then `more` of a story the text document doesn't /// have. Without `story` the file has no text document. fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec { + half_outlined_ai_on(story, more, type_content, "", |page| page) +} + +/// [`half_outlined_ai`] with the editing data's comments `head` before its art, whose page is +/// `page_of` the 200 × 100 pt page it draws on (other boxes, more entries). +fn half_outlined_ai_on(story: Option<&str>, more: usize, type_content: &str, head: &str, page_of: impl FnOnce(PdfPage) -> PdfPage) -> Vec { let text = |story: u32| format!("/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n{story} /StoryIndex ,\n;\n"); let texts: String = std::iter::once(text(0)).chain((0..more).map(|_| text(99))).collect(); let mut body = - format!("%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0)))); + format!("{head}%AI3_TemplateBox: 100 50 100 50\n{}", ai::layer("Art", &format!("0.5 g\n{}f\n{texts}", ai::rect(120.0, 20.0, 160.0, 60.0)))); if let Some(story) = story { // The story's one line starts at the canvas center (8191.5, the template box's center) moved // to (14, 65): its y runs down the page. @@ -1255,7 +1261,7 @@ fn half_outlined_ai(story: Option<&str>, more: usize, type_content: &str) -> Vec }; let cmap = "begincmap\n1 begincodespacerange\n<00> \nendcodespacerange\n1 beginbfchar\n<41> \nendbfchar\nendcmap\n"; pdf_with( - &[page], + &[page_of(page)], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len()), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None, ) @@ -1287,6 +1293,12 @@ fn texts(s: &Session) -> Vec { /// (art x 10 to 90 and 110 to 190, y 10 to 90), then a band across the first frame (y 30 to 70), /// made a wrap object with no offset when `wrap` is set. fn wrapped_thread_ai(wrap: bool) -> Vec { + ai::ai(&wrapped_thread_data(wrap.then_some(0.0)), PLACEHOLDER) +} + +/// The editing data of [`wrapped_thread_ai`], compressed, with the band a wrap object of `offset` +/// when one is given. +fn wrapped_thread_data(offset: Option) -> Vec { // The template box is centred at (100, 50), the canvas centre 8191.5: y runs down the canvas. let canvas = |x: f64, y: f64| (x + 8091.5, 8241.5 - y); let rect = |x0: f64, y0: f64, x1: f64, y1: f64| { @@ -1306,14 +1318,47 @@ fn wrapped_thread_ai(wrap: bool) -> Vec { ); let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); let frame = |f: u32| format!("/AI11Text :\n0 /FreeUndo ,\n{f} /FrameIndex ,\n0 /StoryIndex ,\n;\n"); - let dict = if wrap { "%_/ArtDictionary :\n%_0 /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n" } else { "" }; + let dict = offset + .map(|o| format!("%_/ArtDictionary :\n%_{o} /Real (AI11TextWrapOffset) ,\n%_0 /Bool (AI11TextWrapInvert) ,\n%_;\n%_\n")) + .unwrap_or_default(); let art = format!("{}{}0.5 g\n{}f\n{dict}", frame(0), frame(1), ai::rect(10.0, 30.0, 90.0, 70.0)); let body = format!( "%AI3_TemplateBox: 100 50 100 50\n{}%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", ai::layer("Art", &art), lines.join("\n") ); - ai::ai(&compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()), PLACEHOLDER) + compressed(ai::editing_data(200.0, 100.0, &body).as_bytes()) +} + +/// The wrap offset of the first frame of `doc`'s threaded type, as its text resolves it. +fn first_frame_wrap_offset(doc: &vectorcraft_doc::Document) -> f64 { + match &doc.node(doc.text_threads[0][0]).unwrap().kind { + NodeKind::Text(t) => t.wrap[0].wrap.offset, + _ => panic!("area type"), + } +} + +/// A `.ai` in units of 10 points whose threaded area type flows around a wrap object of a 2 unit +/// offset opens with the type flowing round it 20 pt off, its PDF part read or not, and when its +/// PDF part can't be read. The default graphic styles of a file without its own aren't scaled. +#[test] +fn wrapped_type_in_units_of_ten_points_flows_round_the_wrap_at_its_size_in_points() { + let private = wrapped_thread_data(Some(2.0)); + let page = "0.5 g 10 30 80 40 re f"; + let refused = ai::ai_with_entries_and_content(&private, page, "/UserUnit 10", REFUSED_CONTENT); + // On the trim boxes the PDF part is imported, and the refused stream stops it. + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + let files = [(ai::ai_with(&private, page, "/UserUnit 10"), LoadOptions::default()), (refused, trim)]; + for (file, opts) in &files { + let loaded = load_with("thread.ai", file, opts).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert!((first_frame_wrap_offset(&loaded.doc) - 20.0).abs() < 0.01, "{:?}", loaded.warnings); + } + let loaded = load_with("thread.ai", &files[1].0, &files[1].1).unwrap(); + assert!(loaded.warnings.iter().any(|w| w.starts_with("the PDF part couldn't be read")), "{:?}", loaded.warnings); + // The file has no graphic styles of its own: the default ones aren't scaled either way. + let read = load_with("thread.ai", &files[0].0, &files[0].1).unwrap(); + assert_eq!(loaded.doc.graphic_styles, read.doc.graphic_styles); } /// Threaded area type below a wrap object flows around it when the file opens: the text the wrap @@ -1358,6 +1403,77 @@ fn type_from_the_text_document_opens_without_the_pdf_parts_note_on_outlines() { assert!(!r["warnings"].as_array().unwrap().contains(&without_outlines_note(1)), "{r}"); } +/// A `.ai` whose text document makes all of its type, with nothing unread, opens from its layers +/// without its PDF part being imported: a page that draws more than the layers isn't compared with +/// them. On its trim box it takes the pages' bleed, and pages in units of 10 points draw it ten +/// times as large, as when its PDF part is imported. With type the text document can't make, +/// editing data on a large canvas, its type asked for as outlines, another box or pages picked, the +/// PDF part is imported as before. +#[test] +fn type_all_from_the_text_document_opens_without_importing_the_pdf_part() { + let line = half_outlined_line(65.0, "rst draft", 0); + // The page draws a red square the layers don't have. + let differs = half_outlined_ai(Some("first draft"), 0, &format!("{line} 1 0 0 rg 20 20 30 30 re f")); + let mut s = Session::new(); + let before = vectorcraft_pdf::imports_of(&differs); + let loaded = load_with("draft.ai", &differs, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&differs), before, "{:?}", loaded.warnings); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert!(!loaded.warnings.iter().any(|w| w.contains("differently")), "{:?}", loaded.warnings); + let r = open(&mut s, "draft.ai", &differs, json!({})).unwrap(); + assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}"); + assert_eq!(texts(&s), ["first draft"], "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[0].children().unwrap().len(), 2, "the square and the type, without the page's red square: {r}"); + // A 10 pt bleed round the trim box, the art drawn in the trim box. + let bled = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { + media: [0.0, 0.0, 220.0, 120.0], + bleed: Some([0.0, 0.0, 220.0, 120.0]), + trim: Some([10.0, 10.0, 210.0, 110.0]), + content: format!("1 0 0 1 10 10 cm {}", p.content), + ..p + }); + let before = vectorcraft_pdf::imports_of(&bled); + let loaded = load_with("bled.ai", &bled, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&bled), before); + assert_eq!(loaded.doc.setup.bleed, [10.0; 4]); + // Pages of 10 pt units. + let large = half_outlined_ai_on(Some("first draft"), 0, &line, "", |p| PdfPage { entries: format!("{} /UserUnit 10", p.entries), ..p }); + let before = vectorcraft_pdf::imports_of(&large); + let loaded = load_with("large.ai", &large, &LoadOptions::default()).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(&large), before); + let board = loaded.doc.artboards[0].rect; + assert!((board.width() - 2000.0).abs() < 0.01 && (board.height() - 1000.0).abs() < 0.01, "{board:?}"); + // Opened on the trim boxes with the PDF part imported and compared, as before, both files have + // the same artboards and bleed. + for file in [&bled, &large] { + let alone = load_with("draft.ai", file, &LoadOptions::default()).unwrap(); + let compared = load_with("draft.ai", file, &LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }).unwrap(); + assert!(compared.editing_data, "{:?}", compared.warnings); + let boards = |d: &vectorcraft_doc::Document| d.artboards.iter().map(|a| a.rect).collect::>(); + assert_eq!(boards(&alone.doc), boards(&compared.doc)); + assert_eq!(alone.doc.setup.bleed, compared.doc.setup.bleed); + assert_eq!(names(&alone.doc.layers), names(&compared.doc.layers)); + // The file has no graphic styles of its own: the default ones aren't scaled. + assert_eq!(alone.doc.graphic_styles, compared.doc.graphic_styles); + } + // The PDF part is imported, once. + let unmade = half_outlined_ai(Some("first draft"), 1, &line); + // Editing data on a large canvas reads at its own scale when the file has no PDF part. + let canvas = half_outlined_ai_on(Some("first draft"), 0, &line, "%AI24_LargeCanvasScale: 2\n", |p| p); + let cases = [ + (&unmade, LoadOptions::default()), + (&canvas, LoadOptions::default()), + (&differs, LoadOptions { text_as: vectorcraft_pdf::TextAs::Outlines, ..Default::default() }), + (&differs, LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }), + (&differs, LoadOptions { pages: Some("1".into()), ..Default::default() }), + ]; + for (file, opts) in cases { + let before = vectorcraft_pdf::imports_of(file); + load_with("draft.ai", file, &opts).unwrap(); + assert_eq!(vectorcraft_pdf::imports_of(file) - before, 1, "{opts:?}"); + } +} + /// A text object that takes the page's type lacks the glyphs next to it that the page kept as /// outlines: a note counts such objects, in place of the PDF part's notes. Stroked glyphs that /// come in with the stroked type keep the PDF part's notes. diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index f122812715..aefb80ccb1 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -71,7 +71,7 @@ use interp::{Fault, Interp}; use obj::PsError; pub(crate) use native::scale_document; -pub use native::{ai_alone, ai_alone_on_page, is_loss, layered_ai}; +pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, is_loss, layered_ai, layered_ai_from}; pub use text::family_style; /// The page of a PostScript file without a bounding box (US Letter). diff --git a/crates/eps/src/import/native.rs b/crates/eps/src/import/native.rs index 354196555d..ed1b97616f 100644 --- a/crates/eps/src/import/native.rs +++ b/crates/eps/src/import/native.rs @@ -23,7 +23,9 @@ //! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is //! also the safety net: when the layers' art looks different from it (one draws an object the //! other doesn't, or much of it differs; an EPS whose page is its art's box has nothing printed -//! outside it), the page is used. +//! outside it), the page is used. A `.ai` whose text document makes all of its type, with no +//! object unread and nothing else that the page would decide, opens from its layers without its +//! PDF part being imported, so nothing is compared ([`ai_layers_alone`]). //! //! Where a file doesn't match what this module expects, it is left alone and its page is imported. @@ -52,7 +54,7 @@ use build::{Frame, MADE, prune_unseen}; use compare::{ MAX_DIFFERENCE, MAX_SOLID_DIFFERENCE, PageView, Shares, compare, compared, comparison_render, comparison_samples, differ, differ_in_colour, }; -pub use layers::{ai_alone, ai_alone_on_page, layered_ai}; +pub use layers::{AiLayers, ai_alone, ai_alone_on_page, ai_layers_alone, layered_ai, layered_ai_from}; pub(super) use layers::{layered, program_alone}; pub use slots::is_loss; #[cfg(test)] diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 31be3af5a8..1498c730a0 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -76,14 +76,98 @@ pub(super) fn build_on_page(data: &[u8], page: (f64, f64), unit: f64) -> Result< }; let in_units = |r: Option, k: f64| k.is_finite() && k > 1.0 && fits(r, k) && !fits(r, 1.0); let scale = [unit, structure.canvas_scale].into_iter().find(|&k| in_units(board, k) || (!fits(board, 1.0) && in_units(art, k))); + let styles = structure.styles_read; let (mut doc, notes) = build_from(structure, data, None, Page::Artboard, false, false, 1.0)?; if let Some(k) = scale { - // The graphic styles here are all the file's, drawn in its units too. - scale_document(&mut doc, k, true); + // The graphic styles read from the file are drawn in its units too. + scale_document(&mut doc, k, styles); + relayout_wrapped(&mut doc); } Ok((doc, notes)) } +/// A document read from the editing copy and its notes, or why it can't be read. +pub(super) type Built = Result<(Document, Vec), String>; + +/// [`build`] of a `.ai` without importing its PDF part, whose pages (each its trim box in points, +/// width and height) are `pages` and are in units of `unit` points: the document read from +/// `structure` (the editing copy `data` read) with nothing compared with the pages, when the file's +/// text document makes the type of every text object (at least one shows, and none is type that a +/// look draws), no object is unread or has another placement or drawn art that the page would +/// choose, and its artboards are the pages, one for one and of their size, in points or in the pages' +/// units ([`page_scale_alone`]). The document is drawn at that scale. Else `Err(structure)`, for +/// [`build_from`] with the page. +pub(super) fn build_without_page(structure: Structure, data: &[u8], pages: &[(f64, f64)], unit: f64) -> Result> { + let Some(scale) = page_scale_alone(&structure, pages, unit).filter(|_| nothing_waits_on_page(&structure) && type_all_made(&structure, data)) + else { + return Err(Box::new(structure)); + }; + let styles = structure.styles_read; + let built = build_from(structure, data, None, Page::Artboard, false, false, 1.0).map(|(mut doc, notes)| { + if scale != 1.0 { + // The graphic styles read from the file are drawn in its units too. + scale_document(&mut doc, scale, styles); + relayout_wrapped(&mut doc); + } + (doc, notes) + }); + Ok(built) +} + +/// Is nothing in `structure` waiting on the page: no object unread (the page's art takes its +/// place), no placed file with another placement, no live envelope with the drawn art it replaced +/// (the comparison with the page chooses between them)? +fn nothing_waits_on_page(structure: &Structure) -> bool { + structure.unread.is_empty() + && structure.unread_elsewhere.is_empty() + && structure.placed_elsewhere.is_empty() + && structure.envelopes_drawn.is_empty() +} + +/// Does the text document of `data` (read as `structure`) make the type of every text object, those +/// that don't show included, with at least one that shows, and none of them type that a look draws? +fn type_all_made(structure: &Structure, data: &[u8]) -> bool { + let mut infos = vec![]; + collect_slots(&structure.doc.layers, true, &mut infos); + if !infos.iter().any(|i| i.shown) || infos.iter().any(|i| i.look.is_some()) { + return false; + } + let frames = ai::text_frames(data); + for info in &mut infos { + info.art_path = info.story.and_then(|s| frames.get(&(s, info.frame))).map(|p| PathData::from_bezpath(&(structure.to_doc * p.clone()))); + } + let Some(texts) = Texts::read(data) else { return false }; + let mut read: std::collections::BTreeMap>> = Default::default(); + let stories: Vec>> = infos + .iter() + .map(|i| { + let n = i.story?; + read.entry(n).or_insert_with(|| texts.story(n as usize).map(Arc::new)).clone() + }) + .collect(); + // A slot without its story is made from nothing; past the text `build_from` reads, nothing is + // made either: it refuses the file. + if stories.iter().any(Option::is_none) || stories.iter().flatten().map(|s| s.len()).sum::() > MAX_TEXT { + return false; + } + let template = structure.template.map(|t| ((t[0] + t[2]) / 2.0, (t[1] + t[3]) / 2.0)); + make_slots(&infos, &stories, template, structure.to_doc, &mut vec![]).iter().all(Option::is_some) +} + +/// The scale at which the artboards of `structure` are the pages `pages` (each its width and height +/// in points), one for one and in order, each within half a point: 1 when they are in points, else +/// `unit` (the pages' `UserUnit`) when they are in those units, as [`page_scale`] finds it with the +/// page. `None` when they aren't the pages, and for a file that declares a large canvas scale (a +/// `.ai` saved without its PDF part reads one at that scale, [`super::ai_alone`]). +fn page_scale_alone(structure: &Structure, pages: &[(f64, f64)], unit: f64) -> Option { + let boards = &structure.doc.artboards; + if boards.is_empty() || boards.len() != pages.len() || structure.canvas_scale != 1.0 { + return None; + } + let fits = |k: f64| boards.iter().zip(pages).all(|(b, (w, h))| (b.rect.width() - w / k).abs() <= 0.5 && (b.rect.height() - h / k).abs() <= 0.5); + [1.0, unit].into_iter().find(|&k| k.is_finite() && k >= 1.0 && fits(k)) +} + /// [`build`] from `structure`, the editing copy `data` already read. pub(super) fn build_from( structure: Structure, diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index bb88aa1244..26cca96c0f 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -1,4 +1,4 @@ -use super::build::{PAGE_MOVE, Page, build, build_from, build_on_page}; +use super::build::{PAGE_MOVE, Page, build, build_from, build_on_page, build_without_page}; use super::slots::LAYERS_UNREAD; use super::{Affine, Arc, Cow, Document, Imported, Node, NodeKind, PathData, Rect, Vec2, ai}; @@ -110,11 +110,24 @@ fn layer_tree(nodes: &[Arc]) -> Vec> { /// units comes in `unit` times as large, and so does the artboard layout `place_pages` takes from /// it. pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outlined: bool, trust: bool, unit: f64) -> (Document, Vec, bool) { + layered_ai_from(AiLayers::decode(private), visible, warnings, outlined, trust, unit) +} + +/// [`layered_ai`] of the editing copy `layers`, as far as it was already decoded and read. +pub fn layered_ai_from( + layers: AiLayers, + visible: Document, + warnings: Vec, + outlined: bool, + trust: bool, + unit: f64, +) -> (Document, Vec, bool) { let unread = |mut all: Vec, why: &str| { all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let data = match ai::decode_private(private) { + let AiLayers { data, structure } = layers; + let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), }; @@ -137,7 +150,10 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl use_variables(&data, &mut visible, &mut all); (visible, all, false) }; - match build(&data, Some(&visible), Page::Artboard, outlined, trust, unit) { + let built = structure + .unwrap_or_else(|| ai::read(&data, false).map(Box::new)) + .and_then(|structure| build_from(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit)); + match built { // An image too large for the editing data's reader would be missing from the layers, while // the PDF part has it: the file comes in as its PDF part instead (#1479). Ok((_, notes)) if notes.iter().any(|n| n == ai::IMAGE_TOO_LARGE) => { @@ -153,6 +169,51 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec, outl } } +/// The `.ai` whose editing copy is `private` (as [`layered_ai`] takes it) from its layers alone, +/// without its PDF part, whose pages (each its trim box in points, width and height) are `pages` +/// and are in units of `unit` points (its first page's `UserUnit`): the document and the notes of +/// reading it, when the file's text document makes all of its type and nothing in its layers needs +/// the PDF part (see `build_without_page`). Nothing is compared with the PDF part. Else, as the +/// error, what was decoded and read of the editing copy, for [`layered_ai_from`] once the PDF part +/// is imported. +pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64) -> Result<(Document, Vec), AiLayers> { + let data = match ai::decode_private(private) { + Ok(data) => data, + Err(why) => return Err(AiLayers { data: Err(why), structure: None }), + }; + if !has_layers(&data) { + return Err(AiLayers { data: Ok(data), structure: None }); + } + let structure = match ai::read(&data, false) { + Ok(structure) => structure, + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)) }), + }; + match build_without_page(structure, &data, pages, unit) { + // An image too large for the editing data's reader is missing from the layers: the PDF + // part has it (as in `layered_ai`). + Ok(Ok((doc, notes))) if !notes.iter().any(|n| n == ai::IMAGE_TOO_LARGE) => Ok((doc, notes)), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)) }), + } +} + +/// A `.ai`'s editing copy decoded, and its layers read when they were, for [`layered_ai_from`]: +/// what [`ai_layers_alone`] read isn't decoded or read again. +pub struct AiLayers { + /// The editing copy decoded, or why it can't be. + data: Result, String>, + /// Its layers read with [`ai::read`] as [`layered_ai`] reads them, or why they can't be; `None` + /// when they are still to be read. + structure: Option, String>>, +} + +impl AiLayers { + /// The editing copy `private` (as [`layered_ai`] takes it), decoded. + pub fn decode(private: &[u8]) -> Self { + Self { data: ai::decode_private(private), structure: None } + } +} + /// `doc` (a file read as its page or PDF part, in place of its layers) with the variables, data /// sets, active data set and lock of the variable library of its editing data `data`, as [`build`] /// gives a document read from the layers, and the note about what of the library wasn't read diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 8fe04326c3..51d2447523 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -44,7 +44,8 @@ mod tiff; pub use ai_editing::{AiEditingOptions, AiEditingOutput, CREATOR_VERSION, export_ai_editing, private_data as ai_private_data}; pub use import::{ - Imported, POSTSCRIPT_ERRORS, ai_alone, ai_alone_on_page, family_style, import, import_trusting, import_with, is_loss, layered_ai, page, + 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 print::{PrintJob, PrintPage, print}; diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index 6bd298a078..66ff8b6e39 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -9,7 +9,7 @@ description = "VectorCraft PDF export and import" workspace = true [features] -# `vectorcraft_pdf::reads_of` for other crates' tests (dev-dependencies only). +# `vectorcraft_pdf::reads_of` and `imports_of` for other crates' tests (dev-dependencies only). read-count = [] [dependencies] diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index ff04da781d..6423578af1 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -38,6 +38,8 @@ mod state; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; +#[cfg(any(test, feature = "read-count"))] +pub use entry::imports_of; pub use entry::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 3f521c0265..687fcb1566 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -221,6 +221,16 @@ fn read_with_reader_options(bytes: &[u8], opts: &ImportOptions, reader: &craft_p read_opened(bytes, opts, reader, &original) } +/// How many times each buffer's pages have been imported, by its address (tests). +#[cfg(any(test, feature = "read-count"))] +static IMPORTS: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); + +/// How many times the pages of `bytes`, at its address, have been imported on any thread (tests). +#[cfg(any(test, feature = "read-count"))] +pub fn imports_of(bytes: &[u8]) -> usize { + IMPORTS.lock().ok().and_then(|i| i.get(&(bytes.as_ptr() as usize)).copied()).unwrap_or(0) +} + /// [`read_with_reader_options`] of `original`, the PDF `bytes` read with `reader`. fn read_opened( bytes: &[u8], @@ -228,6 +238,11 @@ fn read_opened( reader: &craft_pdf::OpenOptions, original: &craft_pdf::syntax::Pdf, ) -> Result { + #[cfg(any(test, feature = "read-count"))] + if let Ok(mut imports) = IMPORTS.lock() { + let n = imports.entry(bytes.as_ptr() as usize).or_default(); + *n = n.saturating_add(1); + } let picked = crate::pages::picked(opts, original.pages().len())?; let mut ocgs = Ocgs::read(original); let route = opts.layers && !ocgs.list.is_empty(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index d39fc0b95d..ca7e44ae7a 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -76,6 +76,8 @@ pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_w pub use encrypt::Encryption; pub use export::{export, export_with_report, page_areas}; pub use file_info::{FileInfo, file_info}; +#[cfg(any(test, feature = "read-count"))] +pub use import::imports_of; pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, @@ -83,8 +85,8 @@ pub use import::{ #[cfg(any(test, feature = "read-count"))] pub use pages::reads_of; pub use pages::{ - IllustratorData, Opened, PageInfo, PdfInfo, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, is_postscript, - open_pdf, + IllustratorData, Opened, PageInfo, PdfInfo, TrimPages, has_illustrator_data, illustrator_data, illustrator_data_without_pdf_part, info, + is_postscript, open_pdf, }; pub use piece_info::{PRIVATE_CHUNK, PrivateData}; pub use post::{THUMBNAIL_SIZE, Thumbnail}; diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index b5cee4b1bc..013d09f22d 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -280,6 +280,36 @@ impl Opened { pub fn page_count(&self) -> usize { self.pdf.pages().len() } + + /// The pages' trim boxes and bleed, as an import of every page on its trim box takes them, + /// without importing any page's art. + pub fn trim_pages(&self) -> TrimPages { + let pages = self.pdf.pages(); + let mut bleed = [0.0; 4]; + for page in pages.iter() { + for (side, b) in bleed.iter_mut().zip(self::bleed(page)) { + *side = f64::max(*side, b); + } + } + TrimPages { + sizes: pages.iter().map(|page| frame(page, CropTo::Trim).1).map(|r| (r.width(), r.height())).collect(), + user_unit: pages.first().map_or(1.0, |page| f64::from(page.user_unit())), + bleed, + } + } +} + +/// A PDF's pages as an import on their trim boxes sizes them ([`Opened::trim_pages`]). +#[derive(Clone, Debug, PartialEq)] +pub struct TrimPages { + /// Each page's trim box (its crop box when it has none) in points, rotated as the page shows: + /// width and height. + pub sizes: Vec<(f64, f64)>, + /// The size in points of a unit of the first page's user space (its `UserUnit`). + pub user_unit: f64, + /// The bleed of the pages, `[top, bottom, left, right]` in points: on each side, the widest + /// of the pages' bleed, as the import makes it the document's bleed. + pub bleed: [f64; 4], } /// Preserve the application's existing accepted file sizes. Ordinary stream decoding still diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 65e6de0bf8..c9039ea062 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -118,7 +118,7 @@ private editing data. VectorCraft: ### Illustrator's private editing data -the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. +the app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping, object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke or Convert to Shape comes in as itself with them and their saved settings; one with more, other effects, an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a brush or dashes aligned to corners comes in as its drawn look (a group named after it). The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. Type keeps its art style as a live appearance whatever its stack, so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its settings at their defaults) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). Symbols, pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068). A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. ## Format by format From 1348f827d0bc1d0005400d5265a4f2b965acb3bf Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:29:43 -0500 Subject: [PATCH 054/482] Area Type Options: applying to several frames keeps each frame's own options text.areaOptions given for several area type frames (ids, or a selection of several) copied the first frame's options onto all of them, so setting one option (say the vertical alignment) also replaced the others' columns, gutter, inset and fit. Each frame now takes only the options given over its own, and fit resolves against each frame's own setting, so fitMinPercent alone changes only frames that already shrink text to fit. Options that change nothing add no undo step and keep redo. --- crates/engine/src/cmd/typecmd.rs | 94 +++++++++++++-------- crates/engine/src/cmd/typecmd/area_tests.rs | 43 ++++++++++ crates/engine/src/tests/areafit.rs | 2 +- crates/engine/src/tests/typearea.rs | 22 +++++ docs/mcp.md | 5 ++ 5 files changed, 132 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index a24be32523..6656385a3b 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -87,7 +87,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options; width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), @@ -1080,46 +1080,74 @@ fn area_options(s: &mut Session, p: &Value) -> Result { let t = area_text(s.doc()?.doc.node(first)).ok_or_else(|| bad(C, "select area type (text in a frame)"))?; area_options_json(t) }; + // Checked once up front (its errors don't depend on the frame); each frame resolves `fit` + // against its own setting below. let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default(); - let fit = fit_param(p, cur.fit, C)?; - let mut v = serde_json::to_value(&cur).map_err(|e| EngineError::Other(e.to_string()))?; + fit_param(p, cur.fit, C)?; + let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null()); let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0)); - let (w, mut h) = (size("width"), size("height")); - let mut changed = w.is_some() || h.is_some() || fit.is_some(); - if let (Some(o), Some(src)) = (v.as_object_mut(), p.as_object()) { - for (k, val) in src.iter().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())) { - o.insert(k.clone(), val.clone()); - changed = true; - } - } - if !changed { + let (w, h) = (size("width"), size("height")); + let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect(); + if w.is_none() && h.is_none() && !fit_given && given.is_empty() { return options(s); } - let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?; - opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); - opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); - let finite = |x: f64| if x.is_finite() { x } else { 0.0 }; - opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0); - // A gutter given alone is the rows' and the columns'. - if p.get("gutter").is_some() && p.get("rowGutter").is_none() { - opts.row_gutter = None; - } - opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter); - opts.inset = finite(opts.inset).clamp(0.0, 10_000.0); - opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0); - opts.fit = fit.unwrap_or(cur.fit); - if opts.fit == AreaFit::AutoHeight { + // Each area type takes the options given over its own (#3759): setting one option on several + // frames leaves their other options as they were. + let merged = |own: &vectorcraft_doc::AreaOptions| -> Result { + let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?; + if let Some(o) = v.as_object_mut() { + for (k, val) in &given { + o.insert((*k).clone(), (*val).clone()); + } + } + let mut opts: vectorcraft_doc::AreaOptions = serde_json::from_value(v).map_err(|e| bad(C, e.to_string()))?; + opts.rows = opts.rows.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); + opts.columns = opts.columns.clamp(1, vectorcraft_doc::AreaOptions::MAX_ROWS_COLUMNS); + let finite = |x: f64| if x.is_finite() { x } else { 0.0 }; + opts.gutter = finite(opts.gutter).clamp(0.0, 10_000.0); + // A gutter given alone is the rows' and the columns'. + if p.get("gutter").is_some() && p.get("rowGutter").is_none() { + opts.row_gutter = None; + } + opts.row_gutter = opts.row_gutter.map(|g| finite(g).clamp(0.0, 10_000.0)).filter(|g| *g != opts.gutter); + opts.inset = finite(opts.inset).clamp(0.0, 10_000.0); + opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0); + // Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames). + opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit); + Ok(opts) + }; + let d = &s.doc()?.doc; + let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids + .iter() + .filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area))) + .map(|(id, own)| merged(own).map(|o| (id, o))) + .collect::>()?; + let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| { + t.area = opts.clone(); // Auto Size sets the height (Illustrator's dialog turns the Height field off). - h = None; + let h = if opts.fit == AreaFit::AutoHeight { None } else { h }; + // A resized frame has laid its text out again; otherwise the new options do here. + if !size_area(t, w, h) { + refresh_bounds(t); + } + }; + // Options that change nothing (the vertical alignment already set, `fitMinPercent` on frames + // without Shrink Text) add no undo step and keep redo, frame sizes and Auto Size included. + let unchanged = planned.iter().all(|(id, opts)| match d.node(*id).map(|n| &n.kind) { + Some(NodeKind::Text(t)) => { + let mut after = t.clone(); + apply(&mut after, opts); + after == *t + } + _ => true, + }); + if unchanged { + return options(s); } s.edit("Area Type Options", |d, _| { - for id in &ids { + for (id, opts) in &planned { if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { - t.area = opts.clone(); - // A resized frame has laid its text out again; otherwise the new options do here. - if !size_area(t, w, h) { - refresh_bounds(t); - } + apply(t, opts); } } Ok(()) diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index 20945f7702..4748dcc8d9 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -1762,3 +1762,46 @@ fn area_options_set_a_gutter_between_rows_of_its_own() { s.execute("text.areaOptions", &json!({"rowGutter": null})).unwrap(); assert_eq!(area(&s).row_gutter, None); } + +/// #3759: an option given for several area types goes onto each one's own options: the others +/// stay as each had them, not copied from the first. +#[test] +fn area_options_for_several_frames_change_only_what_is_given() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let make = |s: &mut Session, x: f64| { + s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (make(&mut s, 10.0), make(&mut s, 200.0)); + s.execute("text.areaOptions", &json!({"ids": [a], "columns": 3, "gutter": 6})).unwrap(); + s.execute("text.areaOptions", &json!({"ids": [b], "inset": 4})).unwrap(); + s.execute("text.areaOptions", &json!({"ids": [a, b], "verticalAlign": "bottom"})).unwrap(); + let area = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.area.clone(), + k => panic!("{k:?}"), + }; + let (oa, ob) = (area(&s, a), area(&s, b)); + assert_eq!((oa.vertical_align, ob.vertical_align), (vectorcraft_doc::VerticalAlign::Bottom, vectorcraft_doc::VerticalAlign::Bottom)); + assert_eq!((oa.columns, oa.gutter, oa.inset), (3, 6.0, 0.0)); + assert_eq!((ob.columns, ob.inset), (1, 4.0), "b keeps its own options"); +} + +/// `fitMinPercent` alone changes only the frames that shrink text to fit, each from its own +/// setting (#3759). +#[test] +fn fit_min_percent_for_several_frames_keeps_each_frames_fit() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let make = |s: &mut Session, x: f64| { + s.execute("text.create", &json!({"x": x, "y": 10, "text": "A", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap() + }; + let (plain, shrink) = (make(&mut s, 10.0), make(&mut s, 200.0)); + s.execute("text.areaOptions", &json!({"ids": [shrink], "fit": "shrinkText"})).unwrap(); + s.execute("text.areaOptions", &json!({"ids": [plain, shrink], "fitMinPercent": 30})).unwrap(); + let fit = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.area.fit, + k => panic!("{k:?}"), + }; + assert_eq!(fit(&s, plain), vectorcraft_doc::AreaFit::None, "the plain frame doesn't start shrinking"); + assert_eq!(fit(&s, shrink), vectorcraft_doc::AreaFit::ShrinkText { min_percent: 30.0 }); +} diff --git a/crates/engine/src/tests/areafit.rs b/crates/engine/src/tests/areafit.rs index 57182baf35..b6d6883430 100644 --- a/crates/engine/src/tests/areafit.rs +++ b/crates/engine/src/tests/areafit.rs @@ -77,7 +77,7 @@ fn area_options_set_and_report_the_fit() { let n = undo_len(&s); let again = s.execute("text.areaOptions", &q).unwrap(); assert_eq!(again, q); - assert_eq!(undo_len(&s), n + 1); + assert_eq!(undo_len(&s), n, "options that change nothing add no undo step"); // Undo back to no fit. while text(&s, id).area.fit != AreaFit::None { s.execute("edit.undo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/typearea.rs b/crates/engine/src/tests/typearea.rs index 623eaa5a42..9ada8b7194 100644 --- a/crates/engine/src/tests/typearea.rs +++ b/crates/engine/src/tests/typearea.rs @@ -508,3 +508,25 @@ fn area_type_options_set_the_text_flow() { assert_eq!((text(&s, id).area.flow, second(&s)), (TextFlow::Columns, (0.0, 160.0))); assert!(cmd::find_command("text.areaOptions").unwrap().params.contains("flow?: columns|rows")); } + +/// #3759: options that change nothing (the vertical alignment already set, or +/// `fitMinPercent` alone on a frame without Shrink Text) add no undo step and keep redo; a size +/// change with them still applies. +#[test] +fn unchanged_area_type_options_add_no_undo_step() { + let mut s = session(); + let id = area(&mut s, 40.0, 40.0, 200.0, 300.0, "Short story"); + sel(&mut s, &[id]); + s.execute("text.areaOptions", &json!({"verticalAlign": "bottom"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap(); + let n = undo_len(&s); + let before = text(&s, id); + s.execute("text.areaOptions", &json!({"verticalAlign": "center"})).unwrap(); + s.execute("text.areaOptions", &json!({"fitMinPercent": 40})).unwrap(); + assert_eq!(undo_len(&s), n, "no step for options already set"); + assert_eq!(text(&s, id), before); + // A real change still counts, and a new width with an unchanged option too. + s.execute("text.areaOptions", &json!({"verticalAlign": "center", "width": 180})).unwrap(); + assert_eq!(undo_len(&s), n + 1); +} diff --git a/docs/mcp.md b/docs/mcp.md index ea6d1dd371..a74c29ea02 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5021,6 +5021,11 @@ command also accepts that object form. The query (and every reply) of `text.area `document.inspect` (and `document.node {summary: true}`) reports `overflow` for area type and type on a path (text past the end of the path), and `fit` and `fitScale` for area type. +Given for several area types (`ids`, or a selection of several), `text.areaOptions` changes only the options given on +each one: each frame keeps its other options (it used to take the first frame's), and `fitMinPercent` alone changes only +the frames that already shrink text to fit. Options that change nothing (the vertical alignment already set, say) add +no undo step and keep redo. + Text that doesn't fit is drawn up to the last line that does, so a one-line headline in a frame lower than its line draws nothing. The commands that make type or change what it holds say so in their own reply: `text.create`, `text.createInPath`, `text.setText` and `text.setStyle` add `overflow: [id…]` (the area type and type on a path among From 2b10694f9923afbe75d8e91c77b08ca608bbc2f4 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:08:06 +0700 Subject: [PATCH 055/482] Fix #3759: vertical alignment buttons for area type in the Properties and Control panels Squashed from #5100 onto main. --- crates/ui-egui/src/chrome/control_bar.rs | 5 ++ 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/panels/properties.rs | 12 +++- crates/ui-egui/src/panels/properties/tests.rs | 68 +++++++++++++++++++ .../src/panels/properties/vertical_align.rs | 65 ++++++++++++++++++ docs/target-app-parity.md | 7 +- docs/ui-parity.md | 3 +- 32 files changed, 261 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/panels/properties/vertical_align.rs diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 1df1f08ab0..58e203b759 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -263,6 +263,11 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); crate::panels::character::control_bar(app, ui); + // Area type: its vertical alignment in the frame (#3759). + if crate::panels::properties::vertical_align::buttons(app, ui, 24.0) { + ui.add_space(4.0); + ui.separator(); + } if sel.is_empty() { if widgets::flat_button(ui, tl!("Document Setup"), 112.0).clicked() { app.run("file.documentSetup", json!({})).ok(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 4f7feb3ee0..ac5f629c19 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1597,6 +1597,10 @@ font-technology Variable Променливи Join Tool Инструмент „Свързване“ Justification… Подравняване… Justify all lines Двустранно подравняване на всички редове + Align Top Подравняване горе + Align Center Подравняване в средата + Align Bottom Подравняване долу + Justify Vertically Двустранно вертикално подравняване Justify with last line aligned center Двустранно подравняване с центриран последен ред Justify with last line aligned left Двустранно подравняване с ляво подравнен последен ред Justify with last line aligned right Двустранно подравняване с дясно подравнен последен ред diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index fa7f049f6c..c4280273c2 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -950,6 +950,10 @@ lighting Light Svjetlo Home Početna Import Keyboard Shortcuts… Uvezi prečice na tastaturi… Justify all lines Obostrano poravnaj sve redove + Align Top Poravnaj gore + Align Center Poravnaj u sredinu + Align Bottom Poravnaj dolje + Justify Vertically Obostrano poravnaj okomito Justify with last line aligned left Obostrano s posljednjim redom lijevo Keyboard Shortcut Conflicts Konflikti prečica na tastaturi Keyboard Shortcut Set Skup prečica na tastaturi diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 05d058dbcb..9d5ce938df 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2053,6 +2053,10 @@ digits Malayalam Malaiàlam Justification… Justificació… Justify Justifica Justify all lines Justifica totes les línies + Align Top Alinea a dalt + Align Center Alinea al mig + Align Bottom Alinea a baix + Justify Vertically Justifica verticalment Justify with last line aligned center Justifica amb l’última línia centrada Justify with last line aligned left Justifica amb l’última línia alineada a l’esquerra Justify with last line aligned right Justifica amb l’última línia alineada a la dreta diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 03c6020b8d..4a3fe56955 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -969,6 +969,10 @@ lighting Light Světlo Home Domů Import Keyboard Shortcuts… Importovat klávesové zkratky… Justify all lines Do bloku včetně posledního řádku + Align Top Zarovnat nahoru + Align Center Zarovnat svisle na střed + Align Bottom Zarovnat dolů + Justify Vertically Zarovnat svisle do bloku Justify with last line aligned left Do bloku, poslední řádek vlevo Keyboard Shortcut Conflicts Konflikty klávesových zkratek Keyboard Shortcut Set Sada klávesových zkratek diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 37cfc96474..b671f79d14 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -886,6 +886,10 @@ lighting Light Lys Home Home Import Keyboard Shortcuts… Importér tastaturgenveje… Justify all lines Justér alle linjer + Align Top Justér mod toppen + Align Center Justér lodret mod midten + Align Bottom Justér mod bunden + Justify Vertically Justér lodret Justify with last line aligned left Justér med sidste linje venstrejusteret Keyboard Shortcut Conflicts Konflikter mellem tastaturgenveje Keyboard Shortcut Set Tastaturgenvejssæt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9658d57295..f7c7faea08 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1642,6 +1642,10 @@ file-filter Templates Vorlagen Join Tool Zusammenfügen-Werkzeug Justification… Abstände… Justify all lines Blocksatz, alle Zeilen + Align Top Oben ausrichten + Align Center Mittig ausrichten + Align Bottom Unten ausrichten + Justify Vertically Vertikaler Blocksatz Justify with last line aligned center Blocksatz, letzte Zeile zentriert Justify with last line aligned left Blocksatz, letzte Zeile linksbündig Justify with last line aligned right Blocksatz, letzte Zeile rechtsbündig diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index eca62bdb96..445720603a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1561,6 +1561,10 @@ font-technology Variable Μεταβλητές Join Tool Ένωση (Join Tool) Justification… Πλήρης στοίχιση… Justify all lines Πλήρης στοίχιση όλων των γραμμών + Align Top Στοίχιση επάνω + Align Center Στοίχιση στη μέση + Align Bottom Στοίχιση κάτω + Justify Vertically Κατακόρυφη πλήρης στοίχιση Justify with last line aligned center Πλήρης στοίχιση με τελευταία γραμμή στο κέντρο Justify with last line aligned left Πλήρης στοίχιση με τελευταία γραμμή αριστερά Justify with last line aligned right Πλήρης στοίχιση με τελευταία γραμμή δεξιά diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index e739c742c2..c6950dae52 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1647,6 +1647,10 @@ font-technology Variable Variables Join Tool Herramienta Unir Justification… Justificación… Justify all lines Justificar todas las líneas + Align Top Alinear arriba + Align Center Alinear en el medio + Align Bottom Alinear abajo + Justify Vertically Justificar verticalmente Justify with last line aligned center Justificar con la última línea centrada Justify with last line aligned left Justificar con la última línea alineada a la izquierda Justify with last line aligned right Justificar con la última línea alineada a la derecha diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index e277504979..ae6d114bbb 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -948,6 +948,10 @@ lighting Light Valo Home Aloitus Import Keyboard Shortcuts… Tuo pikanäppäimet… Justify all lines Tasaa kaikki rivit + Align Top Tasaa ylös + Align Center Tasaa pystysuunnassa keskelle + Align Bottom Tasaa alas + Justify Vertically Tasaa pystysuunnassa Justify with last line aligned left Tasaa, viimeinen rivi vasemmalle Keyboard Shortcut Conflicts Pikanäppäinristiriidat Keyboard Shortcut Set Pikanäppäinjoukko diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index bac0097a6a..3caae7f683 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1641,6 +1641,10 @@ font-technology Variable Variables Join Tool Outil Jonction Justification… Justification… Justify all lines Justifier toutes les lignes + Align Top Aligner en haut + Align Center Aligner au milieu + Align Bottom Aligner en bas + Justify Vertically Justifier verticalement Justify with last line aligned center Justifier, dernière ligne centrée Justify with last line aligned left Justifier, dernière ligne alignée à gauche Justify with last line aligned right Justifier, dernière ligne alignée à droite diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 225fa709f2..3bc6b98619 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2074,6 +2074,10 @@ file-filter Templates Sablonok Justification… Sorkizárás… Justify Sorkizárt Justify all lines Sorkizárás minden sorra + Align Top Igazítás felülre + Align Center Igazítás függőlegesen középre + Align Bottom Igazítás alulra + Justify Vertically Függőleges sorkizárás Justify with last line aligned center Sorkizárás, utolsó sor középre Justify with last line aligned left Sorkizárás, utolsó sor balra Justify with last line aligned right Sorkizárás, utolsó sor jobbra diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index d0d09e8390..7948e08ba4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -886,6 +886,10 @@ lighting Light Cahaya Home Home Import Keyboard Shortcuts… Impor pintasan papan ketik… Justify all lines Ratakan semua baris + Align Top Sejajarkan ke atas + Align Center Sejajarkan ke tengah vertikal + Align Bottom Sejajarkan ke bawah + Justify Vertically Ratakan vertikal Justify with last line aligned left Ratakan dengan baris terakhir rata kiri Keyboard Shortcut Conflicts Konflik pintasan papan ketik Keyboard Shortcut Set Set pintasan papan ketik diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a4a7d547a0..5a11b455e1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1674,6 +1674,10 @@ file-filter Templates Modelli Join Tool Strumento Unisci Justification… Giustificazione… Justify all lines Giustifica tutte le righe + Align Top Allinea in alto + Align Center Allinea al centro verticalmente + Align Bottom Allinea in basso + Justify Vertically Giustifica verticalmente Justify with last line aligned center Giustifica con l'ultima riga centrata Justify with last line aligned left Giustifica con l'ultima riga allineata a sinistra Justify with last line aligned right Giustifica con l'ultima riga allineata a destra diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 3d04b70ce5..178aaef86f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3598,6 +3598,10 @@ file-filter Templates テンプレート Installed plug-in {} プラグイン {} をインストールしました Internal CSS 内部 CSS Justify all lines 両端揃え (最終行も均等配置) + Align Top 上揃え + Align Center 上下中央揃え + Align Bottom 下揃え + Justify Vertically 縦方向に均等配置 Justify with last line aligned center 両端揃え (最終行中央揃え) Justify with last line aligned left 両端揃え (最終行左揃え) Justify with last line aligned right 両端揃え (最終行右揃え) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index d0c69c179d..0d806a2205 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -836,6 +836,10 @@ lighting Light სინათლე Home საწყისი ეკრანი Import Keyboard Shortcuts… კლავიატურის მალსახმობების იმპორტირება… Justify all lines ყველა სტრიქონის ორმხრივი სწორება + Align Top ზემოთ სწორება + Align Center შუაში სწორება + Align Bottom ქვემოთ სწორება + Justify Vertically ვერტიკალური ორმხრივი სწორება Justify with last line aligned left ორმხრივი სწორება, ბოლო სტრიქონი მარცხნივ Keyboard Shortcut Conflicts კლავიატურის მალსახმობების კონფლიქტები Keyboard Shortcut Set კლავიატურის მალსახმობების ნაკრები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 926896ebb8..a216b40368 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3586,6 +3586,10 @@ file-filter Templates 템플릿 Installed plug-in {} 플러그인 {}을(를) 설치했습니다 Internal CSS 내부 CSS Justify all lines 모든 줄 양끝 맞춤 + Align Top 위쪽 정렬 + Align Center 세로 가운데 정렬 + Align Bottom 아래쪽 정렬 + Justify Vertically 세로 양끝 맞춤 Justify with last line aligned center 마지막 줄 가운데 정렬 양끝 맞춤 Justify with last line aligned left 마지막 줄 왼쪽 정렬 양끝 맞춤 Justify with last line aligned right 마지막 줄 오른쪽 정렬 양끝 맞춤 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 8e23b89e8d..3e15af341a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -900,6 +900,10 @@ lighting Light Licht Home Home Import Keyboard Shortcuts… Sneltoetsen importeren… Justify all lines Alle regels uitvullen + Align Top Boven uitlijnen + Align Center Midden uitlijnen + Align Bottom Onder uitlijnen + Justify Vertically Verticaal uitvullen Justify with last line aligned left Uitvullen met laatste regel links uitgelijnd Keyboard Shortcut Conflicts Sneltoetsconflicten Keyboard Shortcut Set Sneltoetsset diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6fd390d6d9..cc5d041e7f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -906,6 +906,10 @@ lighting Light Światło Home Strona startowa Import Keyboard Shortcuts… Importuj skróty klawiaturowe… Justify all lines Justuj wszystkie wiersze + Align Top Wyrównaj do góry + Align Center Wyrównaj pionowo do środka + Align Bottom Wyrównaj do dołu + Justify Vertically Justuj w pionie Justify with last line aligned left Justuj z ostatnim wierszem do lewej Keyboard Shortcut Conflicts Konflikty skrótów klawiaturowych Keyboard Shortcut Set Zestaw skrótów klawiaturowych diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 331edd6bc1..0921b0c728 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4590,6 +4590,10 @@ axis Both Ambos Installed plug-in {} Plug-in {} instalado Internal CSS CSS Interno Justify all lines Justificar Todas as Linhas + Align Top Alinhar em Cima + Align Center Alinhar ao Meio + Align Bottom Alinhar em Baixo + Justify Vertically Justificar Verticalmente Justify with last line aligned center Justificar com Última Linha Centralizada Justify with last line aligned left Justificar com Última Linha à Esquerda Justify with last line aligned right Justificar com Última Linha à Direita diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 654e0a1435..f620e86595 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1671,6 +1671,10 @@ file-filter Templates Шаблоны Join Tool Инструмент «Соединение» Justification… Выключка… Justify all lines Выключить все строки + Align Top Выровнять по верху + Align Center Выровнять по середине + Align Bottom Выровнять по низу + Justify Vertically Выключка по вертикали Justify with last line aligned center Выключить с последней строкой по центру Justify with last line aligned left Выключить с последней строкой по левому краю Justify with last line aligned right Выключить с последней строкой по правому краю diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 58a91b8884..23a96006a0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1603,6 +1603,10 @@ font-technology Variable Variabla Join Tool Sammanfogningsverktyg Justification… Justering… Justify all lines Marginaljustera alla rader + Align Top Justera överkant + Align Center Centrera vertikalt + Align Bottom Justera nederkant + Justify Vertically Marginaljustera vertikalt Justify with last line aligned center Marginaljustera med sista raden centrerad Justify with last line aligned left Marginaljustera med sista raden vänsterjusterad Justify with last line aligned right Marginaljustera med sista raden högerjusterad diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 5f41a51986..e16c913b71 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1485,6 +1485,10 @@ font-technology Variable Değişken Join Tool Birleştirme Aracı Justification… İki Yana Yaslama… Justify all lines Tüm satırları iki yana yasla + Align Top Üste hizala + Align Center Dikey ortala + Align Bottom Alta hizala + Justify Vertically Dikey olarak iki yana yasla Justify with last line aligned center Son satıra hizalanmış merkeze yasla Justify with last line aligned left Son satırı sola hizalanmış şekilde iki yana yasla Justify with last line aligned right Son satırı sağa hizalayarak yasla diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ad511f3ed5..49dd42a05c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1668,6 +1668,10 @@ file-filter Templates Шаблони Join Tool Інструмент «З’єднання» Justification… Вирівнювання за шириною… Justify all lines Вирівняти всі рядки за шириною + Align Top Вирівняти по верху + Align Center Вирівняти по середині + Align Bottom Вирівняти по низу + Justify Vertically Вирівняти по вертикалі за висотою Justify with last line aligned center Вирівняти за шириною, останній рядок — по центру Justify with last line aligned left Вирівняти за шириною, останній рядок — ліворуч Justify with last line aligned right Вирівняти за шириною, останній рядок — праворуч diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index fb24f7d044..0bfce04b8f 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1955,6 +1955,10 @@ digits Hindi Hindi Joins Kiểu nối Justification… Căn đều… Justify all lines Căn đều tất cả dòng + Align Top Căn trên + Align Center Căn giữa theo chiều dọc + Align Bottom Căn dưới + Justify Vertically Căn đều theo chiều dọc Justify with last line aligned center Căn đều, dòng cuối giữa Justify with last line aligned left Căn đều, dòng cuối trái Justify with last line aligned right Căn đều, dòng cuối phải diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index bf2a49b374..e70d78656c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1599,6 +1599,10 @@ file-filter Templates 模板 Join Tool 连接工具 Justification… 对齐设置… Justify all lines 全部两端对齐 + Align Top 顶对齐 + Align Center 垂直居中对齐 + Align Bottom 底对齐 + Justify Vertically 垂直两端对齐 Justify with last line aligned center 两端对齐,末行居中 Justify with last line aligned left 两端对齐,末行左对齐 Justify with last line aligned right 两端对齐,末行右对齐 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 5f48b43071..b4a60cc3bd 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1638,6 +1638,10 @@ file-filter Templates 範本 Join Tool 連接工具 Justification… 對齊設定… Justify all lines 兩端對齊所有行 + Align Top 靠上對齊 + Align Center 垂直置中對齊 + Align Bottom 靠下對齊 + Justify Vertically 垂直齊行 Justify with last line aligned center 兩端對齊,最後一行置中 Justify with last line aligned left 兩端對齊,最後一行靠左 Justify with last line aligned right 兩端對齊,最後一行靠右 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index b775dc05ae..b8a42e9285 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1004,7 +1004,8 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { super::character::variable_font(app, ui, &s, w - 4.0); super::character::metrics_grid(app, ui, "props-char", &s, w, false); section_header(ui, tl!("Paragraph")); - // As in the Paragraph panel: the seven alignments and Hyphenate (#775); the rest is there. + // As in the Paragraph panel: the seven alignments and Hyphenate (#775), and area type's + // vertical alignment (#3759); the rest is there. if let Some((_, para)) = super::character::text_style(app) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 3.0; @@ -1013,9 +1014,18 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { app.ui.open_panel = Some("paragraph".into()); } }); + // Area type: its vertical alignment in the frame (#3759). + if vertical_align::shown(app).is_some() { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 3.0; + vertical_align::buttons(app, ui, 24.0); + }); + } super::paragraph::hyphenate_check(app, ui, ¶); } } +pub(crate) mod vertical_align; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 1a38e4f707..30ac3cd455 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1792,3 +1792,71 @@ fn objects_on_path_options_set_pivot_and_rotate_in_one_undo_step() { assert_eq!((pivot_rotate(&app, &group), pivot_rotate(&app, &other)), ((8, 30.0), (8, 45.0)), "both groups' Pivot"); assert_eq!(undo_depth(&app), depth + 1, "one undo step for both groups"); } + +/// #3759: with area type selected, the Properties panel's Paragraph section shows Align Top, Align +/// Center, Align Bottom and Justify Vertically; a click sets the alignment on every selected frame +/// in one undo step. Point type shows none; frames with rows or columns and threaded frames turn +/// the buttons off, as the public documentation limits vertical alignment to them. +#[test] +fn vertical_alignment_buttons_align_the_selected_area_type() { + use vectorcraft_doc::{NodeId, VerticalAlign}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + let make = |app: &mut VectorcraftApp, x: f64, y: f64| { + app.run("text.create", json!({"x": x, "y": y, "text": "Panel", "area": {"width": 100, "height": 120}})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (make(&mut app, 10.0, 10.0), make(&mut app, 200.0, 10.0)); + let point = app.run("text.create", json!({"x": 10, "y": 350, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + let align = |app: &VectorcraftApp, id: u64| match &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => t.area.vertical_align, + k => panic!("{k:?}"), + }; + app.run("select.set", json!({"ids": [point]})).unwrap(); + assert_eq!(vertical_align::shown(&app), None, "point type: no buttons"); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + assert_eq!(vertical_align::shown(&app), Some(vertical_align::Shown { shared: Some(VerticalAlign::Top), enabled: true })); + // The buttons sit in the panel's Paragraph section: click Align Center (the second). + let ctx = egui::Context::default(); + let mut row = Rect::NOTHING; + let draw = |app: &mut VectorcraftApp, ui: &mut Ui, row: &mut Rect| { + *row = ui + .horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 3.0; + vertical_align::buttons(app, ui, 24.0); + }) + .response + .rect; + }; + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| draw(&mut app, ui, &mut row)); + out.textures_delta.clear(); + let texts = panel_frame(&mut app, &ctx, vec![], type_sections); + assert!(texts.iter().any(|(t, _)| t == "Paragraph"), "{texts:?}"); + let undo = app.session.active().unwrap().history.undo.len(); + let center = row.min + vec2(12.0 + 27.0, 12.0); + super::super::tests_appearance::click(&ctx, &mut app, center, |app, ui| { + let mut r = Rect::NOTHING; + draw(app, ui, &mut r); + }); + assert_eq!((align(&app, a), align(&app, b)), (VerticalAlign::Center, VerticalAlign::Center)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "one undo step for both frames"); + // Differing alignments show none selected. + app.run("text.areaOptions", json!({"ids": [b], "verticalAlign": "bottom"})).unwrap(); + assert_eq!(vertical_align::shown(&app).map(|s| s.shared), Some(None)); + // Columns turn the buttons off, and a click does nothing. + app.run("text.areaOptions", json!({"ids": [b], "columns": 2})).unwrap(); + assert_eq!(vertical_align::shown(&app).map(|s| s.enabled), Some(false)); + let undo = app.session.active().unwrap().history.undo.len(); + super::super::tests_appearance::click(&ctx, &mut app, center, |app, ui| { + let mut r = Rect::NOTHING; + draw(app, ui, &mut r); + }); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo, "turned off: no change"); + assert_eq!(align(&app, a), VerticalAlign::Center); + // So does threading: a and c threaded, b left out of the selection. + let c = make(&mut app, 10.0, 200.0); + app.run("select.set", json!({"ids": [a, c]})).unwrap(); + assert_eq!(vertical_align::shown(&app).map(|s| s.enabled), Some(true)); + app.run("text.thread.create", json!({})).unwrap(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(vertical_align::shown(&app).map(|s| s.enabled), Some(false)); +} diff --git a/crates/ui-egui/src/panels/properties/vertical_align.rs b/crates/ui-egui/src/panels/properties/vertical_align.rs new file mode 100644 index 0000000000..bf2fef4a05 --- /dev/null +++ b/crates/ui-egui/src/panels/properties/vertical_align.rs @@ -0,0 +1,65 @@ +//! Area type's vertical alignment in its frame (#3759): the Align Top, Align Center, Align Bottom +//! and Justify Vertically buttons of the Properties panel's Paragraph section and of the Control +//! panel. Per the public documentation they align area type with one row and one column that isn't +//! threaded ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html)), +//! so they are turned off when a selected frame has rows or columns or is threaded. + +use egui::Ui; +use serde_json::json; +use vectorcraft_doc::{NodeKind, TextKind, VerticalAlign}; + +use crate::VectorcraftApp; +use crate::widgets; + +/// The vertical alignment the selected area type shows, and whether the buttons can change it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Shown { + /// The alignment every selected frame shares; `None` when they differ. + pub(crate) shared: Option, + /// Every selected frame has one row and one column and isn't threaded. + pub(crate) enabled: bool, +} + +/// The vertical alignment of the selected area type (and area type in selected groups, the frames +/// `text.areaOptions` changes); `None` when no area type is selected. +pub(crate) fn shown(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let threaded = |id| st.doc.text_threads.iter().any(|t| t.len() > 1 && t.contains(&id)); + let mut out: Option = None; + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + let NodeKind::Text(t) = &c.kind else { return }; + if !matches!(t.kind, TextKind::Area { .. }) { + return; + } + let a = t.area.vertical_align; + let plain = t.area.rows <= 1 && t.area.columns <= 1 && !threaded(c.id); + out = Some(match out { + None => Shown { shared: Some(a), enabled: plain }, + Some(s) => Shown { shared: s.shared.filter(|b| *b == a), enabled: s.enabled && plain }, + }); + }); + } + out +} + +/// The four buttons for the selected area type: the shared alignment shows selected; a click sets +/// it on every selected frame in one undo step (`text.areaOptions {verticalAlign}`, as Area Type +/// Options does, each frame keeping its other options). Turned off for frames with rows or columns +/// and threaded ones; nothing shows without area type. Returns whether the buttons were drawn. +pub(crate) fn buttons(app: &mut VectorcraftApp, ui: &mut Ui, size: f32) -> bool { + let Some(s) = shown(app) else { return false }; + for (a, icon, tip, id) in [ + (VerticalAlign::Top, "dc-al-top", tl!("Align Top"), "top"), + (VerticalAlign::Center, "dc-al-vcenter", tl!("Align Center"), "center"), + (VerticalAlign::Bottom, "dc-al-bottom", tl!("Align Bottom"), "bottom"), + (VerticalAlign::Justify, "dc-dist-vcenter", tl!("Justify Vertically"), "justify"), + ] { + if widgets::icon_button_enabled(ui, icon, tip, s.enabled && s.shared == Some(a), s.enabled, size).clicked() + && let Err(e) = app.run("text.areaOptions", json!({ "verticalAlign": id })) + { + app.status(e); + } + } + true +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 534aff2069..adcdb060a4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (Object › Expand turns symbol instances into their art; 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-04 · **Change:** minor (area type vertical alignment in the Properties and Control panels, #3759; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence @@ -1589,10 +1589,15 @@ While a corner widget is pressed or dragged with the Selection or Direct Selecti A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool enters isolation mode on it ([isolate objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html): a double-click with the Selection tool isolates an object; [repeat patterns overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/repeat-patterns-overview.html): every instance follows edits to the original object); there the source art is selected and edited as usual (a double-click on type in it switches to the Type tool on that text) and every copy follows, with the repeat's settings kept (#5054). Test: `tests::repeat_edit::a_double_click_on_a_repeat_isolates_it_to_edit_its_text`. +## Area type: vertical alignment in the Properties and Control panels (2026-11-04) + +With area type selected, the Properties panel's Paragraph section and the Control panel show Align Top, Align Center, Align Bottom and Justify Vertically buttons, as the public documentation places them ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html)). They set the type's vertical alignment in its frame (`text.areaOptions {verticalAlign}`, as Area Type Options does) on every selected frame in one undo step, each frame keeping its other options; the shared alignment shows selected, none when the frames differ (#3759). As that page limits vertical alignment to area type without rows, columns or threads, the buttons are turned off while a selected frame has rows or columns or is threaded; Area Type Options and `text.areaOptions` still align each row/column cell (a VectorCraft extension, unchanged here). Tests: `panels::properties::tests::vertical_alignment_buttons_align_the_selected_area_type`. + ## Revision history | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | | 2026-11-03 | minor | Find Font's replacement-source chooser offers Document, Recent and System (#5217); scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b1f034cdaa..a51fdd99d1 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-03 · **Change:** minor (Type on a Path Options has a Preview checkbox, #5360; the Action Options row cites the public Actions panel page; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (area type vertical alignment buttons in the Properties and Control panels, turned off for rows, columns and threads, #3759; 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) ## Feature submission evidence @@ -420,6 +420,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | Area type: Align Top / Center / Bottom / Justify Vertically buttons in the Properties panel (Paragraph section) and the Control panel set its vertical alignment in the frame, as Area Type Options does; turned off for frames with rows or columns and threaded frames (#3759); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control accept the wheel without opening the menu (#5253); scores and estimates unchanged. | From ac0ca081bb0f443cc82ab98a5d4c026bf20a591e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 20:08:42 +0700 Subject: [PATCH 056/482] Commands: a color param with an alpha part is refused instead of losing its alpha Squashed from #5603 onto main. --- crates/engine/src/cmd.rs | 20 ++++++++- crates/engine/src/cmd/addons/color.rs | 2 +- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/symbols.rs | 4 +- crates/engine/src/cmd/buildcmds.rs | 2 +- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/engine/src/cmd/colormgmt.rs | 8 ++-- crates/engine/src/cmd/colortheme.rs | 2 +- crates/engine/src/cmd/create.rs | 3 +- crates/engine/src/cmd/docsetup.rs | 2 +- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/freeform.rs | 4 +- crates/engine/src/cmd/gradient.rs | 2 +- crates/engine/src/cmd/halftone.rs | 2 +- crates/engine/src/cmd/layer.rs | 4 +- crates/engine/src/cmd/library.rs | 2 +- crates/engine/src/cmd/live.rs | 2 +- crates/engine/src/cmd/live/commands.rs | 4 +- crates/engine/src/cmd/live/mesh.rs | 6 +-- crates/engine/src/cmd/menucmds.rs | 2 +- crates/engine/src/cmd/paint.rs | 2 +- crates/engine/src/cmd/recolor.rs | 7 ++-- crates/engine/src/cmd/select.rs | 2 +- crates/engine/src/cmd/slices.rs | 3 +- crates/engine/src/cmd/swatch.rs | 11 ++--- crates/engine/src/cmd/textedit.rs | 3 +- crates/engine/src/cmd/typecmd.rs | 2 +- crates/engine/src/cmd/webexport.rs | 3 +- crates/engine/src/cmd/xform.rs | 2 +- crates/engine/src/tests/brushsym.rs | 20 +++++++++ crates/engine/src/tests/colormgmt.rs | 4 ++ crates/engine/src/tests/live.rs | 22 ++++++++++ crates/engine/src/tests/menucmds.rs | 2 + crates/engine/src/tests/panelcmds.rs | 50 +++++++++++++++++++++++ crates/engine/src/tests/recolor.rs | 6 +++ crates/engine/src/tests/slices.rs | 2 + crates/engine/src/tests/webexport.rs | 2 + docs/mcp.md | 10 +++-- docs/target-app-parity.md | 1 + 39 files changed, 186 insertions(+), 47 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 1af3693ca5..85689bf707 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -484,9 +484,10 @@ pub fn matrix_param(p: &Value, key: &str) -> Option { } /// A colour from `"#rrggbb"`, a colour key (`"cmyk 0 100 100 0"`, `"lab 55 60 40"`), `[r,g,b]` (0..1), /// `{"c":..,"m":..,"y":..,"k":..}` (percent when any component is above 1, else 0..1), `{"gray":..}` or `{"l":..,"a":..,"b":..}` (CIE Lab: L 0..100, a and b about -/// −128..127). +/// −128..127). `None` for a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without the `#`). pub fn color_value(v: &Value) -> Option { match v { + Value::String(s) if hex_with_alpha(s) => None, // A hex, or a colour key ("cmyk 0 100 100 0", as Recolor Artwork lists colours). Value::String(s) => Color::from_hex(s).or_else(|| vectorcraft_color::recolor::ColorKey::parse(s).map(|k| k.color())), Value::Array(a) if a.len() >= 3 => Some(Color::rgb(a[0].as_f64()? as f32, a[1].as_f64()? as f32, a[2].as_f64()? as f32)), @@ -512,6 +513,23 @@ pub fn color_value(v: &Value) -> Option { } } +/// Is `s` a hex color with an alpha part: eight or four hex digits, with or without the `#`? +/// [`Color::from_hex`] reads `#rrggbbaa` as `#rrggbb`, without the alpha. +pub(crate) fn hex_with_alpha(s: &str) -> bool { + let s = s.trim(); + let h = s.strip_prefix('#').unwrap_or(s); + matches!(h.len(), 4 | 8) && h.chars().all(|c| c.is_ascii_hexdigit()) +} + +/// The color `p` gives for `key`, read by [`color_value`]: `None` when `p` leaves it out or gives +/// null. Any other value that is not a color is an error: "bad color {v}". +pub(crate) fn color_param(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + None => Ok(None), + Some(v) => color_value(v).map(Some).ok_or_else(|| bad(cmd, format!("bad color {v}"))), + } +} + /// `v` as an object id: an error unless it is a non-negative integer. fn object_id(v: &Value) -> Result { v.as_u64().map(NodeId).ok_or_else(|| EngineError::Other(format!("object ids are non-negative integers, not {v}"))) diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index d1ed6c84a7..ac8947cb4a 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -59,7 +59,7 @@ pub fn specs() -> Vec { "Find Nearest Swatch", ["Object", "Plug-ins", "Color Effects"], None, - "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", + "{library?: a swatch library's id or name (swatch.library.list: the built-in ones, and the colour books and libraries the user saved or loaded) or \"document\" (the document's swatches; the default), color?: colour (look this colour up, #rrggbbaa and #rgba refused; default: the selection's), fill?: true, stroke?: true (the selected objects' fills and strokes, their type's and those of the objects inside them: solid colours and gradient stops, once each, the first 100), count?: 1..50 (5), ids?: [id…] (default: the selection)} list the library's colour swatches closest to each colour, closest first, by CIEDE2000 difference (ΔE; under 1 hardly tells apart, about 2 to 3 close). Tint swatches, None and Registration aren't matched → {library, colors: [{values, hex, matches: [{name, values, hex, spot, deltaE}]}]}", has_doc, nearest::find ), diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index f5da40e7b4..a6505a057b 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -19,7 +19,7 @@ use super::edit::{outermost, selected_roots}; use super::pathops::{remove_each, separate}; use super::swatch::{anchor, names_param}; use super::{ - CommandSpec, Result, Session, bad, check_numbers, cmd, color_value, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok, + CommandSpec, Result, Session, bad, check_numbers, cmd, color_param, find_command, has_doc, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, }; use crate::EngineError; @@ -304,7 +304,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color?, keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y]…], radius?: 40, intensity?: 1..10 (5), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 3bc167ffa1..77a61c58a4 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -1,7 +1,7 @@ use super::dynamic::{fit_overrides, type_id, type_param}; use super::{ Affine, AppearanceItem, Arc, CURRENT_SYMBOL, Color, Document, EngineError, FillLayer, HALF, Node, NodeId, NodeKind, Paint, Point, Result, - SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_value, ids_json, json, + SIZES_KEY, Session, Symbol, SymbolExportType, SymbolNineSlice, SymbolRegistration, Value, Vec2, bad, brush, color_param, ids_json, json, name_param, number_or, ok, remove_each, roots, selection_art, separate, set_unknown, str_param, switch_or, }; @@ -834,7 +834,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let intensity = number_or(p, "intensity", 5.0, C)?.clamp(1.0, 10.0) / 10.0; let alt = switch_or(p, "alt", false, C)?; let st = s.doc()?; - let color = match p.get("color").and_then(color_value) { + let color = match color_param(p, "color", C)? { Some(c) => crate::cmd::paint::new_color(s, p, c), None => s.paint.fill.color().unwrap_or(Color::BLACK), }; diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 829c3af5df..442b68c583 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec { "Live Paint Bucket", [], None, - "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", + "{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}", has_doc, lp_fill ), diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 4ab859740b..d70a81700f 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -116,7 +116,7 @@ pub fn specs() -> Vec { "Color Guide", [], None, - "{color, rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}", + "{color (#rrggbbaa and #rgba are refused), rule: complementary|complementary2|splitComplementary|leftComplement|rightComplement|analogous|analogous2|monochromatic|shades|triad|triad2|triad3|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast2|highContrast3|pentagram (or its label), steps?: 1..20 (4), variation?: \"tintsShades\"|\"warmCool\"|\"vividMuted\", amount?: 0..100 (50; how far the outermost steps go), limitTo?: swatch library id or name; or \"document\" (the document's swatches): every colour snaps to its nearest colour there (ΔE 2000)} the Color Guide for a base colour → {rule, colors: [\"#rrggbb\", the base first], grid: [per colour, 2·steps+1 variations from shades/cool/muted to tints/warm/vivid with the colour itself in the centre]}", always, harmony ), diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index f03b66a925..9842cfbe96 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color, to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", always, convert_color ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "Gamut Warning", [], None, - "{ids?|id?, colors?: [color]} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", + "{ids?|id?, colors?: [color] (#rrggbbaa and #rgba are refused)} colours that can't be printed in the working CMYK (selection, or the whole document when nothing is selected) → {checked, outOfGamut: [{hex, deltaE, count}]}", has_doc, gamut_check ), @@ -675,7 +675,9 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { fn gamut_check(s: &mut Session, p: &Value) -> Result { let mut cols: Vec = vec![]; if let Some(a) = p.get("colors").and_then(Value::as_array) { - cols.extend(a.iter().filter_map(color_value)); + for v in a { + cols.push(color_value(v).ok_or_else(|| bad("color.gamutCheck", format!("bad color {v}")))?); + } } else { let st = s.doc()?; let ids = targets(s, p)?; diff --git a/crates/engine/src/cmd/colortheme.rs b/crates/engine/src/cmd/colortheme.rs index 9321fc12bc..b61432aea1 100644 --- a/crates/engine/src/cmd/colortheme.rs +++ b/crates/engine/src/cmd/colortheme.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Save Theme", ["Window", "Color Themes"], None, - "{colors: [1–5 colours] | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}", + "{colors: [1–5 colours] (#rrggbbaa and #rgba are refused) | color + rule (a harmony rule id or label, see color.harmony: its 5-colour theme from that base colour, base first), rule?: the rule it was made with, name?: (default \"Theme N\"), replace?: a saved theme's name (overwrite that theme in place, e.g. after editing it; it may be renamed), color?: one colour (as colors: [colour])} save a colour theme to the local theme library (the preferences) → {name, count: themes saved}", always, save ), diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 65a6ee0c37..00ea88ea64 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -706,6 +706,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result { super::paint::check_keep_model(p, "text.create")?; check_numbers(p, &["size"], "text.create")?; check_switches(p, &["vertical", "placeholder"], "text.create")?; + super::color_param(p, "color", "text.create")?; if let Some(a) = p.get("area") { check_numbers(a, &["width", "height"], "text.create")?; } diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index f5cb1d6b72..894d9b90ae 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "Document Setup", [], None, - "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", + "{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup", has_doc, setup )] diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index f269f0fc0f..5b734c5a26 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in their layers), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; SVG has it as an SVG option), ppi?: 72 (raster formats: pixels per inch, stored in the file; wins over scale), scale?: 1 (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. Never changes the document's path", has_doc, export::export ), diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs index ac04dc94c2..21b5245aef 100644 --- a/crates/engine/src/cmd/freeform.rs +++ b/crates/engine/src/cmd/freeform.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Add Freeform Point", [], None, - "{at: [x,y] (document coordinates), color? (default: the gradient's colour there), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}", + "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it → {index}", has_doc, add_point ), @@ -28,7 +28,7 @@ pub fn specs() -> Vec { "Edit Freeform Point", [], None, - "{index? (default: the selected point), at?: [x,y] (document coordinates), color?, keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", + "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}", has_doc, set_point ), diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index b2996aa72a..fde35136c4 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index a205adc46c..bd6afd4663 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Vector Halftone…", ["Object"], None, - "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", + "{shape?: \"circle\"|\"ellipse\"|\"square\"|\"diamond\"|\"line\" (circle), frequency?: lines per inch 1–300 (20), angle?: deg (45; CMYK: the black screen's, cyan −30°, magenta +30°, yellow −45° from it), mode?: \"mono\"|\"cmyk\" (mono), color?: mono dot colour (\"#000000\"; #rrggbbaa and #rgba are refused), invert?: bool (dots for light tones), clip?: true (clip the dots to the art's outline), keepOriginal?: false} the selection as vector halftone dots sized by its tone, a group of one path per screen (CMYK screens multiply), as one undo step → {id, dots, warning? (an image in the art couldn't be decoded, as object.rasterize says)}", has_selection, halftone )] diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index fd7d633e4f..6b21673af6 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "New Artboard", ["Window", "Artboards"], None, - "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)", + "{x?, y?, width?, height?, name?, color?: color (its background color, as artboard.setProps takes it, #rrggbbaa and #rgba refused; default: none), showCenterMark?: bool, showCrossHairs?: bool, showVideoSafeAreas?: bool (as artboard.setProps takes them; default false), videoRulerPixelAspectRatio?: number 0.1–10 (as artboard.setProps takes it; default 1)} (default place: right of the last)", has_doc, artboard_new ), @@ -155,7 +155,7 @@ pub fn specs() -> Vec { "Artboard Options…", ["Window", "Artboards"], None, - "{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", + "{index | artboards: [{index, name?, color?, locked?, showCenterMark?, showCrossHairs?, showVideoSafeAreas?, videoRulerPixelAspectRatio?, x?, y?, width?, height?}…] (several artboards in one undo step, each with its own fields; the art inside each before any of them changes goes with it, and an object inside several goes with the first listed that moves or scales its art), name?, color?: color (\"#rrggbb\", {c,m,y,k}, … as the paint commands take, #rrggbbaa and #rgba refused: the background color the canvas draws the artboard's paper in, multiplied with the Simulate Colored Paper color while that is on; exports and print leave it out) | null (no background color), locked?: bool (the Artboards panel's lock column: a locked artboard keeps its rectangle (a new x, y, width or height is an error unless locked is false), can't be moved, deleted or cut, and Rearrange and Fit to Artwork Bounds leave it as it is; the art on it (each object of a layer or sublayer whose bounds with strokes overlap it, a group as one object) acts as locked art until it is unlocked: clicks, marquees, select.set, select.all and the tools pass over it (art drawn or pasted onto it stays selected and editable until a selection leaves it out or it is moved off the locked artboards), it is deselected, and when another artboard moves or scales it stays unless lockedAndHidden), showCenterMark?: bool (Artboard Options' Show Center Mark: the canvas draws a mark at the artboard's center), showCrossHairs?: bool (Show Cross Hairs: the canvas draws a line from the middle of each side through the center), showVideoSafeAreas?: bool (Show Video Safe Areas: the canvas draws the action-safe area 3.5% and the title-safe area 5% in from each edge, as EBU R 95 sets them; the three are screen-only, as the artboard's edges are: exports and print leave them out), videoRulerPixelAspectRatio?: number 0.1–10 (Video Ruler Pixel Aspect Ratio: the width of one video pixel over its height, which View › Rulers › Show Video Rulers counts the artboard in; default 1, square pixels), x?, y?, width?, height?, moveArt?: bool (default false; a position-only change moves the contained art with its artboard), scaleArt?: bool (Scale Artwork with Artboard: resized, the artboard takes the art fully inside it (locked and hidden art only with lockedAndHidden?: bool, default prefs moveLockedWithArtboard) and its guides from its old rectangle onto the new one, each side by its own ratio; strokes/corners/patterns as object.scale), strokes?: bool, corners?: bool, patterns?: bool (the three as object.scale, for art that moves or scales with the artboard), lockedAndHidden?: bool (locked and hidden art moves along; default: the preference; recorded in the journal so a replay matches)} → null, or with scaleArt {scaled: the art scaled}", has_doc, artboard_set ), diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 49865914e9..ff4e3d0fbd 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -643,7 +643,7 @@ pub fn specs() -> Vec { "Add to Library", [], None, - "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", + "{library?: id or name (default: the current library, made when there is none), kind: graphic|fillColor|strokeColor|fillGradient|strokeGradient|fillPattern|strokePattern|charStyle|paraStyle, ids?: objects (default: the selection), name?, color?: colour (a colour to add, instead of the selection's; #rrggbbaa and #rgba are refused), swatch?: a gradient or pattern swatch of the document (fillGradient…strokePattern: added instead of the selection's paint), group?: name, before?: item | after?: item (an item of the same kind)} add an item from the selection: graphic: a copy of the objects with every resource they use; fillColor/strokeColor: the first selected object's solid fill/stroke colour (else the default fill/stroke); fillGradient/strokeGradient: the first selected object's fill/stroke gradient (else the default's), without its placement or swatch links, named after its swatch, else \"Gradient\"; fillPattern/strokePattern: the first selected object's fill/stroke pattern (else the default's) with the resources its art uses, named after it; charStyle/paraStyle: the selected text's character/paragraph attributes (the Type tool's range, else the first selected text object). A new item goes into `group` (default: none) and, with `before` or `after`, just before or after that item in the order its kind is shown in, as dropping it among the Libraries panel's items does; an item the library already has (same kind and contents) isn't added again, nor moved → {library, kind, name, id?: graphic id, existing: bool, group?: name or null (a new item's)}", has_doc, add ), diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index be2b694cdc..be02c16b1b 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -20,7 +20,7 @@ use super::edit::selected_roots; use super::expand::gradient_sampler; use super::pathops::Beside; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_value, f64_or, f64_req, finite_numbers, + CommandSpec, EngineError, Result, Session, always, bad, check_numbers, check_switches, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi, has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, }; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 5f438c8f5b..99c813fa3e 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -245,7 +245,7 @@ pub fn specs() -> Vec { "Set Mesh Point Color", [], None, - "{id, index | points: [index…] | items: [{id, index | points}…], color?, keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)", + "{id, index | points: [index…] | items: [{id, index | points}…], color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1} colour and/or opacity of gradient mesh points (one undo step; an index out of range changes nothing)", has_doc, mesh_set_color ), @@ -272,7 +272,7 @@ pub fn specs() -> Vec { "Add Mesh Line", [], None, - "{id, x, y, color?, keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", + "{id, x, y, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), tolerance?: pt (0)} add a row and a column through (x, y) to a gradient mesh (new point in `color`) or a mesh envelope; a point outside within `tolerance` of the edge adds them through the nearest point of the edge → {index}", has_doc, mesh_add_line ), diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index e00c074bcd..87a7af3578 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec use super::envelope::{outline_of, rows_cols}; use super::{ Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad, - check_numbers, color_value, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param, + check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param, }; // ---------- Gradient mesh ---------- @@ -232,7 +232,7 @@ pub(super) fn mesh_set_color(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["opacity"], C)?; crate::cmd::paint::check_keep_model(p, C)?; let items = point_items(p, C)?; - let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c)); + let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c)); let opacity = p.get("opacity").and_then(Value::as_f64); if color.is_none() && opacity.is_none() { return Err(bad(C, "missing `color` or `opacity`")); @@ -283,7 +283,7 @@ pub(super) fn mesh_add_line(s: &mut Session, p: &Value) -> Result { crate::cmd::paint::check_keep_model(p, C)?; check_numbers(p, &["tolerance"], C)?; let tol = f64_or(p, "tolerance", 0.0).max(0.0); - let color = p.get("color").and_then(color_value).map(|c| crate::cmd::paint::new_color(s, p, c)); + let color = color_param(p, "color", C)?.map(|c| crate::cmd::paint::new_color(s, p, c)); let index = with_mesh(s, p, C, "Add Mesh Line", true, |m| { let i = m.add_lines_at(q, tol).ok_or_else(|| bad(C, "point is outside the mesh"))?; if let Some(c) = color { diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index 5077408e49..e608bb43c2 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -115,7 +115,7 @@ pub fn specs() -> Vec { "Rasterize…", ["Object"], None, - "{ppi?, background?: transparent|white|black|\"#rrggbb\", antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", + "{ppi?, background?: transparent|white|black|\"#rrggbb\" (#rrggbbaa and #rgba are refused), antiAlias?: none|art|type (text snapped to pixels)|bool, padding?|addAround?: pt (0–1000), colorModel?: \"rgb\"|\"cmyk\"|\"grayscale\"|\"bitmap\", clippingMask?: bool (a clip group with the art's outline)} replace the selection with an embedded image (PNG; in a CMYK document with its own colour model, a CMYK image of the art's inks, its transparency as its opacity mask); each defaults to document.rasterEffectsSettings; a frame of threaded text that is rasterized leaves its thread with the text it shows → {id (the image, or its clip group), width, height, warning?: \"an image couldn't be decoded and is missing from the picture\" (as raster exports say)}", has_selection, rasterize ), diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 3abe60b541..0772bf5b14 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -19,7 +19,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg, start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 1759372d0a..f4996f4ad0 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "Recolor Artwork", ["Edit", "Edit Colors"], None, - "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null, exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", + "{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex)], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model)}", has_doc, apply ), @@ -255,13 +255,14 @@ enum Match { } impl Match { - /// A colour key, a hex (`#rrggbb`) or a colour value. + /// A colour key, a hex (`#rrggbb`) or a colour value. `None` for a hex color with an alpha + /// part (`#rrggbbaa` or `#rgba`). fn of(v: &Value) -> Option { if let Some(s) = v.as_str() { if let Some(k) = ColorKey::parse(s) { return Some(Match::Key(k)); } - return Color::from_hex(s).map(|c| Match::Hex(c.to_hex())); + return Color::from_hex(s).filter(|_| !super::hex_with_alpha(s)).map(|c| Match::Hex(c.to_hex())); } color_value(v).map(|c| Match::Key(ColorKey::of(&c))) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 6cc8e3839a..5874c76ab4 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "Select by Color", [], None, - "{fill?: colour, stroke?: colour (as paint.setFill's color; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}", + "{fill?: colour, stroke?: colour (as paint.setFill's color, #rrggbbaa and #rgba refused; at least one)} select the objects whose fill (and stroke) reads as that colour in #rrggbb, as document.inspect reports colours, whatever its swatch or tint; with both, the objects that match both. No object needs to be selected first; Select > Reselect repeats it → {count}", has_doc, select_color ), diff --git a/crates/engine/src/cmd/slices.rs b/crates/engine/src/cmd/slices.rs index 1adc147c56..cc8598a5cc 100644 --- a/crates/engine/src/cmd/slices.rs +++ b/crates/engine/src/cmd/slices.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Slice Options…", ["Object", "Slice"], None, - "{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\", hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}", + "{kind?: \"image\"|\"noImage\"|\"htmlText\" (object slices of type only), name?, url?, target?, message?, alt?: (image), text?: cell text; HTML allowed (noImage), background?: \"\"|\"matte\"|\"#rrggbb\" (#rrggbbaa and #rgba are refused), hAlign?: \"default\"|\"left\"|\"center\"|\"right\", vAlign?: \"default\"|\"top\"|\"middle\"|\"baseline\"|\"bottom\"} set the selected slices' options as one undo step; no options: read them → the first slice's {kind, name, url, target, message, alt, text, background, hAlign, vAlign, htmlText: whether HTML Text applies}", slices_targeted, options ), @@ -513,6 +513,7 @@ impl Edits { "" | "none" => Ok(String::new()), "matte" => Ok("matte".to_string()), _ => vectorcraft_color::Color::from_hex(&b) + .filter(|_| !super::hex_with_alpha(&b)) .map(|c| c.to_hex()) .ok_or_else(|| bad(C, "`background` must be \"\", \"matte\" or #rrggbb")), }) diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 4aa0c0b472..7944e59a0d 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "New Swatch", ["Window", "Swatches"], None, - "{name?, color? | colors?: [colour] (one swatch each, in one undo step) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", + "{name?, color? | colors?: [colour] (one swatch each, in one undo step; #rrggbbaa and #rgba are refused) | swatch? | gradient? | pattern?: name (default: the current fill), tint?: 0..100 (% of the global or spot `swatch`, or of the one the current fill links to), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour; lab: CIE L*a*b*, how spot colours are usually defined), global?, spot? (a spot colour, always global), group?: colour group name (solid colours only; default: ungrouped), none?: true (the None paint), paint?: paint.setFill params, keepModel?: bool (as paint.setFill)} save a colour, gradient or pattern as a swatch. A tint of a global or spot colour (below 100%, without mode, global or spot) becomes a tint swatch, \"Name 40%\", linked to its base: it follows edits to the base and applies as that tint of it. Names are unique (\"Sky 2\"); a colour's default name is its values (\"C=10 M=20 Y=30 K=0\", \"R=255 G=128 B=0\", \"Gray K=40\", \"L=55 a=60 b=40\") → {name, names: [every new swatch]}", has_doc, swatch_new ), @@ -38,7 +38,7 @@ pub fn specs() -> Vec { "New Color Group", ["Window", "Swatches"], None, - "{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}", + "{name?, swatches?: [names] (solid colours move into the group; gradients, patterns and None stay), colors?: [colour] (added as new swatches; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), fromArtwork?: false (add the unique colours of the selected art: fills, strokes, text, gradient stops and mesh points; a colour linked to a global swatch moves that swatch into the group), toGlobal?: true (with fromArtwork: the new swatches are global and the selected art's matching unlinked colours link to them), includeTints?: false (with fromArtwork: tints of global swatches also get swatches of their own)} → {name, swatches: [names in the group], linked: paints linked}", has_doc, swatch_new_group ), @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Swatch Options", ["Window", "Swatches"], None, - "{name, newName?, color? (e.g. {l, a, b} for a Lab colour), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", + "{name, newName?, color? (e.g. {l, a, b} for a Lab colour; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill; the swatch's own color and a color given with mode keep their model), mode?: \"gray\"|\"rgb\"|\"hsb\"|\"lab\"|\"cmyk\"|\"web\" (convert the colour), global?, spot? (spot colours are always global), paint?: paint.setFill params ({color}, {gradient}, {swatch} or {pattern}) replacing the swatch's colour; gradient or pattern with one of the same kind} edit a swatch in any colour group, as one undo step. Fills, strokes, text, gradient stops and tint swatches linked to a global swatch take its new colour (at their own tint) and name; turning Global off unlinks them (they keep their colour). Colour, mode and spot apply to solid colours only; a tint swatch only takes a new name (edit its base) → {name, relinked: paints changed}", has_doc, swatch_edit ), @@ -130,7 +130,7 @@ pub fn specs() -> Vec { "Edit Color Group", ["Window", "Swatches"], None, - "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", + "{group: colour group, colors: [colour] (hex, key, {c,m,y,k} or {l,a,b}; #rrggbbaa and #rgba are refused; the group's swatches take them in order, extra colours become new swatches, swatches past the end are removed; built-in swatches can't change; a color the swatch already has keeps its model), keepModel?: bool (as paint.setFill), rename?: new group name} rewrite a colour group as one undo step; art linked to its global swatches takes their new colours (and keeps its colour, unlinked, when its swatch goes) → {name, swatches: [names], relinked}", has_doc, swatch_edit_group ), @@ -316,7 +316,8 @@ fn swatch_new_group(s: &mut Session, p: &Value) -> Result { let colors: Vec = p .get("colors") .and_then(Value::as_array) - .map(|a| a.iter().filter_map(color_value).map(|c| super::paint::new_color(s, p, c)).collect()) + .map(|a| a.iter().map(|v| color_value(v).map(|c| super::paint::new_color(s, p, c)).ok_or_else(|| bad(C, format!("bad color {v}")))).collect()) + .transpose()? .unwrap_or_default(); let from_art = bool_or(p, "fromArtwork", false); let to_global = from_art && bool_or(p, "toGlobal", true); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 6406fcf5b7..5f3d0231a8 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\", keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg, fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_range_style ), @@ -1353,6 +1353,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { super::paint::check_keep_model(p, C)?; check_numbers(p, &["size"], C)?; check_switches(p, &["vertical", "placeholder"], C)?; + super::color_param(p, "color", C)?; let style = super::create::new_type_style(s, p); let text = str_param(p, "text").unwrap_or("").to_string(); let start = match point_param(p, "at") { diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 6656385a3b..519d282e84 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -123,7 +123,7 @@ pub fn specs() -> Vec { "Character", [], None, - "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", + "{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour|\"none\", stroke?: colour|\"none\" (characters without a stroke weight get 1 pt; #rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt (the character stroke's weight, in document points as stroke.set), features?: [\"dlig\", \"-liga\", …] OpenType, featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits), warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}", has_doc, set_style ), diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index af0f313ea1..9e641a6e6a 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -329,6 +329,7 @@ impl ColorTable { list.iter() .map(|h| { vectorcraft_color::Color::from_hex(h) + .filter(|_| !super::hex_with_alpha(h)) .map(|c| { let [r, g, b, _] = c.to_rgba8(1.0); [r, g, b] diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 9e4969e27a..bac865c71b 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color, stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index c1f33ac974..7a28b922bf 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1405,6 +1405,26 @@ fn symbolism_adjustments() { assert!(s.execute("symbol.adjust", &json!({"tool": "nope", "points": at})).is_err()); } +/// The Symbol Stainer's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes +/// nothing, rather than staining with the current fill; `#rrggbb` still stains with it. +#[test] +fn a_stain_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let (inst, _, b) = make_symbol(&mut s); + let c = b.center(); + let at = json!([[c.x, c.y]]); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in ["#ff000080", "ff000080", "#f008"] { + assert!(s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": bad, "intensity": 10})).is_err(), "{bad}"); + } + assert_eq!(*s.doc().unwrap().doc, *before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("symbol.adjust", &json!({"tool": "stain", "points": at, "color": "#ff0000", "intensity": 10})).unwrap(); + let f = node(&s, inst).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000")); +} + /// In a CMYK document the Symbol Stainer's RGB `color` separates through the color settings, as /// `paint.setFill` stores it. #[test] diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 7208f44f58..5a65b31bea 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -242,6 +242,10 @@ fn gamut_check_flags_unprintable_colours() { let r = s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", {"c": 100, "m": 0, "y": 0, "k": 0}]})).unwrap(); assert_eq!(r["checked"], 2); assert_eq!(r["outOfGamut"].as_array().unwrap().len(), 1); + // A color it can't read, a hex color with an alpha part included, is an error, not skipped. + for bad in ["#0000ff80", "nope"] { + assert!(s.execute("color.gamutCheck", &json!({"colors": ["#00ff00", bad]})).is_err(), "{bad}"); + } } #[test] diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index f500e2c398..1dc5f66bad 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -851,6 +851,28 @@ fn mesh_point_colour_move_and_undo() { assert!(s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 99, "color": "#000000"})).is_err()); } +/// A mesh point's `color` with an alpha part (`#rrggbbaa` or `#rgba`) is refused and changes +/// nothing, also when `opacity` is given and when Add Mesh Line takes it; `#rrggbb` still sets it. +#[test] +fn a_mesh_point_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + sel(&mut s, &[a]); + s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in ["#00ff0080", "00ff0080", "#0f08"] { + let set = json!({"id": a.0, "index": 3, "color": bad, "opacity": 0.5}); + assert!(s.execute("object.mesh.setPointColor", &set).is_err(), "{bad}"); + assert!(s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 50, "y": 50, "color": bad})).is_err(), "{bad}"); + } + assert_eq!(*s.doc().unwrap().doc, *before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + s.execute("object.mesh.setPointColor", &json!({"id": a.0, "index": 3, "color": "#00ff00"})).unwrap(); + assert_eq!(mesh_of(&s, a).points[3].color.to_hex(), "#00ff00"); + s.execute("object.mesh.addLine", &json!({"id": a.0, "x": 50, "y": 50, "color": "#00ff00"})).unwrap(); +} + /// `object.mesh.movePoints` moves just the points it names (their handles with them), over one or /// several meshes, as one undo step; `object.mesh.setPointColor` colours and fades several points /// alike. A bad index, a non-number or a move past the coordinate range fails and changes nothing diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index b201a60c3c..8c18eae43a 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -2545,6 +2545,8 @@ fn select_color_matches_fill_and_stroke_without_a_selection() { assert_eq!(pick(&mut s, json!({"fill": "#000000"})), vec![a, t, empty]); assert!(s.execute("select.color", &json!({})).is_err()); assert!(s.execute("select.color", &json!({"fill": "not a colour"})).is_err()); + assert!(s.execute("select.color", &json!({"fill": "#00000080"})).is_err(), "a hex color with an alpha part"); + assert!(s.execute("select.color", &json!({"stroke": "#ff000080"})).is_err(), "a hex color with an alpha part"); } #[test] diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index fabf5cc54f..e6b4ca3d02 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -162,6 +162,56 @@ fn artboard_color_is_set_and_cleared_in_one_undo_step() { assert_eq!(*s.doc().unwrap().doc, *before, "a bad color changes nothing"); } +/// A color param given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without +/// the `#`) is refused and changes nothing: a Rasterize background, an artboard's color, a fill or +/// stroke, a swatch's colors and the color of new type. `#rrggbb`, a color key and `[r, g, b]` +/// still set the color. +#[test] +fn a_color_with_an_alpha_part_is_refused() { + let mut s = session(); + let id = rect(&mut s); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + for bad in ["#ff000080", "ff000080", " #FF000080 ", "#f008"] { + for (cmd, p) in [ + ("object.rasterize", json!({"ppi": 72, "background": bad})), + ("artboard.setProps", json!({"index": 0, "color": bad})), + ("artboard.new", json!({"color": bad})), + ("paint.setFill", json!({"ids": [id.0], "color": bad})), + ("paint.setStroke", json!({"ids": [id.0], "color": bad})), + ("swatch.new", json!({"name": "Half", "color": bad})), + ("swatch.new", json!({"colors": ["#00ff00", bad]})), + ("swatch.newGroup", json!({"name": "Half", "colors": ["#00ff00", bad]})), + ("text.create", json!({"x": 10, "y": 10, "text": "a", "color": bad})), + ("text.createInPath", json!({"path": id.0, "mode": "area", "text": "a", "color": bad})), + ("document.export", json!({"format": "png", "background": bad})), + ("document.export", json!({"format": "gif", "matte": bad})), + ] { + assert!(s.execute(cmd, &p).is_err(), "{cmd} {p}"); + } + } + assert_eq!(*s.doc().unwrap().doc, *before, "a color with an alpha part changes nothing"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "and records no undo step"); + s.execute("artboard.setProps", &json!({"index": 0, "color": "#ff0000"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.artboards[0].color.map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + let fill = node(&s, id).appearance.fill_paint(); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": "cmyk 0 100 100 0"})).unwrap(); + assert!(node(&s, id).appearance.fill_paint() != fill && node(&s, id).appearance.fill_paint().color().is_some()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": [0, 0, 1]})).unwrap(); + assert_eq!(node(&s, id).appearance.fill_paint().color().map(|c| c.to_hex()).as_deref(), Some("#0000ff")); + s.execute("swatch.new", &json!({"name": "Pure Green", "color": "#00ff00"})).unwrap(); + let green = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Pure Green").map(|w| w.paint.clone()); + assert_eq!(green.and_then(|p| p.color()).map(|c| c.to_hex()).as_deref(), Some("#00ff00")); + let t = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "a", "color": "#ff0000"})).unwrap(); + let NodeKind::Text(t) = node(&s, NodeId(t["id"].as_u64().unwrap())).kind else { panic!("not type") }; + assert_eq!(t.runs[0].style.fill.color().map(|c| c.to_hex()).as_deref(), Some("#ff0000")); + s.execute("document.export", &json!({"format": "png", "background": "#ff0000"})).unwrap(); + s.execute("document.export", &json!({"format": "gif", "matte": "#ff0000"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72, "background": "#ff0000"})).unwrap(); +} + /// The native format writes an artboard's background color and reads it back. An artboard without /// one is written as before, with no `color` key. #[test] diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index cff302503d..541f961b81 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -292,6 +292,12 @@ fn methods_and_bad_params() { select_all(&mut s); assert!(s.execute("recolor.apply", &json!({"map": {"#ff0000": "#00ff00"}, "method": "nope"})).is_err()); assert!(s.execute("recolor.apply", &json!({"map": {"#ff0000": "nonsense"}})).is_err()); + // A current or new color with an alpha part (`#rrggbbaa` or `#rgba`) is refused. + let undo = s.doc().unwrap().history.undo.len(); + for (from, to) in [("#ff000080", "#00ff00"), ("ff000080", "#00ff00"), ("#ff0000", "#00ff0080"), ("#ff0000", "#0f08")] { + assert!(s.execute("recolor.apply", &json!({"map": {from: to}})).is_err(), "{from} {to}"); + } + assert_eq!(s.doc().unwrap().history.undo.len(), undo); assert!(s.execute("recolor.apply", &json!({})).is_err()); run(&mut s, "select.none", json!({})); assert!(s.execute("recolor.apply", &json!({"map": {}})).is_err(), "needs art or a group"); diff --git a/crates/engine/src/tests/slices.rs b/crates/engine/src/tests/slices.rs index eee1a47694..1576f50ce3 100644 --- a/crates/engine/src/tests/slices.rs +++ b/crates/engine/src/tests/slices.rs @@ -199,6 +199,8 @@ fn slice_options_set_read_and_undo_in_one_step() { assert_eq!(slices(&mut s)[0]["name"], "cell"); assert!(s.execute("object.slice.options", &json!({"kind": "htmlText"})).is_err(), "HTML Text is for type"); assert!(s.execute("object.slice.options", &json!({"background": "pink-ish"})).is_err()); + assert!(s.execute("object.slice.options", &json!({"background": "#00ff0080"})).is_err(), "a hex color with an alpha part"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); run(&mut s, "edit.undo", json!({})); assert_eq!(s.doc().unwrap().doc.slices[0].options, Default::default()); // An object slice of type can be HTML Text. diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index c16896ac7d..bdd474612f 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -373,7 +373,9 @@ fn image_size_region_and_metadata() { json!({"format": "bmp"}), json!({"colors": "many"}), json!({"matte": "plaid"}), + json!({"matte": "#ffff0080"}), json!({"colorTable": {"locked": ["nope"]}}), + json!({"colorTable": {"transparent": ["#ff000080"]}}), json!({"artboard": 3}), json!({"preset": "Nope"}), ] { diff --git a/docs/mcp.md b/docs/mcp.md index a74c29ea02..6843b8cf66 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -385,6 +385,10 @@ leaves it out when `ids` list it together with a group that holds it. Paint values (`fill`, `stroke`) accept `"#rrggbb"`, `"none"`, `[r,g,b]` (0..1), `{"c","m","y","k"}`, `{"gray"}`, or a full `paint.setFill` params object (`{"gradient": …}`, `{"swatch": "name"}`). +A color read this way (a fill or stroke color, a swatch's, an artboard's or new type's color, and the other colors +commands read in these forms) that is given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`, with or without +the `#`) is an error and changes nothing, as VectorCraft's own rule. The `color` of Drop Shadow, Inner Glow, Outer Glow +and Shift to Color is read differently and takes `#rrggbbaa`, as described below. For `draw_shape` and `draw_path`, omitted paint fields inherit the current [new-art appearance](#new-art). Both also style the new object in the same call: `dash` (lengths, or null for solid), `cap` (butt|round|square) and `join` (miter|round|bevel) go to `stroke.set` with `strokeWidth`; `opacity` (0–100 %) @@ -701,7 +705,7 @@ its effects paint, the effects of groups, type and images included. `artboard.fi way. Raster exports take more options in `options`: `ppi` (72, 150, 300…; stored in the file, except in GIF, WebP and -Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`), `antiAlias` (`none`, `art`, `type`: text +Targa), `background` (`transparent`, `white`, `black` or `"#rrggbb"`; `#rrggbbaa` and `#rgba` are refused), `antiAlias` (`none`, `art`, `type`: text snapped to pixels) and, for PNG, `interlaced`. `width` or `height` sets the size of each file in pixels: each artboard (with `useArtboards`, each file), `rect` or art bounds gets the scale that makes it that wide or high, within 0.01–64 pixels per point, and the file stores the resolution that results, as with `ppi`. `width` wins over `height`, and @@ -3952,7 +3956,7 @@ still rename it). A Shift-click or Shift-drag on a locked artboard selects or dr document summary (`document.inspect`) adds `locked: true` to a locked artboard. An artboard's background color (Properties › Artboards › Fill, Artboard Options' Background Color): `artboard.setProps -{index, color}` sets it, with a color as the paint commands take it (`"#rrggbb"`, `{c, m, y, k}`, …), and +{index, color}` sets it, with a color as the paint commands take it (`"#rrggbb"`, `{c, m, y, k}`, …; `#rrggbbaa` and `#rgba` are refused), and `artboard.setProps {index, color: null}` removes it, each in one undo step; `artboard.new {color}` makes an artboard with one. The canvas draws that artboard's paper in the color. With Simulate Colored Paper on, it multiplies the color with the paper color, each sRGB channel as @@ -4396,7 +4400,7 @@ selects, and the selected objects that are object slices. `slice.list` reports b `object.slice.fromGuides` (the grid the ruler guides cut the artboards into), `object.slice.fromSelection`, `object.slice.duplicate {dx?, dy?}`, `object.slice.combine`, `object.slice.divide {rows? | rowHeight?, columns? | columnWidth?}`, `object.slice.deleteAll`, `object.slice.options {kind?: image|noImage|htmlText, name?, url?, target?, -message?, alt?, text?, background?: ""|matte|#rrggbb, hAlign?, vAlign?}` and `object.slice.clipToArtboard {on?}` are +message?, alt?, text?, background?: ""|matte|#rrggbb (#rrggbbaa and #rgba refused), hAlign?, vAlign?}` and `object.slice.clipToArtboard {on?}` are each one undo step. `view.slices.hide {hidden?}` and `view.slices.lock {locked?}` are session view state; the canvas draws the slices in the `sliceLineColor` preference, numbered while `showSliceNumbers` is on. Locking or hiding deselects the slices in every open document; unlocking or showing them again leaves them deselected and does not diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index adcdb060a4..7c9115d548 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1271,6 +1271,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Control transport:** idle sockets expire after 5 minutes, partial lines after an absolute 30 seconds from their first byte, and reply writes after 60 seconds (#1726). Real TCP regressions cover stalled peers and slot recovery; command execution has its separate existing timeout. MCP limits: 16 MiB lines, 64-message batches, 256-step `command_batch` with 8 MiB of kept results and 256 MiB control replies (#1764, fixes #1727). MCP requires the JSON-RPC 2.0 envelope and matches control replies by id, and an app refusal without an id reports the app's reason (#1768, fixes #1728). The MCP server reconnects to the app before a call when the connection was closed or holds stray bytes, after an app restart or an idle expiry (#1739). - **MCP vertical type:** `add_text {vertical: true}` forwards to `text.create` or `text.createInPath`. Regression coverage checks point type, rectangular area type, type in a path and type on a path with true, false and omitted direction. This exposes an existing engine option; it does not change glyph orientation, CJK composition or the type/automation scores. - **Malformed MCP replies:** invalid JSON from the app drops the connection, reports that the operation may have completed and leaves the next call to reconnect; it never replays the edit (#1761). TCP regressions cover malformed and uncorrelated replies, connection closure and a subsequent inspection. Envelope regressions also verify zero backend calls and unchanged initialization state for invalid versions. +- **Command colors with an alpha part:** as VectorCraft's own rule, a command's color given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing: fill and stroke colors, artboard, swatch, color group, new type, mesh point and Symbol Stainer colors, and the colors of `recolor.apply`, `select.color`, `color.gamutCheck`, `object.slice.options` (`background`), `object.rasterize` (`background`), `document.export` (`background`, `matte`) and `document.exportForWeb` (`matte`, `colorTable`) among them. Before, a `#rrggbbaa` color was set without its alpha, and a few commands used a default or skipped a color they could not read. The effects' `color` keeps taking `#rrggbbaa`. Tests: `a_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/panelcmds.rs`, `a_mesh_point_color_with_an_alpha_part_is_refused` and `a_stain_color_with_an_alpha_part_is_refused`. - **Tests and robustness:** ~2,840 automated tests: model-based property tests, a junk-parameter sweep over every command, import fuzzing (SVG, PDF, libraries), golden renders, and MCP end-to-end tests over stdio. Shipped code never panics (workspace lints and a rollback safety net; see `docs/development.md`). Scatter graph data near the largest number is refused with a message instead of hanging the app (#1780). One very long Liquify stroke segment can no longer create an unbounded number of dabs (#1779). A drag whose last preview failed is no longer recorded as a committed command in the journal that actions and scripts read (#1775). Tests: text import fuzzing no longer searches installed fonts (#1785). Tests: render tests that add fonts no longer race the frame cache tests (#1795). - **Raster-effect resolution in PDF:** when the 64 million pixel cap on an effect image renders an object's raster effects below the document's raster effects resolution, PDF export warns once per object with the requested and the lowest achieved ppi (`crates/engine/src/tests/pdfraster.rs`). - **Rasterize effect:** Effect › Rasterize… (`rasterize`) draws an object as an image of square pixels at its own resolution or the document's raster effects resolution, with Object › Rasterize's color model, background, anti-aliasing, clipping mask and room around the object, while its paths stay editable. Expand Appearance and PDF and SVG export of an object whose only raster effect is Rasterize give the image Object › Rasterize gives (`crates/engine/src/tests/rastersettings.rs`, `crates/render/src/tests/rasterize.rs`). Behavior reference: [How to save artwork in Illustrator](https://helpx.adobe.com/illustrator/using/saving-artwork.html), [Work with effects](https://helpx.adobe.com/illustrator/using/effects.html). From f3faa115c6401d86397633d740f328ac77b9d08c Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:39:10 +0300 Subject: [PATCH 057/482] Fix #3226: copy and paste ruler guides Edit > Copy and Cut put the selected ruler guides on the clipboard, with the selected objects or on their own. Pasting puts them on the layer new art goes to, selected, in the same undo step: with objects they move as the objects do; alone they keep their places, while Paste in Place / in Front / in Back put them on the active artboard as they lay on theirs, and Paste on All Artboards on every artboard. --- crates/engine/src/cmd.rs | 6 +- crates/engine/src/cmd/clipboard.rs | 5 +- crates/engine/src/cmd/edit.rs | 83 ++++++++++++++++++++-- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/guide_clipboard.rs | 70 ++++++++++++++++++ docs/target-app-parity.md | 5 ++ docs/ui-parity.md | 1 + 7 files changed, 160 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/tests/guide_clipboard.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 85689bf707..b1b9efd60b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -168,9 +168,9 @@ pub fn has_selection(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; if st.selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) } } -/// Objects are selected, or the Artboard tool is chosen (Copy and Cut take its artboard). -pub fn has_selection_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { - if s.tool_id() == "artboard" { has_doc(s) } else { has_selection(s) } +/// Objects or ruler guides are selected, or the Artboard tool is chosen (what Copy and Cut take). +pub fn has_selection_guides_or_artboard_tool(s: &Session) -> std::result::Result<(), String> { + if s.tool_id() == "artboard" { has_doc(s) } else { has_selection_or_guides(s) } } /// Objects or ruler guides are selected (what Delete and the arrow keys act on). pub fn has_selection_or_guides(s: &Session) -> std::result::Result<(), String> { diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index 29933309e9..c487425d36 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -93,11 +93,14 @@ pub struct Clipboard { /// The artboards copied with the Artboard tool (`artboard.copy`); `nodes` are then their art. /// Pasting adds a copy of each with the art. pub artboards: Vec, + /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on + /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. + pub guides: Vec, } impl Clipboard { pub fn is_empty(&self) -> bool { - self.nodes.is_empty() && self.artboards.is_empty() + self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() } /// Objects `roots` of `st`'s document with their resources, source artboard and layers. diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 09aab81325..6c99d33509 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2}; use super::clipboard::SwatchChoices; use super::{ CommandSpec, Result, Session, always, bad, bool_or, can_clear_history, can_redo, can_undo, checked_ids_param, cmd, f64_or, f64_req, - finite_numbers, has_clipboard, has_doc, has_selection, has_selection_or_artboard_tool, has_selection_or_guides, id_param, index, ok, point_param, - str_param, + finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index, ok, + point_param, str_param, }; use crate::{Clipboard, EngineError, inspect}; @@ -125,8 +125,24 @@ pub fn specs() -> Vec { always, undo_group_end ), - cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{} (the Artboard tool chosen: artboard.cut)", has_selection_or_artboard_tool, cut), - cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{} (the Artboard tool chosen: artboard.copy)", has_selection_or_artboard_tool, copy), + cmd!( + "edit.cut", + "Cut", + ["Edit"], + Some("Cmd+X"), + "{} (selected ruler guides go too; the Artboard tool chosen: artboard.cut)", + has_selection_guides_or_artboard_tool, + cut + ), + cmd!( + "edit.copy", + "Copy", + ["Edit"], + Some("Cmd+C"), + "{} the selection with what it uses, and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy → {copied, guides}", + has_selection_guides_or_artboard_tool, + copy + ), cmd!( "edit.paste", "Paste", @@ -652,9 +668,35 @@ fn copy(s: &mut Session, _: &Value) -> Result { if s.tool_id() == "artboard" { return super::panelcmds::artboard_copy(s, &json!({}), false); } - let roots = selected_roots(s)?; - s.clipboard = Clipboard::copy(s.doc()?, &roots); - Ok(json!({ "copied": s.clipboard.nodes.len() })) + let st = s.doc()?; + // Selected ruler guides come along (#3226), as canvas guides: their layer and artboard stay + // behind. + let guides: Vec = st + .selection + .guides + .iter() + .filter_map(|i| st.doc.guides.get(*i)) + .map(|g| vectorcraft_doc::Guide { layer: None, artboard: None, ..g.clone() }) + .collect(); + let roots = if st.selection.is_empty() && !guides.is_empty() { vec![] } else { selected_roots(s)? }; + let st = s.doc()?; + let mut clip = Clipboard::copy(st, &roots); + // Guides alone: the artboard the first one belongs to, or crosses, is where in-place pastes + // measure from, as the objects' artboard is. + if clip.nodes.is_empty() + && let Some(g) = st.selection.guides.first().and_then(|i| st.doc.guides.get(*i)) + { + let board = g.artboard.and_then(|id| st.doc.artboards.iter().find(|a| a.id == id)).or_else(|| { + st.doc + .artboards + .iter() + .find(|a| if g.vertical { (a.rect.x0..=a.rect.x1).contains(&g.pos) } else { (a.rect.y0..=a.rect.y1).contains(&g.pos) }) + }); + clip.source_artboard = board.map(|a| a.rect); + } + clip.guides = guides; + s.clipboard = clip; + Ok(json!({ "copied": s.clipboard.nodes.len(), "guides": s.clipboard.guides.len() })) } fn cut(s: &mut Session, p: &Value) -> Result { @@ -663,6 +705,11 @@ fn cut(s: &mut Session, p: &Value) -> Result { } // Copy promotes a compound member to its compound. Cut must remove the same objects it // copied, while Clear on its own deletes exactly the selected members. + // Ruler guides selected on their own: Copy takes them, Clear removes them. + if s.doc()?.selection.is_empty() { + copy(s, p)?; + return clear(s, &json!({})); + } let ids = selected_roots(s)?; copy(s, p)?; if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) } @@ -850,6 +897,13 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho // In place, in front, in back: onto the active artboard when the UI names it. _ => vec![onto_artboard(&st.doc, p, clip)], }; + // Guides alone don't follow a plain paste's offset or the view centre: they stay where they + // were. With objects they move as the objects do. + let guide_placements: Vec = if !clip.nodes.is_empty() || !matches!(mode, PasteMode::Offset | PasteMode::Library | PasteMode::Drag) { + placements.clone() + } else { + vec![Affine::IDENTITY] + }; let (ids, imported, artboards, into) = s.edit(mode.label(), |d, sel| { let imported = clip.import_into(d, choices, same_doc); // Draw Inside: the clip group of the object drawn into, made on the first paste. @@ -897,6 +951,20 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } } sel.set(new_ids.iter().copied()); + // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a + // paste of guides alone keeps them where they were, but onto another artboard or every + // artboard as the in-place pastes put art); they are selected with the objects. + let guide_layer = parent.and_then(|p| if d.node(p).is_some_and(Node::is_layer) { Some(p) } else { d.layer_containing(p) }); + for xf in &guide_placements { + let dv = xf.translation(); + for g in &clip.guides { + let pos = g.pos + if g.vertical { dv.x } else { dv.y }; + if pos.is_finite() { + sel.guides.push(d.guides.len()); + d.guides.push(vectorcraft_doc::Guide { pos, layer: guide_layer, ..g.clone() }); + } + } + } // Pasted type arrives without the layout bounds cache: fill it so boxes and alignment are // right away (opening the file later would, but paste must not depend on a reopen). super::typecmd::refresh_bounds_of(d, &new_ids); @@ -911,6 +979,7 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho } Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::>(), + "guides": clip.guides.len() * guide_placements.len(), "artboard": artboards.first(), "artboards": artboards, "added": imported.added, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3f6a653c99..a1fa3e0487 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -67,6 +67,7 @@ mod gradient; mod gradpanel; mod gradpresets; mod gradspan; +mod guide_clipboard; mod halftone; mod history_mem; mod ids_without_selection; diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs new file mode 100644 index 0000000000..6c8eec3c29 --- /dev/null +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -0,0 +1,70 @@ +//! Copying and pasting ruler guides (#3226): selected guides go on the clipboard with the objects +//! or alone, and paste into another document or onto another artboard. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::*; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +/// The active document's guides: (vertical, pos, layer). +fn guides(s: &Session) -> Vec<(bool, f64, Option)> { + s.doc().unwrap().doc.guides.iter().map(|g| (g.vertical, g.pos, g.layer)).collect() +} + +#[test] +fn ruler_guides_copy_and_paste_into_another_document() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 120})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 80})); + run(&mut s, "guide.select", json!({"indexes": [0, 1]})); + let r = run(&mut s, "edit.copy", json!({})); + assert_eq!(r["guides"], 2); + // Into another document: the same places, on its current layer, selected, one undo step. + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + let layer = s.doc().unwrap().doc.layers[0].id; + let undo = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "edit.paste", json!({})); + assert_eq!(r["guides"], 2); + assert_eq!(guides(&s), [(true, 120.0, Some(layer)), (false, 80.0, Some(layer))], "where they were, not offset"); + assert_eq!(s.doc().unwrap().selection.guides, [0, 1]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + run(&mut s, "edit.undo", json!({})); + assert!(guides(&s).is_empty()); + // With an object, they move as it does (Paste offsets it by the Paste Offset preference). + run(&mut s, "document.activate", json!({"index": 0})); + let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [rect]})); + run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "document.activate", json!({"index": 1})); + run(&mut s, "edit.paste", json!({"dx": 5, "dy": 7})); + assert_eq!(guides(&s).iter().map(|g| (g.0, g.1)).collect::>(), [(true, 125.0)]); +} + +#[test] +fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 100, "height": 100, "artboards": 2})); + let [a, b] = [0, 1].map(|i| s.doc().unwrap().doc.artboards[i].rect); + run(&mut s, "guide.add", json!({"vertical": true, "pos": a.x0 + 30.0})); + run(&mut s, "guide.select", json!({"indexes": [0]})); + // Cut takes the guide away and keeps it on the clipboard. + run(&mut s, "edit.cut", json!({})); + assert!(guides(&s).is_empty()); + // Paste in Place onto the second artboard: 30 pt into it. + run(&mut s, "edit.pasteInPlace", json!({"artboard": 1})); + assert_eq!(guides(&s).iter().map(|g| g.1).collect::>(), [b.x0 + 30.0]); + // Paste on All Artboards: one on each. + run(&mut s, "edit.pasteOnAllArtboards", json!({})); + let mut at: Vec = guides(&s).iter().map(|g| g.1).collect(); + at.sort_by(f64::total_cmp); + assert_eq!(at, [a.x0 + 30.0, b.x0 + 30.0, b.x0 + 30.0]); + // Nothing selected: Copy is off. + run(&mut s, "select.none", json!({})); + assert!(s.execute("edit.copy", &json!({})).is_err()); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7c9115d548..ceb941f65f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1594,10 +1594,15 @@ A double-click on a Repeat (Radial, Grid or Mirror) with the Selection tool ente With area type selected, the Properties panel's Paragraph section and the Control panel show Align Top, Align Center, Align Bottom and Justify Vertically buttons, as the public documentation places them ([Align text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/align-text.html)). They set the type's vertical alignment in its frame (`text.areaOptions {verticalAlign}`, as Area Type Options does) on every selected frame in one undo step, each frame keeping its other options; the shared alignment shows selected, none when the frames differ (#3759). As that page limits vertical alignment to area type without rows, columns or threads, the buttons are turned off while a selected frame has rows or columns or is threaded; Area Type Options and `text.areaOptions` still align each row/column cell (a VectorCraft extension, unchanged here). Tests: `panels::properties::tests::vertical_alignment_buttons_align_the_selected_area_type`. +## Copy and paste ruler guides (2026-11-01) + +Edit › Copy and Cut put the selected ruler guides on the clipboard, with the selected objects or on their own, so they paste into another artboard or document (#3226). Pasted guides go on the layer new art goes to and are selected; with objects they move as the objects do, and alone they keep their places, while Paste in Place, in Front and in Back put them on the active artboard as they lay on theirs and Paste on All Artboards on every artboard. Tests: `tests::guide_clipboard`. + ## Revision history | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-02 | minor | Wheel input over closed font-family fields changes selected text (#5253); public documentation and application choices distinguished; scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a51fdd99d1..d40316ad28 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -420,6 +420,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 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 | | 2026-11-04 | minor | Area type: Align Top / Center / Bottom / Justify Vertically buttons in the Properties panel (Paragraph section) and the Control panel set its vertical alignment in the frame, as Area Type Options does; turned off for frames with rows or columns and threaded frames (#3759); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | | 2026-11-03 | minor | Type on a Path Options has a Preview checkbox (#5360, as public tutorials of the dialog show); scores and estimates unchanged | From 484a78f812c37f1f226aaba312825d3a661f05ae Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:37:35 +0300 Subject: [PATCH 058/482] Copy and paste guides: Cut takes the selected guides with the objects Cut with objects and ruler guides selected now removes both, in one undo step: edit.clear takes guides: true beside ids to delete the selected guides with the objects it names. --- crates/engine/src/cmd/edit.rs | 10 ++++++---- crates/engine/src/tests/guide_clipboard.rs | 10 ++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 6c99d33509..08f765c83d 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -193,7 +193,7 @@ pub fn specs() -> Vec { "Clear", ["Edit"], Some("Delete"), - "{ids?} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)", + "{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides)", has_selection_or_guides, clear ), @@ -712,7 +712,8 @@ fn cut(s: &mut Session, p: &Value) -> Result { } let ids = selected_roots(s)?; copy(s, p)?; - if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids })) } else { clear(s, &json!({})) } + // The selected ruler guides it copied go with the objects, in the same undo step (#3226). + if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({})) } } fn clear(s: &mut Session, p: &Value) -> Result { @@ -726,8 +727,9 @@ fn clear(s: &mut Session, p: &Value) -> Result { return super::docmenu::guide_remove(s, &json!({})); } let st = s.doc()?; - // Guides selected with the art go with it (not when ids are given). - let with_guides = explicit.is_none(); + // Guides selected with the art go with it (not when ids are given, unless `guides` says so: + // Cut, which names the objects it copied). + let with_guides = explicit.is_none() || bool_or(p, "guides", false); let targets = explicit.unwrap_or_else(|| st.selection.in_paint_order(&st.doc)); // Keep the selected ids themselves, without promoting compound members. Delete a selected // ancestor just once; its selected descendants leave with it. Layers themselves are kept. diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs index 6c8eec3c29..ca1f9fd798 100644 --- a/crates/engine/src/tests/guide_clipboard.rs +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -64,6 +64,16 @@ fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() { let mut at: Vec = guides(&s).iter().map(|g| g.1).collect(); at.sort_by(f64::total_cmp); assert_eq!(at, [a.x0 + 30.0, b.x0 + 30.0, b.x0 + 30.0]); + // Cut with an object and a guide selected takes both away, in one undo step. + let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + let before = guides(&s).len(); + run(&mut s, "select.set", json!({"ids": [rect]})); + run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true})); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "edit.cut", json!({})); + assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); + assert_eq!(guides(&s).len(), before - 1, "the selected guide goes too"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); // Nothing selected: Copy is off. run(&mut s, "select.none", json!({})); assert!(s.execute("edit.copy", &json!({})).is_err()); From 2402f8e1aa8a3d825fa30e5722e666ede891bae7 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:47:20 +0300 Subject: [PATCH 059/482] Copy and paste guides: Cut with direct-selected anchors takes the guides too With anchors and ruler guides selected, Cut deletes the anchors and the selected guides in one undo step (edit.clear's guides: true reaches the anchor-deleting path). --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/path.rs | 8 +++++++- crates/engine/src/tests/guide_clipboard.rs | 10 ++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 08f765c83d..41276c2326 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -713,7 +713,7 @@ fn cut(s: &mut Session, p: &Value) -> Result { let ids = selected_roots(s)?; copy(s, p)?; // The selected ruler guides it copied go with the objects, in the same undo step (#3226). - if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({})) } + if s.doc()?.selection.anchors.is_empty() { clear(s, &json!({ "ids": ids, "guides": true })) } else { clear(s, &json!({ "guides": true })) } } fn clear(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index f1bc3e501a..2def5ce9ea 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1189,7 +1189,9 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result { ok() } -pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result { +pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { + // `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step. + let with_guides = p.get("guides").and_then(Value::as_bool).unwrap_or(false); let st = s.doc()?; let sel = st.selection.anchors.clone(); let segments = st.selection.segments.clone(); @@ -1197,6 +1199,10 @@ pub(crate) fn delete_anchors(s: &mut Session, _: &Value) -> Result { // also catches part of another path must still delete those whole objects. let whole = st.selection.whole(); s.edit("Clear", |d, selection| { + if with_guides { + let gone = selection.guides.clone(); + d.retain_guides(selection, |i, _| !gone.contains(&i)); + } let targets: BTreeSet = whole.into_iter().filter(|id| d.node(*id).is_some_and(|n| !n.is_layer())).collect(); let whole_ids: Vec = targets .iter() diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs index ca1f9fd798..d71c1dd42d 100644 --- a/crates/engine/src/tests/guide_clipboard.rs +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -74,6 +74,16 @@ fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() { assert!(s.doc().unwrap().doc.node(NodeId(rect)).is_none()); assert_eq!(guides(&s).len(), before - 1, "the selected guide goes too"); assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + // Cut with direct-selected anchors and a guide: the anchors and the guide go, one undo step. + let path = run(&mut s, "shape.rectangle", json!({"x": 40, "y": 40, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 90})); + let n = guides(&s).len(); + run(&mut s, "select.anchors", json!({"id": path, "anchors": [[0, 0]], "mode": "set"})); + run(&mut s, "guide.select", json!({"indexes": [n - 1], "toggle": true})); + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "edit.cut", json!({})); + assert_eq!(guides(&s).len(), n - 1, "the guide goes with the anchors"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); // Nothing selected: Copy is off. run(&mut s, "select.none", json!({})); assert!(s.execute("edit.copy", &json!({})).is_err()); From ad64852255f226dd7ae2482b785e9c5ebb895da8 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:54:02 +0300 Subject: [PATCH 060/482] Guide clipboard: guides alone stay off the system clipboard; test two pastes and layers Copying only ruler guides published an empty SVG and text to the system clipboard, replacing what other apps put there. The clipboard now offers other apps nothing without art. Tests cover two pastes adding guides of their own on the current layer (following its visibility) and the SVG carrying no guides. --- crates/engine/src/cmd/clipboard.rs | 8 +++- crates/engine/src/cmd/clipboard/flavours.rs | 2 +- crates/engine/src/tests/guide_clipboard.rs | 41 +++++++++++++++++++++ crates/ui-egui/src/sysclip.rs | 5 +++ 4 files changed, 54 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c487425d36..cf6718d8ed 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -103,6 +103,12 @@ impl Clipboard { self.nodes.is_empty() && self.artboards.is_empty() && self.guides.is_empty() } + /// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft: + /// guides alone put nothing on the system clipboard (#3226). + pub fn has_art(&self) -> bool { + !self.nodes.is_empty() || !self.artboards.is_empty() + } + /// Objects `roots` of `st`'s document with their resources, source artboard and layers. pub(crate) fn copy(st: &DocState, roots: &[NodeId]) -> Self { let d = &*st.doc; @@ -198,7 +204,7 @@ impl Clipboard { /// The objects as standalone SVG (`None` when there are none). pub fn svg(&self) -> Option { - if self.is_empty() { + if !self.has_art() { return None; } let d = self.to_document(); diff --git a/crates/engine/src/cmd/clipboard/flavours.rs b/crates/engine/src/cmd/clipboard/flavours.rs index b2e1114e1a..f4c096d9be 100644 --- a/crates/engine/src/cmd/clipboard/flavours.rs +++ b/crates/engine/src/cmd/clipboard/flavours.rs @@ -286,7 +286,7 @@ impl Clipboard { /// The MIME types of [`Self::flavours`], without making them. pub fn flavour_types(&self, svg: bool, pdf: bool) -> Vec<&'static str> { - if self.is_empty() { + if !self.has_art() { return vec![]; } let text = (svg && self.image_bytes() <= COPY_TEXT_IMAGE_BYTES) || self.nodes.iter().all(type_only); diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs index d71c1dd42d..b6fceead01 100644 --- a/crates/engine/src/tests/guide_clipboard.rs +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -88,3 +88,44 @@ fn guides_paste_in_place_onto_another_artboard_and_cut_removes_them() { run(&mut s, "select.none", json!({})); assert!(s.execute("edit.copy", &json!({})).is_err()); } + +/// #3226 review: each paste adds guides of its own (a guide is its place and layer; there is no +/// id to share), on the layer new art goes to, so they take that layer's colour, visibility and +/// lock; and the SVG put on the system clipboard carries no guides. +#[test] +fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 400, "height": 300})); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 120})); + run(&mut s, "guide.select", json!({"indexes": [0]})); + run(&mut s, "edit.copy", json!({})); + // Guides alone: no art for the system clipboard's SVG. + assert!(s.clipboard_svg().is_none(), "guides alone put no SVG on the system clipboard"); + assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (it keeps what other apps put there)"); + let layer = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); + run(&mut s, "edit.paste", json!({})); + assert_eq!(s.doc().unwrap().selection.guides, [1], "the first paste selects its own guide"); + run(&mut s, "edit.paste", json!({})); + assert_eq!(s.doc().unwrap().selection.guides, [2], "the second paste selects its own guide"); + let g = guides(&s); + assert_eq!(g.len(), 3, "two pastes, two more guides: {g:?}"); + assert_eq!((g[1].2, g[2].2), (Some(layer), Some(layer)), "on the layer new art goes to"); + // Moving the second pasted guide leaves the first where it is. + run(&mut s, "guide.move", json!({"index": 2, "pos": 200})); + assert_eq!(guides(&s).iter().map(|g| g.1).collect::>(), [120.0, 120.0, 200.0]); + // Hiding that layer hides the guides pasted on it: they follow its visibility (and lock). + run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": false})); + let st = s.doc().unwrap(); + let shown: Vec = st.doc.guides.iter().map(|g| st.doc.guide_shown(g)).collect(); + assert_eq!(shown, [true, false, false]); + // With an object, the SVG holds the object and no guide. + run(&mut s, "layer.setProps", json!({"id": layer.0, "visible": true})); + let rect = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids": [rect]})); + run(&mut s, "guide.select", json!({"indexes": [0], "toggle": true})); + let r = run(&mut s, "edit.copy", json!({})); + assert_eq!(r["guides"], 1); + let svg = s.clipboard_svg().unwrap(); + assert!(svg.contains(" Date: Wed, 4 Nov 2026 07:11:03 -0500 Subject: [PATCH 061/482] Guide clipboard: Paste after a guides-only Copy takes the guides, not older system clipboard content A Copy of ruler guides alone left the system clipboard as it was, so the next Paste took whatever another app had copied before instead of the guides. The guides-only Copy now empties the system clipboard (on the web, empty text through egui with Copy As SVG on), as any Copy replaces what the clipboard held, and drops an earlier Copy's formats not written yet. What another app copies afterwards still pastes. --- crates/engine/src/cmd/clipboard.rs | 2 +- crates/engine/src/tests/guide_clipboard.rs | 2 +- crates/ui-egui/src/sysclip.rs | 28 +++++- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/sysclip.rs | 8 +- crates/ui-egui/src/tests/sysclip_guides.rs | 102 +++++++++++++++++++++ docs/target-app-parity.md | 2 +- docs/ui-parity.md | 1 + 8 files changed, 137 insertions(+), 9 deletions(-) create mode 100644 crates/ui-egui/src/tests/sysclip_guides.rs diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index cf6718d8ed..88c0447ef1 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -104,7 +104,7 @@ impl Clipboard { } /// Does it hold art (objects or artboards) for other apps? Ruler guides stay in VectorCraft: - /// guides alone put nothing on the system clipboard (#3226). + /// a Copy of guides alone empties the system clipboard (#3226). pub fn has_art(&self) -> bool { !self.nodes.is_empty() || !self.artboards.is_empty() } diff --git a/crates/engine/src/tests/guide_clipboard.rs b/crates/engine/src/tests/guide_clipboard.rs index b6fceead01..d509dfa206 100644 --- a/crates/engine/src/tests/guide_clipboard.rs +++ b/crates/engine/src/tests/guide_clipboard.rs @@ -101,7 +101,7 @@ fn two_pastes_add_their_own_guides_on_the_current_layer_and_svg_has_none() { run(&mut s, "edit.copy", json!({})); // Guides alone: no art for the system clipboard's SVG. assert!(s.clipboard_svg().is_none(), "guides alone put no SVG on the system clipboard"); - assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (it keeps what other apps put there)"); + assert!(s.clipboard.flavour_types(true, true).is_empty(), "nor any other format (the app empties the system clipboard)"); let layer = NodeId(run(&mut s, "layer.new", json!({}))["id"].as_u64().unwrap()); run(&mut s, "edit.paste", json!({})); assert_eq!(s.doc().unwrap().selection.guides, [1], "the first paste selects its own guide"); diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index 4d70737516..f72339a3e5 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -124,9 +124,11 @@ impl VectorcraftApp { /// ([`Self::write_formats_before_text_input`]). Once they are written, the status bar shows /// the first of the PNG's and PDF's warnings. pub(crate) fn publish_clipboard(&mut self) { - // Ruler guides copied alone stay in VectorCraft: the system clipboard keeps what other - // apps put there (#3226). + // Ruler guides copied alone stay in VectorCraft, but the Copy still replaces what the + // system clipboard held: it is emptied, so the next Paste takes the guides rather than + // what another app copied before, and what another app copies after still wins (#3226). if !self.session.clipboard.has_art() { + self.clear_system_clipboard(); return; } if self.services.system_clipboard.is_none() { @@ -181,6 +183,28 @@ impl VectorcraftApp { } } + /// A Copy with nothing for other apps (ruler guides alone): the formats of an earlier Copy or + /// Cut not written yet are dropped and the system clipboard is emptied. On the web, empty text + /// goes through egui when Copy As SVG is on, in place of the SVG objects would put there. + fn clear_system_clipboard(&mut self) { + let publishing = &mut self.clipboard_publishing; + publishing.latest.fetch_add(1, Ordering::SeqCst); + publishing.pending = false; + match self.services.system_clipboard.as_mut() { + Some(cb) => { + if let Err(e) = cb.write(&[]) { + self.ui.status = format!("Couldn't copy to the system clipboard: {e}"); + } + } + None => { + if self.session.prefs.copy_as_svg { + self.clipboard_out = Some(String::new()); + self.clipboard_published = None; + } + } + } + } + /// End of a frame: when something copied text or a picture through egui this frame (a text /// field, the Type tool), the formats of an earlier Copy or Cut that are not written yet are /// dropped, and the system clipboard keeps that copy. diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 250f721fdc..f0c779f646 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -48,6 +48,7 @@ mod svgsave; pub(super) mod synthetic; pub(super) mod sysclip; mod sysclip_emf; +mod sysclip_guides; mod sysclip_probe; mod tab_overflow; mod taskbar; diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index 6a013e9289..3266e6ba19 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -80,7 +80,7 @@ pub(super) fn copy_rect(app: &mut VectorcraftApp) { run(app, "edit.copy", json!({})); } -fn written(board: &Rc>) -> Vec<&'static str> { +pub(super) fn written(board: &Rc>) -> Vec<&'static str> { board.borrow().flavours.iter().map(|f| f.mime).collect() } @@ -90,7 +90,7 @@ pub(super) fn pasted(app: &VectorcraftApp) -> Vec { st.selection.objects.iter().map(|id| st.doc.node(*id).unwrap().clone()).collect() } -fn count(app: &VectorcraftApp) -> usize { +pub(super) fn count(app: &VectorcraftApp) -> usize { app.session.active().unwrap().doc.layers[0].children().unwrap().len() } @@ -152,7 +152,7 @@ pub(crate) fn blue_png() -> Vec { /// One headless frame of app logic (shortcuts too, from the second frame on) delivering `events`, /// in the test's one context (in a new one the app starts its fonts over). -fn frame(app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { +pub(super) fn frame(app: &mut VectorcraftApp, events: Vec) -> egui::FullOutput { thread_local! { static CTX: egui::Context = egui::Context::default(); } @@ -175,7 +175,7 @@ fn app_with_worker() -> (VectorcraftApp, Rc>) { /// [`app_with_worker`], its worker busy with a job labeled `label` (none: another Copy's formats) /// until the sender is dropped, or for 10 s. -fn app_with_busy_worker(label: &str) -> (VectorcraftApp, Rc>, Sender<()>) { +pub(super) fn app_with_busy_worker(label: &str) -> (VectorcraftApp, Rc>, Sender<()>) { let (mut app, board) = app_with_worker(); let hold = hold_worker(&mut app, label); (app, board, hold) diff --git a/crates/ui-egui/src/tests/sysclip_guides.rs b/crates/ui-egui/src/tests/sysclip_guides.rs new file mode 100644 index 0000000000..a54bd57eb6 --- /dev/null +++ b/crates/ui-egui/src/tests/sysclip_guides.rs @@ -0,0 +1,102 @@ +//! Ruler guides copied alone and the system clipboard (#3226 review): a guides-only Copy empties +//! the system clipboard, as any Copy replaces what it held, so the next Paste takes the guides and +//! not what another app copied before. What another app copies after it still wins. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_engine::Session; +use vectorcraft_engine::cmd::clipboard::{PNG, TEXT}; + +use crate::tests_sysclip::{app, app_with_busy_worker, copy_elsewhere, copy_rect, count, frame, pasted, run, written}; +use crate::{Services, VectorcraftApp, background}; + +fn guides(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().doc.guides.len() +} + +/// Add a vertical guide at `pos`, select only it and copy it. +fn copy_guide(app: &mut VectorcraftApp, pos: f64) { + run(app, "guide.add", json!({"vertical": true, "pos": pos})); + let last = guides(app) - 1; + run(app, "select.none", json!({})); + run(app, "guide.select", json!({"indexes": [last]})); + run(app, "edit.copy", json!({})); +} + +#[test] +fn a_guides_only_copy_pastes_the_guides_not_what_another_app_copied_before() { + let (mut app, board) = app(); + copy_elsewhere(&board, vec![(TEXT, b"Words another app copied".to_vec()), (PNG, vec![1, 2, 3])]); + copy_guide(&mut app, 120.0); + assert!(written(&board).is_empty(), "the Copy emptied the system clipboard: {:?}", written(&board)); + run(&mut app, "edit.paste", json!({})); + assert_eq!(guides(&app), 2, "the copied guide was pasted"); + assert_eq!(count(&app), 0, "and not the other app's text"); + assert_eq!(app.session.active().unwrap().selection.guides, [1]); + // A second Paste takes the guides again. + run(&mut app, "edit.paste", json!({})); + assert_eq!((guides(&app), count(&app)), (3, 0)); +} + +#[test] +fn what_another_app_copies_after_a_guides_only_copy_is_pasted() { + let (mut app, board) = app(); + copy_guide(&mut app, 120.0); + copy_elsewhere(&board, vec![(TEXT, b"Copied later".to_vec())]); + run(&mut app, "edit.paste", json!({})); + let NodeKind::Text(t) = &pasted(&app)[0].kind else { panic!("not type") }; + assert_eq!(t.plain_text(), "Copied later"); + assert_eq!(guides(&app), 1, "no guide pasted"); +} + +#[test] +fn objects_copied_after_guides_paste_as_objects() { + let (mut app, board) = app(); + copy_guide(&mut app, 120.0); + run(&mut app, "select.none", json!({})); + copy_rect(&mut app); + assert!(!written(&board).is_empty(), "objects go to the system clipboard"); + run(&mut app, "edit.paste", json!({})); + assert!(matches!(pasted(&app)[0].kind, NodeKind::Path { .. })); + assert_eq!(guides(&app), 1, "the earlier guides-only copy is replaced"); +} + +/// A guides-only Copy right after an object Copy whose formats are still being made: those formats +/// are dropped, so they don't land on the system clipboard after it and replace the guides. +#[test] +fn a_guides_only_copy_drops_an_earlier_copys_formats_not_written_yet() { + let (mut app, board, hold) = app_with_busy_worker(""); + copy_elsewhere(&board, vec![(TEXT, b"Words another app copied".to_vec())]); + copy_rect(&mut app); + copy_guide(&mut app, 120.0); + drop(hold); + background::wait_all(&mut app); + assert!(written(&board).is_empty(), "{:?}", written(&board)); + let objects = count(&app); + run(&mut app, "edit.paste", json!({})); + assert_eq!((guides(&app), count(&app)), (2, objects), "the guide, not the rectangle or the text"); +} + +/// The web (no clipboard service): a guides-only Copy puts empty text on the clipboard through +/// egui, in place of the SVG an object Copy puts there, so another app's SVG copied before is not +/// pasted instead of the guides. +#[test] +fn on_the_web_a_guides_only_copy_empties_the_clipboard_text() { + let browser = Rc::new(RefCell::new(r#""#.to_string())); + let read = browser.clone(); + let services = Services { clipboard_read: Some(Box::new(move || Some(read.borrow().clone()))), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + run(&mut app, "file.new", json!({"width": 400, "height": 300})); + copy_guide(&mut app, 120.0); + let out = frame(&mut app, vec![]); + let copied: Vec<&String> = + out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t) } else { None }).collect(); + assert_eq!(copied, [""], "empty text replaces the browser's clipboard"); + // The browser now holds that empty text. + browser.borrow_mut().clear(); + run(&mut app, "edit.paste", json!({})); + assert_eq!((guides(&app), count(&app)), (2, 0), "the guide, not the other app's SVG"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ceb941f65f..25a6f25e05 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1596,7 +1596,7 @@ With area type selected, the Properties panel's Paragraph section and the Contro ## Copy and paste ruler guides (2026-11-01) -Edit › Copy and Cut put the selected ruler guides on the clipboard, with the selected objects or on their own, so they paste into another artboard or document (#3226). Pasted guides go on the layer new art goes to and are selected; with objects they move as the objects do, and alone they keep their places, while Paste in Place, in Front and in Back put them on the active artboard as they lay on theirs and Paste on All Artboards on every artboard. Tests: `tests::guide_clipboard`. +Edit › Copy and Cut put the selected ruler guides on the clipboard, with the selected objects or on their own, so they paste into another artboard or document (#3226). Pasted guides go on the layer new art goes to and are selected; with objects they move as the objects do, and alone they keep their places, while Paste in Place, in Front and in Back put them on the active artboard as they lay on theirs and Paste on All Artboards on every artboard. Guides have no format other apps read, so a Copy of guides alone empties the system clipboard, and the next Paste takes the guides rather than what another app copied before. Tests: `tests::guide_clipboard`, `tests::sysclip_guides` (ui-egui). ## Revision history diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d40316ad28..934323ff77 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -430,6 +430,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-11-01 | minor | Live Corners: while a corner widget is pressed or dragged with the Selection or Direct Selection tool, the Up and Down arrows step the corners' kind (round, inverted round, chamfer) with the radius, as one undo step (#2898); scores and estimates unchanged | | 2026-11-01 | minor | Keyboard Shortcuts: every Effect menu item (Distort & Transform › Transform…, Stylize › Drop Shadow…, …) is listed under its menu path and takes a shortcut of its own, which the menu shows and which opens that effect's dialog (or applies an effect without options) (#3296); scores and estimates unchanged | | 2026-10-31 | minor | Units › East Asian Type acts (#394): Q and Ha (a quarter of a millimetre each) are units that preference offers; 4 Preferences options remain stored but unused; 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; a Copy of guides alone empties the system clipboard, so Paste takes the guides, not what another app copied before (#3226); scores and estimates unchanged | | 2026-11-01 | minor | Color Effects add-on (a VectorCraft addition): Find Nearest Swatch (#4923); scores and estimates unchanged | | 2026-11-01 | minor | Artboards panel: a row dragged above or below another reorders the artboards (#4687); scores and estimates unchanged | | 2026-11-01 | minor | Object › Plug-ins › Color Effects › Create Swatch Legend…: a dialog that draws labelled chips of the colour swatches (all, or the ones selected in the Swatches panel) as one group (#4919); scores and estimates unchanged | From 7c04fd8973dc8a4ed377de42f43bad3d67743583 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:42:49 +0300 Subject: [PATCH 062/482] Fix #4921: Image Trace > Batch Trace Folder imageTrace.batchFolder opens each image in a folder, traces it with a preset (optionally expanded), saves it into a destination folder under its own name (vectorcraft, svg, pdf, ai or eps; taken names numbered so nothing is replaced) and closes it again whether it traced or not; the active document stays active. Object > Image Trace > Batch Trace Folder asks for both folders. Not on the web. --- crates/engine/src/cmd/fileio.rs | 1 + crates/engine/src/cmd/fileio/commands.rs | 9 + crates/engine/src/cmd/fileio/trace_batch.rs | 180 ++++++++++++++++++++ crates/ui-egui/src/io.rs | 49 ++++++ crates/ui-egui/src/menus/run.rs | 1 + docs/mcp.md | 7 + docs/target-app-parity.md | 5 + docs/ui-parity.md | 1 + 8 files changed, 253 insertions(+) create mode 100644 crates/engine/src/cmd/fileio/trace_batch.rs diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 76f408d221..f20aa051ea 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -32,6 +32,7 @@ mod export; pub(crate) mod imagemap; mod legacy_ai; mod load; +mod trace_batch; pub(crate) use load::{MAX_RASTER_ALLOC, size_note}; mod jp2read; mod metafile; diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 5b734c5a26..16d85cbaf2 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -112,6 +112,15 @@ pub fn specs() -> Vec { has_doc, batch::batch ), + cmd!( + "imageTrace.batchFolder", + "Batch Trace Folder", + ["Object", "Image Trace"], + None, + "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", + always, + super::trace_batch::batch_folder + ), cmd!( "action.batch", "Batch…", diff --git a/crates/engine/src/cmd/fileio/trace_batch.rs b/crates/engine/src/cmd/fileio/trace_batch.rs new file mode 100644 index 0000000000..354af7c026 --- /dev/null +++ b/crates/engine/src/cmd/fileio/trace_batch.rs @@ -0,0 +1,180 @@ +//! `imageTrace.batchFolder` (#4921): Image Trace › Batch Trace Folder. Each image in a folder is +//! opened, traced with a preset (and expanded when asked), saved into a destination folder under +//! its own name, and closed again, whether it traced or not. + +use serde_json::Value; +#[cfg(not(target_arch = "wasm32"))] +use serde_json::json; + +use super::super::{Result, Session, bad}; +#[cfg(not(target_arch = "wasm32"))] +use super::super::{bool_or, str_param}; + +#[cfg(target_arch = "wasm32")] +pub(super) fn batch_folder(_: &mut Session, _: &Value) -> Result { + Err(bad("imageTrace.batchFolder", "no file system here")) +} + +#[cfg(not(target_arch = "wasm32"))] +/// The image files a batch traces, by extension. +const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"]; +#[cfg(not(target_arch = "wasm32"))] +/// Caps on a batch (folders and MCP payloads are untrusted). +const MAX_FILES: usize = 500; +#[cfg(not(target_arch = "wasm32"))] +const MAX_DEPTH: usize = 8; +#[cfg(not(target_arch = "wasm32"))] +const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"]; + +#[cfg(not(target_arch = "wasm32"))] +/// The image files in `folder` (and its subfolders with `deep`), sorted. +fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Result<()> { + if depth > MAX_DEPTH { + return Err(bad("imageTrace.batchFolder", format!("folders deeper than {MAX_DEPTH} levels"))); + } + let (entries, _) = super::list_dir(folder, MAX_FILES.saturating_mul(2))?; + let mut subdirs = vec![]; + for e in entries { + let name = e.get("name").and_then(Value::as_str).unwrap_or(""); + if name.is_empty() || name.starts_with('.') { + continue; + } + let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned(); + match e.get("kind").and_then(Value::as_str) { + Some("file") if IMAGE_EXTS.contains(&super::extension(&path).as_str()) => out.push(path), + Some("folder") if deep => subdirs.push(path), + _ => {} + } + if out.len() > MAX_FILES { + return Err(bad("imageTrace.batchFolder", format!("more than {MAX_FILES} images"))); + } + } + for d in subdirs { + images(&d, deep, depth + 1, out)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn batch_folder(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.batchFolder"; + let folder = str_param(p, "folder").map(super::absolute_path).ok_or_else(|| bad(C, "missing `folder`"))?; + let dest = str_param(p, "destinationFolder").map(super::absolute_path).ok_or_else(|| bad(C, "missing `destinationFolder`"))?; + let format = str_param(p, "format").unwrap_or("vectorcraft"); + if !FORMATS.contains(&format) { + return Err(bad(C, format!("`format` must be one of {}", FORMATS.join(", ")))); + } + let preset = str_param(p, "preset").unwrap_or("Default").to_string(); + let presets = s.execute("imageTrace.presets", &json!({}))?; + if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { + return Err(bad(C, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); + } + let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + super::may_read(&folder)?; + super::may_write(&dest)?; + let mut files = vec![]; + images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?; + files.sort(); + if files.is_empty() { + return Err(bad(C, "no images in the folder")); + } + std::fs::create_dir_all(&dest).map_err(|e| bad(C, format!("{dest}: {e}")))?; + let ext = super::save_format(Some(format), None).map_err(|e| bad(C, e))?.extensions.first().copied().unwrap_or(format); + let active = s.active_index(); + let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::::new()); + for path in &files { + let opened_before = s.documents().len(); + let one = |s: &mut Session| -> Result { + s.execute("document.open", &json!({ "path": path }))?; + s.execute("select.all", &json!({}))?; + s.execute(trace, &json!({ "preset": preset }))?; + let stem = super::file_stem(path); + let free = (1..=999u32) + .map(|i| if i == 1 { format!("{stem}.{ext}") } else { format!("{stem}-{i}.{ext}") }) + .map(|n| std::path::Path::new(&dest).join(n).to_string_lossy().into_owned()) + .find(|o| !taken.contains(o) && !std::path::Path::new(o).exists()) + .ok_or_else(|| bad(C, "every numbered name for the result is taken"))?; + s.execute("document.save", &json!({ "path": free, "format": format }))?; + Ok(free) + }; + let result = one(s); + // The image's document closes whatever happened, so a failure leaves no tab behind. + if s.documents().len() > opened_before + && let Some(i) = s.active_index() + { + let _ = s.execute("file.close", &json!({ "index": i })); + } + match result { + Ok(out) => { + taken.push(out.clone()); + traced.push(json!({ "path": path, "output": out })); + } + Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })), + } + } + if let Some(i) = active.filter(|i| *i < s.documents().len()) { + s.set_active(i); + } + Ok(json!({ "traced": traced, "failed": failed, "format": format })) +} + +#[cfg(test)] +#[cfg(not(target_arch = "wasm32"))] +mod tests { + use serde_json::json; + + use crate::Session; + + fn png(path: &std::path::Path, dark: bool) { + let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255])); + for y in 6..18 { + for x in 6..18 { + img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) }); + } + } + img.save(path).unwrap(); + } + + /// #4921: each image of the folder is traced and saved under its own name; a file that isn't + /// an image is left alone, one that can't be read is reported, and every document the batch + /// opened is closed again, the active one staying active. + #[test] + fn batch_trace_folder_traces_and_saves_each_image() { + let dir = std::env::temp_dir().join(format!("vc-batch-trace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + png(&src.join("logo.png"), true); + png(&src.join("mark.png"), false); + std::fs::write(src.join("notes.txt"), "not an image").unwrap(); + std::fs::write(src.join("broken.png"), b"not a png").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let docs = s.documents().len(); + let r = s.execute("imageTrace.batchFolder", &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap(); + assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png")); + let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["logo.svg", "mark.svg"]); + let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap(); + assert!(svg.contains(">(), ["Pack", "Pack 2"]); } } + +/// Object › Image Trace › Batch Trace Folder (#4921) with params `p`: the source folder and then +/// the destination folder are asked for when not given; the status bar says how many images were +/// traced and how many weren't. +pub(crate) fn batch_trace(app: &mut VectorcraftApp, p: &Value) -> Result { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + for key in ["folder", "destinationFolder"] { + if p.get(key).is_none() { + p[key] = json!(crate::picks::folder(app).ok_or("cancelled")?); + } + } + let r = app.session.execute("imageTrace.batchFolder", &p).map_err(|e| e.to_string())?; + let traced = r["traced"].as_array().map_or(0, Vec::len) as u64; + let failed = r["failed"].as_array().map_or(0, Vec::len) as u64; + let mut status = crate::i18n::msg_n(traced, "Traced {n} image", "Traced {n} images", &[]); + if failed > 0 { + status = format!("{status}; {}", crate::i18n::msg_n(failed, "{n} image couldn't be traced", "{n} images couldn't be traced", &[])); + } + app.status(status); + Ok(r) +} + +#[cfg(test)] +mod batch_trace_tests { + use serde_json::json; + + use crate::VectorcraftApp; + + /// #4921: Batch Trace Folder from the menu asks for the source folder, then the destination, + /// traces each image there and reports the count; cancelling either does nothing. + #[test] + fn batch_trace_folder_asks_for_both_folders() { + let dir = std::env::temp_dir().join(format!("vc-ui-batch-trace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + image::RgbaImage::from_pixel(16, 16, image::Rgba([0, 0, 0, 255])).save(src.join("a.png")).unwrap(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let mut picks = vec![out.to_string_lossy().into_owned(), src.to_string_lossy().into_owned()]; + app.services.pick_folder = Some(Box::new(move || picks.pop())); + crate::menus::invoke(&mut app, "imageTrace.batchFolder", json!({})); + assert!(out.join("a.vectorcraft").exists(), "{}", app.ui.status); + assert!(app.ui.status.starts_with("Traced 1 image"), "{}", app.ui.status); + assert!(app.session.documents().is_empty(), "the image's document is closed"); + app.services.pick_folder = Some(Box::new(|| None)); + assert_eq!(app.run("imageTrace.batchFolder", json!({})).unwrap_err(), "cancelled"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index c20e3b6504..8bf9b147d0 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -565,6 +565,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), + "imageTrace.batchFolder" => crate::io::batch_trace(app, p), crate::addons::document::EXPORT_ALL => crate::addons::document::export_all(app, p), "tool.setOption" => app.session.set_tool_option_cmd(p), "effect.dialog" => crate::dialogs::open_effect_dialog(app, p), diff --git a/docs/mcp.md b/docs/mcp.md index 6843b8cf66..75721fb753 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1880,6 +1880,13 @@ already walks Image Trace. Short agent entry points: Its journal entry records the saved preset's settings as `savedPreset`, so a replay traces with them after the preset is changed, renamed or deleted. In the app, `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. + `imageTrace.batchFolder {folder, destinationFolder, preset?, expand?, format?, includeSubdirs?}` (Object › Image + Trace › Batch Trace Folder) opens each image in `folder` (PNG, JPEG, TIFF, BMP, GIF, WebP, PSD), traces it with + `preset` (Default by default; with `expand`, as Make and Expand), saves it into `destinationFolder` as + `.` in `format` (`vectorcraft` by default; `svg`, `pdf`, `ai`, `eps`), with `-2`, `-3`… added when the + name is taken so no file is replaced, and closes it again whether it traced or not; the active document stays + active. Up to 500 images and 8 folder levels; not on the web. The app asks for both folders (#4921). + → `{traced: [{path, output}], failed: [{path, error}], format}` - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill of its front-most diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 25a6f25e05..730eeed041 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1571,6 +1571,10 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Export All Open Documents as PDF (or as SVG) asks for a folder and writes a copy of every open document there, each named after its document with `-2`, `-3`… added when a name is taken, so no file is replaced (`addon.document.exportAllOpen {folder, format?}`, #4920). Each copy is written as Save a Copy writes it: the documents keep their paths, titles and modified state, and the active one stays active. A document that can't be written is named in the status bar and the others are still written. Tests: `addons::document::tests::export_all_open_documents_writes_each_to_the_folder_picked` (ui-egui), `cmd::addons::document::tests::export_all_open_documents_writes_each_and_reports_failures` (engine). +## Batch Trace Folder (2026-11-01) + +A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Image Trace › Batch Trace Folder (`imageTrace.batchFolder`) asks for a folder of images and a destination folder, traces each image with a preset (optionally expanded) and saves it there under its own name as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps`, without replacing files, closing each image's document again and reporting the images it couldn't trace (#4921). Tests: `cmd::fileio::trace_batch::tests::batch_trace_folder_traces_and_saves_each_image` (engine), `io::batch_trace_tests::batch_trace_folder_asks_for_both_folders` (ui-egui). + ## Color Effects add-on: Find Nearest Swatch (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Color Effects › Find Nearest Swatch… lists each colour of the selection (fills and strokes, as ticked; solid colours and gradient stops, inside groups and type) with the three swatches of the chosen library closest to it by CIEDE2000 difference, with that difference (`addon.color.nearestSwatch`, #4923). The library is the document's swatches, a built-in library, or a library or colour book the user saved or loaded (no colour book data ships with VectorCraft). Apply gives each colour its nearest swatch as one undo step (`addon.color.applyNearestSwatch`): global and spot swatches link, and a library's swatches the colours take are added to the document first, so a spot colour stays spot. Remaining: typing a colour to look up in the dialog (the command takes `color`), and applying a match other than the nearest. Tests: `cmd::addons::color::nearest::tests` (engine), `addons::color::nearest::tests::find_nearest_swatch_lists_the_matches_and_applies_the_nearest` (ui-egui). @@ -1602,6 +1606,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-03 | minor | Enclosing Lasso is an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 934323ff77..e9bbe627aa 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -420,6 +420,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 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 | | 2026-11-04 | minor | Area type: Align Top / Center / Bottom / Justify Vertically buttons in the Properties panel (Paragraph section) and the Control panel set its vertical alignment in the frame, as Area Type Options does; turned off for frames with rows or columns and threaded frames (#3759); scores and estimates unchanged | | 2026-11-03 | minor | Enclosing Lasso selects fully enclosed objects with a freehand loop under Object › Plug-ins; scores and estimates unchanged. | From 7790c37eb302588a5ad4bb812529aec289953169 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:46:17 +0300 Subject: [PATCH 063/482] Batch Trace Folder: refuse a folder too big to list in full list_dir cuts its listing before sorting, so a cut listing could skip any image. The batch now stops with an error instead of tracing part of the folder. --- crates/engine/src/cmd/fileio/trace_batch.rs | 25 ++++++++++++++++++++- docs/mcp.md | 2 +- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/fileio/trace_batch.rs b/crates/engine/src/cmd/fileio/trace_batch.rs index 354af7c026..d2483440bb 100644 --- a/crates/engine/src/cmd/fileio/trace_batch.rs +++ b/crates/engine/src/cmd/fileio/trace_batch.rs @@ -32,7 +32,12 @@ fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Resu if depth > MAX_DEPTH { return Err(bad("imageTrace.batchFolder", format!("folders deeper than {MAX_DEPTH} levels"))); } - let (entries, _) = super::list_dir(folder, MAX_FILES.saturating_mul(2))?; + let max = MAX_FILES.saturating_mul(2); + let (entries, truncated) = super::list_dir(folder, max)?; + // The listing is cut before it is sorted, so a cut one could skip any image: refuse it. + if truncated { + return Err(bad("imageTrace.batchFolder", format!("{folder}: more than {max} files and folders"))); + } let mut subdirs = vec![]; for e in entries { let name = e.get("name").and_then(Value::as_str).unwrap_or(""); @@ -177,4 +182,22 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + /// A folder too big to list in full is refused rather than traced in part. + #[test] + fn batch_trace_folder_refuses_a_folder_it_cannot_list_in_full() { + let dir = std::env::temp_dir().join(format!("vc-batch-trace-big-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let src = dir.join("in"); + std::fs::create_dir_all(&src).unwrap(); + for i in 0..=super::MAX_FILES * 2 { + std::fs::write(src.join(format!("note-{i}.txt")), "").unwrap(); + } + png(&src.join("logo.png"), true); + let mut s = Session::new(); + let e = s.execute("imageTrace.batchFolder", &json!({"folder": src, "destinationFolder": dir.join("out")})).unwrap_err(); + assert!(e.to_string().contains("more than"), "{e}"); + assert!(!dir.join("out").exists(), "nothing traced"); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 75721fb753..75ede6e30b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1885,7 +1885,7 @@ already walks Image Trace. Short agent entry points: `preset` (Default by default; with `expand`, as Make and Expand), saves it into `destinationFolder` as `.` in `format` (`vectorcraft` by default; `svg`, `pdf`, `ai`, `eps`), with `-2`, `-3`… added when the name is taken so no file is replaced, and closes it again whether it traced or not; the active document stays - active. Up to 500 images and 8 folder levels; not on the web. The app asks for both folders (#4921). + active. Up to 500 images and 8 folder levels (a folder with more than 1,000 entries is refused); not on the web. The app asks for both folders (#4921). → `{traced: [{path, output}], failed: [{path, error}], format}` - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, From 33b57fb581233959c5ecac062aa6d325ca491f24 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 07:49:30 -0500 Subject: [PATCH 064/482] =?UTF-8?q?Batch=20Trace=20Folder:=20move=20to=20O?= =?UTF-8?q?bject=20=E2=80=BA=20Plug-ins=20as=20an=20add-on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Batch Trace Folder replaces a script, so it is now a Document Tools add-on command, addon.document.batchTraceFolder, under Object › Plug-ins › Document Tools (as Export All Open Documents is), and no longer in Object › Image Trace. Behaviour, caps and the refusal of a folder too big to list in full are unchanged; the tests move with it. The status messages have @msgplural rows in every catalog, as does the menu label. When some images trace and some don't, the status is one counted message ("Traced {n} images; not traced: {failed}") so it translates as a whole. --- crates/engine/src/cmd/addons/document.rs | 17 +- .../src/cmd/addons/document/batch_trace.rs | 127 +++++++++++ .../engine/src/cmd/addons/document/tests.rs | 76 ++++++- crates/engine/src/cmd/fileio.rs | 5 +- crates/engine/src/cmd/fileio/access.rs | 8 +- crates/engine/src/cmd/fileio/commands.rs | 9 - crates/engine/src/cmd/fileio/trace_batch.rs | 203 ------------------ crates/ui-egui/src/addons/document.rs | 33 ++- crates/ui-egui/src/addons/document/tests.rs | 26 +++ crates/ui-egui/src/i18n/bg.tsv | 5 + crates/ui-egui/src/i18n/bs.tsv | 5 + crates/ui-egui/src/i18n/ca.tsv | 5 + crates/ui-egui/src/i18n/cs.tsv | 5 + crates/ui-egui/src/i18n/da.tsv | 5 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 5 + crates/ui-egui/src/i18n/es.tsv | 5 + crates/ui-egui/src/i18n/fi.tsv | 5 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 5 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 5 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 5 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 5 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tr.tsv | 5 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/io.rs | 49 ----- crates/ui-egui/src/menus/run.rs | 2 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 4 +- 40 files changed, 431 insertions(+), 285 deletions(-) create mode 100644 crates/engine/src/cmd/addons/document/batch_trace.rs delete mode 100644 crates/engine/src/cmd/fileio/trace_batch.rs diff --git a/crates/engine/src/cmd/addons/document.rs b/crates/engine/src/cmd/addons/document.rs index 30548b80a7..52f7f3168e 100644 --- a/crates/engine/src/cmd/addons/document.rs +++ b/crates/engine/src/cmd/addons/document.rs @@ -1,9 +1,11 @@ //! Document Tools (`addon.document.*`), a built-in add-on: Save a Timestamped Copy writes a copy of //! the document named with the date and time through File › Save a Copy's save; New Symbols from //! Layers makes a symbol of each layer's art as New Symbol does; Export All Open Documents writes a -//! copy of every open document to one folder as Save a Copy does (#4920). Its submenu (Object › Plug-ins › -//! Document Tools) is the UI's. +//! copy of every open document to one folder as Save a Copy does (#4920); Batch Trace Folder traces +//! each image of a folder and saves the results to another ([`batch_trace`], #4921). Its submenu +//! (Object › Plug-ins › Document Tools) is the UI's. +mod batch_trace; #[cfg(test)] mod tests; @@ -14,7 +16,7 @@ use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolRegistration}; use super::super::brushsym::{instance_in_place, normalize, place_xf, store_symbol}; use super::super::fileio::{self, SaveMode}; -use super::super::{CommandSpec, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::super::{CommandSpec, always, bad, checked_ids_param, clock_date, cmd, date_param, has_doc, str_param, switch_or}; use crate::{Result, Session}; /// The most numbers (`-2`, `-3`…) tried after a timestamped name that is taken. @@ -40,6 +42,15 @@ pub fn specs() -> Vec { has_doc, export_all_open ), + cmd!( + "addon.document.batchTraceFolder", + "Batch Trace Folder", + ["Object", "Plug-ins", "Document Tools"], + None, + "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels; a folder with more than 1,000 entries is refused. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", + always, + batch_trace::batch_trace_folder + ), cmd!( "addon.document.symbolsFromLayers", "New Symbols from Layers", diff --git a/crates/engine/src/cmd/addons/document/batch_trace.rs b/crates/engine/src/cmd/addons/document/batch_trace.rs new file mode 100644 index 0000000000..0340fca183 --- /dev/null +++ b/crates/engine/src/cmd/addons/document/batch_trace.rs @@ -0,0 +1,127 @@ +//! Batch Trace Folder (`addon.document.batchTraceFolder`, #4921): each image in a folder is opened, +//! traced with a preset (and expanded when asked), saved into a destination folder under its own +//! name, and closed again, whether it traced or not. + +use serde_json::Value; +#[cfg(not(target_arch = "wasm32"))] +use serde_json::json; + +#[cfg(not(target_arch = "wasm32"))] +use super::super::super::fileio; +use super::super::super::{Result, Session, bad}; +#[cfg(not(target_arch = "wasm32"))] +use super::super::super::{bool_or, str_param}; + +/// The command id. +pub(super) const ID: &str = "addon.document.batchTraceFolder"; + +#[cfg(target_arch = "wasm32")] +pub(super) fn batch_trace_folder(_: &mut Session, _: &Value) -> Result { + Err(bad(ID, "no file system here")) +} + +#[cfg(not(target_arch = "wasm32"))] +/// The image files a batch traces, by extension. +const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"]; +#[cfg(not(target_arch = "wasm32"))] +/// Caps on a batch (folders and MCP payloads are untrusted). +pub(super) const MAX_FILES: usize = 500; +#[cfg(not(target_arch = "wasm32"))] +const MAX_DEPTH: usize = 8; +#[cfg(not(target_arch = "wasm32"))] +const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"]; + +#[cfg(not(target_arch = "wasm32"))] +/// The image files in `folder` (and its subfolders with `deep`), sorted. +fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Result<()> { + if depth > MAX_DEPTH { + return Err(bad(ID, format!("folders deeper than {MAX_DEPTH} levels"))); + } + let max = MAX_FILES.saturating_mul(2); + let (entries, truncated) = fileio::list_dir(folder, max)?; + // The listing is cut before it is sorted, so a cut one could skip any image: refuse it. + if truncated { + return Err(bad(ID, format!("{folder}: more than {max} files and folders"))); + } + let mut subdirs = vec![]; + for e in entries { + let name = e.get("name").and_then(Value::as_str).unwrap_or(""); + if name.is_empty() || name.starts_with('.') { + continue; + } + let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned(); + match e.get("kind").and_then(Value::as_str) { + Some("file") if IMAGE_EXTS.contains(&fileio::extension(&path).as_str()) => out.push(path), + Some("folder") if deep => subdirs.push(path), + _ => {} + } + if out.len() > MAX_FILES { + return Err(bad(ID, format!("more than {MAX_FILES} images"))); + } + } + for d in subdirs { + images(&d, deep, depth + 1, out)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn batch_trace_folder(s: &mut Session, p: &Value) -> Result { + let folder = str_param(p, "folder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `folder`"))?; + let dest = str_param(p, "destinationFolder").map(fileio::absolute_path).ok_or_else(|| bad(ID, "missing `destinationFolder`"))?; + let format = str_param(p, "format").unwrap_or("vectorcraft"); + if !FORMATS.contains(&format) { + return Err(bad(ID, format!("`format` must be one of {}", FORMATS.join(", ")))); + } + let preset = str_param(p, "preset").unwrap_or("Default").to_string(); + let presets = s.execute("imageTrace.presets", &json!({}))?; + if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { + return Err(bad(ID, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); + } + let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; + fileio::may_read(&folder)?; + fileio::may_write(&dest)?; + let mut files = vec![]; + images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?; + files.sort(); + if files.is_empty() { + return Err(bad(ID, "no images in the folder")); + } + std::fs::create_dir_all(&dest).map_err(|e| bad(ID, format!("{dest}: {e}")))?; + let ext = fileio::save_format(Some(format), None).map_err(|e| bad(ID, e))?.extensions.first().copied().unwrap_or(format); + let active = s.active_index(); + let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::::new()); + for path in &files { + let opened_before = s.documents().len(); + let one = |s: &mut Session| -> Result { + s.execute("document.open", &json!({ "path": path }))?; + s.execute("select.all", &json!({}))?; + s.execute(trace, &json!({ "preset": preset }))?; + let stem = fileio::file_stem(path); + // Names this batch already took count as taken, as do files on disk. + let free = super::free_name(&dest, &stem, ext, |o| taken.iter().any(|t| t == o) || std::path::Path::new(o).exists()) + .ok_or_else(|| bad(ID, "every numbered name for the result is taken"))?; + s.execute("document.save", &json!({ "path": free, "format": format }))?; + Ok(free) + }; + let result = one(s); + // The image's document closes whatever happened, so a failure leaves no tab behind. + if s.documents().len() > opened_before + && let Some(i) = s.active_index() + { + // A just-opened image has no work to lose; if closing fails, one extra tab stays open. + let _ = s.execute("file.close", &json!({ "index": i })); + } + match result { + Ok(out) => { + taken.push(out.clone()); + traced.push(json!({ "path": path, "output": out })); + } + Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })), + } + } + if let Some(i) = active.filter(|i| *i < s.documents().len()) { + s.set_active(i); + } + Ok(json!({ "traced": traced, "failed": failed, "format": format })) +} diff --git a/crates/engine/src/cmd/addons/document/tests.rs b/crates/engine/src/cmd/addons/document/tests.rs index 562a389e8a..a1bc5afff6 100644 --- a/crates/engine/src/cmd/addons/document/tests.rs +++ b/crates/engine/src/cmd/addons/document/tests.rs @@ -1,5 +1,5 @@ //! Document Tools' commands: the timestamped copy's name and place with the document left as it -//! was, symbols made of layers, and bad params refused. +//! was, symbols made of layers, a folder of images traced, and bad params refused. use std::path::{Path, PathBuf}; @@ -276,3 +276,77 @@ fn export_all_open_documents_keeps_every_page_and_artboard() { assert!(w > 19.0 && w < 30.0, "the SVG shows the art (the square on the second artboard), not the first artboard: viewBox {view}"); let _ = std::fs::remove_dir_all(&dir); } + +/// A 24×24 white PNG with a dark (or red) square in it. +#[cfg(not(target_arch = "wasm32"))] +fn png(path: &Path, dark: bool) { + let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255])); + for y in 6..18 { + for x in 6..18 { + img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) }); + } + } + img.save(path).unwrap(); +} + +/// #4921: each image of the folder is traced and saved under its own name; a file that isn't an +/// image is left alone, one that can't be read is reported, and every document the batch opened +/// is closed again, the active one staying active. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_trace_folder_traces_and_saves_each_image() { + const C: &str = "addon.document.batchTraceFolder"; + let dir = folder("batch-trace"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + png(&src.join("logo.png"), true); + png(&src.join("mark.png"), false); + std::fs::write(src.join("notes.txt"), "not an image").unwrap(); + std::fs::write(src.join("broken.png"), b"not a png").unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let docs = s.documents().len(); + let r = s.execute(C, &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap(); + assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}"); + assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); + assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png")); + let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["logo.svg", "mark.svg"]); + let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap(); + assert!(svg.contains(" Result<()> { +pub(crate) fn may_read(path: &str) -> Result<()> { #[cfg(test)] touch(path); crate::file_access::check_read(path).map_err(EngineError::Other) @@ -44,7 +44,7 @@ pub(crate) fn touched(f: impl FnOnce() -> T) -> (T, Vec) { /// `path` checked for writing against the automation roots in force. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn may_write(path: &str) -> Result<()> { +pub(crate) fn may_write(path: &str) -> Result<()> { crate::file_access::check_write(path).map_err(EngineError::Other) } @@ -169,7 +169,7 @@ pub(super) fn file_list(_: &mut Session, p: &Value) -> Result { /// The entries of folder `path`, sorted by name: at most `max`, and whether there were more. A /// link isn't followed: its target may lie outside the automation roots. #[cfg(not(target_arch = "wasm32"))] -pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { +pub(crate) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { may_read(path)?; let dir = std::fs::read_dir(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; let mut entries: Vec<(String, Value)> = vec![]; @@ -195,7 +195,7 @@ pub(super) fn list_dir(path: &str, max: usize) -> Result<(Vec, bool)> { } #[cfg(target_arch = "wasm32")] -pub(super) fn list_dir(_: &str, _: usize) -> Result<(Vec, bool)> { +pub(crate) fn list_dir(_: &str, _: usize) -> Result<(Vec, bool)> { Err(EngineError::Other("no file system here".into())) } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 16d85cbaf2..5b734c5a26 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -112,15 +112,6 @@ pub fn specs() -> Vec { has_doc, batch::batch ), - cmd!( - "imageTrace.batchFolder", - "Batch Trace Folder", - ["Object", "Image Trace"], - None, - "{folder, destinationFolder, preset?: name (imageTrace.presets; default: Default), expand?: false (true: trace and expand, as Make and Expand), format?: vectorcraft (default)|svg|pdf|ai|eps, includeSubdirs?: false} open each image in folder (png, jpg, tif, bmp, gif, webp, psd), select it, trace it with the preset, save it into destinationFolder as . (-2, -3… added when that name is taken, so no file is replaced) and close it again, whether it traced or not; the document that was active stays active. Caps: 500 images, 8 folder levels. Not on the web (no file system) → {traced: [{path, output}], failed: [{path, error}], format} (#4921)", - always, - super::trace_batch::batch_folder - ), cmd!( "action.batch", "Batch…", diff --git a/crates/engine/src/cmd/fileio/trace_batch.rs b/crates/engine/src/cmd/fileio/trace_batch.rs deleted file mode 100644 index d2483440bb..0000000000 --- a/crates/engine/src/cmd/fileio/trace_batch.rs +++ /dev/null @@ -1,203 +0,0 @@ -//! `imageTrace.batchFolder` (#4921): Image Trace › Batch Trace Folder. Each image in a folder is -//! opened, traced with a preset (and expanded when asked), saved into a destination folder under -//! its own name, and closed again, whether it traced or not. - -use serde_json::Value; -#[cfg(not(target_arch = "wasm32"))] -use serde_json::json; - -use super::super::{Result, Session, bad}; -#[cfg(not(target_arch = "wasm32"))] -use super::super::{bool_or, str_param}; - -#[cfg(target_arch = "wasm32")] -pub(super) fn batch_folder(_: &mut Session, _: &Value) -> Result { - Err(bad("imageTrace.batchFolder", "no file system here")) -} - -#[cfg(not(target_arch = "wasm32"))] -/// The image files a batch traces, by extension. -const IMAGE_EXTS: [&str; 10] = ["png", "jpg", "jpeg", "tif", "tiff", "bmp", "gif", "webp", "psd", "psb"]; -#[cfg(not(target_arch = "wasm32"))] -/// Caps on a batch (folders and MCP payloads are untrusted). -const MAX_FILES: usize = 500; -#[cfg(not(target_arch = "wasm32"))] -const MAX_DEPTH: usize = 8; -#[cfg(not(target_arch = "wasm32"))] -const FORMATS: [&str; 5] = ["vectorcraft", "svg", "pdf", "ai", "eps"]; - -#[cfg(not(target_arch = "wasm32"))] -/// The image files in `folder` (and its subfolders with `deep`), sorted. -fn images(folder: &str, deep: bool, depth: usize, out: &mut Vec) -> Result<()> { - if depth > MAX_DEPTH { - return Err(bad("imageTrace.batchFolder", format!("folders deeper than {MAX_DEPTH} levels"))); - } - let max = MAX_FILES.saturating_mul(2); - let (entries, truncated) = super::list_dir(folder, max)?; - // The listing is cut before it is sorted, so a cut one could skip any image: refuse it. - if truncated { - return Err(bad("imageTrace.batchFolder", format!("{folder}: more than {max} files and folders"))); - } - let mut subdirs = vec![]; - for e in entries { - let name = e.get("name").and_then(Value::as_str).unwrap_or(""); - if name.is_empty() || name.starts_with('.') { - continue; - } - let path = std::path::Path::new(folder).join(name).to_string_lossy().into_owned(); - match e.get("kind").and_then(Value::as_str) { - Some("file") if IMAGE_EXTS.contains(&super::extension(&path).as_str()) => out.push(path), - Some("folder") if deep => subdirs.push(path), - _ => {} - } - if out.len() > MAX_FILES { - return Err(bad("imageTrace.batchFolder", format!("more than {MAX_FILES} images"))); - } - } - for d in subdirs { - images(&d, deep, depth + 1, out)?; - } - Ok(()) -} - -#[cfg(not(target_arch = "wasm32"))] -pub(super) fn batch_folder(s: &mut Session, p: &Value) -> Result { - const C: &str = "imageTrace.batchFolder"; - let folder = str_param(p, "folder").map(super::absolute_path).ok_or_else(|| bad(C, "missing `folder`"))?; - let dest = str_param(p, "destinationFolder").map(super::absolute_path).ok_or_else(|| bad(C, "missing `destinationFolder`"))?; - let format = str_param(p, "format").unwrap_or("vectorcraft"); - if !FORMATS.contains(&format) { - return Err(bad(C, format!("`format` must be one of {}", FORMATS.join(", ")))); - } - let preset = str_param(p, "preset").unwrap_or("Default").to_string(); - let presets = s.execute("imageTrace.presets", &json!({}))?; - if !presets["presets"].as_array().into_iter().flatten().any(|q| q["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(&preset))) { - return Err(bad(C, format!("no tracing preset `{preset}` (see imageTrace.presets)"))); - } - let trace = if bool_or(p, "expand", false) { "imageTrace.makeAndExpand" } else { "imageTrace.make" }; - super::may_read(&folder)?; - super::may_write(&dest)?; - let mut files = vec![]; - images(&folder, bool_or(p, "includeSubdirs", false), 0, &mut files)?; - files.sort(); - if files.is_empty() { - return Err(bad(C, "no images in the folder")); - } - std::fs::create_dir_all(&dest).map_err(|e| bad(C, format!("{dest}: {e}")))?; - let ext = super::save_format(Some(format), None).map_err(|e| bad(C, e))?.extensions.first().copied().unwrap_or(format); - let active = s.active_index(); - let (mut traced, mut failed, mut taken) = (vec![], vec![], Vec::::new()); - for path in &files { - let opened_before = s.documents().len(); - let one = |s: &mut Session| -> Result { - s.execute("document.open", &json!({ "path": path }))?; - s.execute("select.all", &json!({}))?; - s.execute(trace, &json!({ "preset": preset }))?; - let stem = super::file_stem(path); - let free = (1..=999u32) - .map(|i| if i == 1 { format!("{stem}.{ext}") } else { format!("{stem}-{i}.{ext}") }) - .map(|n| std::path::Path::new(&dest).join(n).to_string_lossy().into_owned()) - .find(|o| !taken.contains(o) && !std::path::Path::new(o).exists()) - .ok_or_else(|| bad(C, "every numbered name for the result is taken"))?; - s.execute("document.save", &json!({ "path": free, "format": format }))?; - Ok(free) - }; - let result = one(s); - // The image's document closes whatever happened, so a failure leaves no tab behind. - if s.documents().len() > opened_before - && let Some(i) = s.active_index() - { - let _ = s.execute("file.close", &json!({ "index": i })); - } - match result { - Ok(out) => { - taken.push(out.clone()); - traced.push(json!({ "path": path, "output": out })); - } - Err(e) => failed.push(json!({ "path": path, "error": e.to_string() })), - } - } - if let Some(i) = active.filter(|i| *i < s.documents().len()) { - s.set_active(i); - } - Ok(json!({ "traced": traced, "failed": failed, "format": format })) -} - -#[cfg(test)] -#[cfg(not(target_arch = "wasm32"))] -mod tests { - use serde_json::json; - - use crate::Session; - - fn png(path: &std::path::Path, dark: bool) { - let mut img = image::RgbaImage::from_pixel(24, 24, image::Rgba([255, 255, 255, 255])); - for y in 6..18 { - for x in 6..18 { - img.put_pixel(x, y, if dark { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([200, 30, 30, 255]) }); - } - } - img.save(path).unwrap(); - } - - /// #4921: each image of the folder is traced and saved under its own name; a file that isn't - /// an image is left alone, one that can't be read is reported, and every document the batch - /// opened is closed again, the active one staying active. - #[test] - fn batch_trace_folder_traces_and_saves_each_image() { - let dir = std::env::temp_dir().join(format!("vc-batch-trace-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let (src, out) = (dir.join("in"), dir.join("out")); - std::fs::create_dir_all(&src).unwrap(); - png(&src.join("logo.png"), true); - png(&src.join("mark.png"), false); - std::fs::write(src.join("notes.txt"), "not an image").unwrap(); - std::fs::write(src.join("broken.png"), b"not a png").unwrap(); - let mut s = Session::new(); - s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); - let docs = s.documents().len(); - let r = s.execute("imageTrace.batchFolder", &json!({"folder": src, "destinationFolder": out, "format": "svg", "expand": true})).unwrap(); - assert_eq!(r["traced"].as_array().unwrap().len(), 2, "{r}"); - assert_eq!(r["failed"].as_array().unwrap().len(), 1, "{r}"); - assert!(r["failed"][0]["path"].as_str().unwrap().ends_with("broken.png")); - let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); - names.sort(); - assert_eq!(names, ["logo.svg", "mark.svg"]); - let svg = std::fs::read_to_string(out.join("logo.svg")).unwrap(); - assert!(svg.contains(" Vec { Item::Cmd("Save a Timestamped Copy", SAVE_COPY, json!({})), Item::Cmd("Export All Open Documents as PDF", EXPORT_ALL, json!({ "format": "pdf" })), Item::Cmd("Export All Open Documents as SVG", EXPORT_ALL, json!({ "format": "svg" })), + Item::Cmd("Batch Trace Folder", BATCH_TRACE, json!({})), Item::Sep, Item::Cmd("New Symbols from Layers", SYMBOLS, json!({})), Item::Cmd("Convert Layers to Symbols", SYMBOLS, json!({ "replace": true })), @@ -62,5 +66,32 @@ pub(crate) fn export_all(app: &mut VectorcraftApp, p: &Value) -> Result Result { + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + for key in ["folder", "destinationFolder"] { + if p.get(key).is_none() { + p[key] = json!(crate::picks::folder(app).ok_or("cancelled")?); + } + } + let r = app.session.execute(BATCH_TRACE, &p).map_err(|e| e.to_string())?; + let traced = r["traced"].as_array().map_or(0, Vec::len) as u64; + let failed = r["failed"].as_array().map_or(0, Vec::len) as u64; + // One count per message: a count inside another counted message would read as the wrong + // template when the status is translated. + let status = if failed == 0 { + crate::i18n::msg_n(traced, "Traced {n} image", "Traced {n} images", &[]) + } else if traced == 0 { + crate::i18n::msg_n(failed, "{n} image couldn't be traced", "{n} images couldn't be traced", &[]) + } else { + let failed = failed.to_string(); + crate::i18n::msg_n(traced, "Traced {n} image; not traced: {failed}", "Traced {n} images; not traced: {failed}", &[("failed", &failed)]) + }; + app.status(status); + Ok(r) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/document/tests.rs b/crates/ui-egui/src/addons/document/tests.rs index 4a2f96bd20..69cb75091f 100644 --- a/crates/ui-egui/src/addons/document/tests.rs +++ b/crates/ui-egui/src/addons/document/tests.rs @@ -123,3 +123,29 @@ fn export_all_open_documents_writes_each_to_the_folder_picked() { assert!(app.session.execute(super::EXPORT_ALL, &json!({"folder": out, "format": "doc"})).is_err()); let _ = std::fs::remove_dir_all(&dir); } + +/// #4921: Batch Trace Folder from Object › Plug-ins › Document Tools asks for the folder of images, +/// then the destination, traces each image there and reports the count (a status the catalogs +/// translate); cancelling either does nothing. +#[test] +fn batch_trace_folder_asks_for_both_folders() { + let dir = folder("batch-trace"); + let (src, out) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&src).unwrap(); + image::RgbaImage::from_pixel(16, 16, image::Rgba([0, 0, 0, 255])).save(src.join("a.png")).unwrap(); + std::fs::write(src.join("b.png"), b"not a png").unwrap(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let mut picks = vec![out.to_string_lossy().into_owned(), src.to_string_lossy().into_owned()]; + app.services.pick_folder = Some(Box::new(move || picks.pop())); + click(&mut app, "Batch Trace Folder"); + assert!(out.join("a.vectorcraft").exists(), "{}", app.ui.status); + assert_eq!(app.ui.status, "Traced 1 image; not traced: 1"); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_eq!(crate::i18n::message(de, &app.ui.status), "1 Bild nachgezeichnet; nicht nachgezeichnet: 1"); + assert_eq!(crate::i18n::message(de, "Traced 2 images"), "2 Bilder nachgezeichnet"); + assert_eq!(crate::i18n::message(de, "2 images couldn't be traced"), "2 Bilder konnten nicht nachgezeichnet werden"); + assert!(app.session.documents().is_empty(), "the images' documents are closed"); + app.services.pick_folder = Some(Box::new(|| None)); + assert_eq!(app.run(super::BATCH_TRACE, json!({})).unwrap_err(), "cancelled"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index ac5f629c19..6100b0b5cd 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6111,6 +6111,11 @@ breakText Glyphs Глифи Export All Open Documents as SVG Експортиране на всички отворени документи като SVG @msgplural Exported {n} document|Exported {n} documents Експортиран е {n} документ|Експортирани са {n} документа @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Експортиран е {n} документ; {title} не беше записан: {error}|Експортирани са {n} документа; {title} не беше записан: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Пакетно трасиране на папка +@msgplural Traced {n} image|Traced {n} images Трасирано е {n} изображение|Трасирани са {n} изображения +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} изображение не можа да бъде трасирано|{n} изображения не можаха да бъдат трасирани +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Трасирано е {n} изображение; нетрасирани: {failed}|Трасирани са {n} изображения; нетрасирани: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип на символа: Dynamic Symbol Динамичен символ diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index c4280273c2..e2aff10a9e 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6145,6 +6145,11 @@ shape Open Otvoren Export All Open Documents as SVG Izvezi sve otvorene dokumente kao SVG @msgplural Exported {n} document|Exported {n} documents Izvezen je {n} dokument|Izvezena su {n} dokumenta|Izvezeno je {n} dokumenata @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Izvezen je {n} dokument; {title} nije zapisan: {error}|Izvezena su {n} dokumenta; {title} nije zapisan: {error}|Izvezeno je {n} dokumenata; {title} nije zapisan: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Paketno praćenje foldera +@msgplural Traced {n} image|Traced {n} images Praćena je {n} slika|Praćene su {n} slike|Praćeno je {n} slika +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} slika nije mogla biti praćena|{n} slike nisu mogle biti praćene|{n} slika nije moglo biti praćeno +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Praćena je {n} slika; nije praćeno: {failed}|Praćene su {n} slike; nije praćeno: {failed}|Praćeno je {n} slika; nije praćeno: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Vrsta simbola: Dynamic Symbol Dinamički simbol diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9d5ce938df..5c5f7f9381 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6245,6 +6245,11 @@ breakText Glyphs Glifs Export All Open Documents as SVG Exporta tots els documents oberts com a SVG @msgplural Exported {n} document|Exported {n} documents S’ha exportat {n} document|S’han exportat {n} documents @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} S’ha exportat {n} document; no s’ha escrit {title}: {error}|S’han exportat {n} documents; no s’ha escrit {title}: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Traçat per lots d’una carpeta +@msgplural Traced {n} image|Traced {n} images S’ha traçat {n} imatge|S’han traçat {n} imatges +@msgplural {n} image couldn't be traced|{n} images couldn't be traced No s’ha pogut traçar {n} imatge|No s’han pogut traçar {n} imatges +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} S’ha traçat {n} imatge; no traçades: {failed}|S’han traçat {n} imatges; no traçades: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipus de símbol: Dynamic Symbol Símbol dinàmic diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 4a3fe56955..77a0b8d1d4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6259,6 +6259,11 @@ breakText Glyphs Glyfy Export All Open Documents as SVG Exportovat všechny otevřené dokumenty jako SVG @msgplural Exported {n} document|Exported {n} documents Exportován {n} dokument|Exportovány {n} dokumenty|Exportováno {n} dokumentů @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Exportován {n} dokument; {title} nebyl zapsán: {error}|Exportovány {n} dokumenty; {title} nebyl zapsán: {error}|Exportováno {n} dokumentů; {title} nebyl zapsán: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Dávková vektorizace složky +@msgplural Traced {n} image|Traced {n} images Vektorizován {n} obraz|Vektorizovány {n} obrazy|Vektorizováno {n} obrazů +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} obraz nebylo možné vektorizovat|{n} obrazy nebylo možné vektorizovat|{n} obrazů nebylo možné vektorizovat +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Vektorizován {n} obraz; nevektorizováno: {failed}|Vektorizovány {n} obrazy; nevektorizováno: {failed}|Vektorizováno {n} obrazů; nevektorizováno: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Typ symbolu: Dynamic Symbol Dynamický symbol diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index b671f79d14..d591b57262 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6127,6 +6127,11 @@ breakText Glyphs Glyffer Export All Open Documents as SVG Eksportér alle åbne dokumenter som SVG @msgplural Exported {n} document|Exported {n} documents Eksporterede {n} dokument|Eksporterede {n} dokumenter @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Eksporterede {n} dokument; {title} blev ikke skrevet: {error}|Eksporterede {n} dokumenter; {title} blev ikke skrevet: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Batchvektorisér mappe +@msgplural Traced {n} image|Traced {n} images Vektoriserede {n} billede|Vektoriserede {n} billeder +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} billede kunne ikke vektoriseres|{n} billeder kunne ikke vektoriseres +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Vektoriserede {n} billede; ikke vektoriseret: {failed}|Vektoriserede {n} billeder; ikke vektoriseret: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symboltype: Dynamic Symbol Dynamisk symbol diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index f7c7faea08..d6d73bf0b0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5845,6 +5845,11 @@ breakText Glyphs Glyphen Export All Open Documents as SVG Alle geöffneten Dokumente als SVG exportieren @msgplural Exported {n} document|Exported {n} documents {n} Dokument exportiert|{n} Dokumente exportiert @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} Dokument exportiert; {title} wurde nicht geschrieben: {error}|{n} Dokumente exportiert; {title} wurde nicht geschrieben: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Ordner stapelweise nachzeichnen +@msgplural Traced {n} image|Traced {n} images {n} Bild nachgezeichnet|{n} Bilder nachgezeichnet +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} Bild konnte nicht nachgezeichnet werden|{n} Bilder konnten nicht nachgezeichnet werden +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} Bild nachgezeichnet; nicht nachgezeichnet: {failed}|{n} Bilder nachgezeichnet; nicht nachgezeichnet: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symboltyp: Dynamic Symbol Dynamisches Symbol diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 445720603a..448cd26a1d 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -6211,6 +6211,11 @@ breakText Glyphs Γλύφοι Export All Open Documents as SVG Εξαγωγή όλων των ανοιχτών εγγράφων ως SVG @msgplural Exported {n} document|Exported {n} documents Εξήχθη {n} έγγραφο|Εξήχθησαν {n} έγγραφα @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Εξήχθη {n} έγγραφο; το {title} δεν γράφτηκε: {error}|Εξήχθησαν {n} έγγραφα; το {title} δεν γράφτηκε: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Μαζική διανυσματοποίηση φακέλου +@msgplural Traced {n} image|Traced {n} images Διανυσματοποιήθηκε {n} εικόνα|Διανυσματοποιήθηκαν {n} εικόνες +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Δεν ήταν δυνατή η διανυσματοποίηση {n} εικόνας|Δεν ήταν δυνατή η διανυσματοποίηση {n} εικόνων +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Διανυσματοποιήθηκε {n} εικόνα; δεν διανυσματοποιήθηκαν: {failed}|Διανυσματοποιήθηκαν {n} εικόνες; δεν διανυσματοποιήθηκαν: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Τύπος συμβόλου: Dynamic Symbol Δυναμικό σύμβολο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c6950dae52..9de4042573 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -6201,6 +6201,11 @@ breakText Glyphs Glifos Export All Open Documents as SVG Exportar todos los documentos abiertos como SVG @msgplural Exported {n} document|Exported {n} documents Se exportó {n} documento|Se exportaron {n} documentos @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Se exportó {n} documento; no se escribió {title}: {error}|Se exportaron {n} documentos; no se escribió {title}: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Calcar carpeta por lotes +@msgplural Traced {n} image|Traced {n} images Se calcó {n} imagen|Se calcaron {n} imágenes +@msgplural {n} image couldn't be traced|{n} images couldn't be traced No se pudo calcar {n} imagen|No se pudieron calcar {n} imágenes +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Se calcó {n} imagen; sin calcar: {failed}|Se calcaron {n} imágenes; sin calcar: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipo de símbolo: Dynamic Symbol Símbolo dinámico diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ae6d114bbb..20317de484 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6289,6 +6289,11 @@ breakText Glyphs Merkit Export All Open Documents as SVG Vie kaikki avoimet asiakirjat SVG-muodossa @msgplural Exported {n} document|Exported {n} documents Vietiin {n} asiakirja|Vietiin {n} asiakirjaa @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Vietiin {n} asiakirja; {title} jäi kirjoittamatta: {error}|Vietiin {n} asiakirjaa; {title} jäi kirjoittamatta: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Jäljitä kansio erässä +@msgplural Traced {n} image|Traced {n} images Jäljitettiin {n} kuva|Jäljitettiin {n} kuvaa +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} kuvaa ei voitu jäljittää|{n} kuvaa ei voitu jäljittää +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Jäljitettiin {n} kuva; jäljittämättä: {failed}|Jäljitettiin {n} kuvaa; jäljittämättä: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symbolin tyyppi: Dynamic Symbol Dynaaminen symboli diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3caae7f683..167792f461 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6254,6 +6254,11 @@ breakText Glyphs Glyphes Export All Open Documents as SVG Exporter tous les documents ouverts en SVG @msgplural Exported {n} document|Exported {n} documents {n} document exporté|{n} documents exportés @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} document exporté; {title} n’a pas été écrit : {error}|{n} documents exportés; {title} n’a pas été écrit : {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Vectoriser un dossier par lots +@msgplural Traced {n} image|Traced {n} images {n} image vectorisée|{n} images vectorisées +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} image n’a pas pu être vectorisée|{n} images n’ont pas pu être vectorisées +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} image vectorisée; non vectorisées : {failed}|{n} images vectorisées; non vectorisées : {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Type de symbole : Dynamic Symbol Symbole dynamique diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 3bc6b98619..4eceaca1e4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -6243,6 +6243,11 @@ breakText Glyphs Glifák Export All Open Documents as SVG Az összes megnyitott dokumentum exportálása SVG-ként @msgplural Exported {n} document|Exported {n} documents Exportált dokumentumok: {n} @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Exportált dokumentumok: {n}; {title} nem lett kiírva: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Mappa kötegelt vektorizálása +@msgplural Traced {n} image|Traced {n} images Vektorizált képek: {n} +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Nem vektorizálható képek: {n} +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Vektorizált képek: {n}; nem vektorizálható: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Szimbólum típusa: Dynamic Symbol Dinamikus szimbólum diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 7948e08ba4..0886dc7467 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6127,6 +6127,11 @@ breakText Glyphs Glif Export All Open Documents as SVG Ekspor Semua Dokumen Terbuka sebagai SVG @msgplural Exported {n} document|Exported {n} documents Berhasil mengekspor {n} dokumen @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Berhasil mengekspor {n} dokumen; {title} tidak ditulis: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Telusuri Folder secara Batch +@msgplural Traced {n} image|Traced {n} images Berhasil menelusuri {n} gambar +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} gambar tidak dapat ditelusuri +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Berhasil menelusuri {n} gambar; tidak ditelusuri: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Jenis simbol: Dynamic Symbol Simbol dinamis diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5a11b455e1..2bb5273022 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5879,6 +5879,11 @@ breakText Glyphs Glifi Export All Open Documents as SVG Esporta tutti i documenti aperti come SVG @msgplural Exported {n} document|Exported {n} documents Esportato {n} documento|Esportati {n} documenti @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Esportato {n} documento; {title} non è stato scritto: {error}|Esportati {n} documenti; {title} non è stato scritto: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Ricalca cartella in batch +@msgplural Traced {n} image|Traced {n} images Ricalcata {n} immagine|Ricalcate {n} immagini +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Impossibile ricalcare {n} immagine|Impossibile ricalcare {n} immagini +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Ricalcata {n} immagine; non ricalcate: {failed}|Ricalcate {n} immagini; non ricalcate: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipo di simbolo: Dynamic Symbol Simbolo dinamico diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 178aaef86f..f57d7c21f0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5944,6 +5944,11 @@ breakText Glyphs 字形 Export All Open Documents as SVG 開いているすべてのドキュメントを SVG として書き出し @msgplural Exported {n} document|Exported {n} documents {n} 個のドキュメントを書き出しました @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} 個のドキュメントを書き出しました; {title} は書き出されませんでした: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder フォルダーを一括トレース +@msgplural Traced {n} image|Traced {n} images {n} 個の画像をトレースしました +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} 個の画像をトレースできませんでした +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} 個の画像をトレースしました; トレースできなかった画像: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: シンボルの種類: Dynamic Symbol ダイナミックシンボル diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 0d806a2205..eff88f55b7 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6255,6 +6255,11 @@ breakText Glyphs გლიფები Export All Open Documents as SVG ყველა ღია დოკუმენტის ექსპორტი SVG-ად @msgplural Exported {n} document|Exported {n} documents ექსპორტირებულია დოკუმენტი ({n}) @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} ექსპორტირებულია დოკუმენტი ({n}); {title} არ ჩაიწერა: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder საქაღალდის პაკეტური ვექტორიზაცია +@msgplural Traced {n} image|Traced {n} images ვექტორიზებულია გამოსახულება ({n}) +@msgplural {n} image couldn't be traced|{n} images couldn't be traced ვერ მოხერხდა გამოსახულების ვექტორიზაცია ({n}) +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} ვექტორიზებულია გამოსახულება ({n}); ვერ მოხერხდა: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: სიმბოლოს ტიპი: Dynamic Symbol დინამიკური სიმბოლო diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a216b40368..90c4fe2eba 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5840,6 +5840,11 @@ breakText Glyphs 글리프 Export All Open Documents as SVG 열린 모든 문서를 SVG로 내보내기 @msgplural Exported {n} document|Exported {n} documents 문서 {n}개를 내보냈습니다 @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} 문서 {n}개를 내보냈습니다; {title}을(를) 쓰지 못했습니다: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder 폴더 일괄 추적 +@msgplural Traced {n} image|Traced {n} images 이미지 {n}개를 추적했습니다 +@msgplural {n} image couldn't be traced|{n} images couldn't be traced 이미지 {n}개를 추적하지 못했습니다 +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} 이미지 {n}개를 추적했습니다; 추적하지 못한 이미지: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: 심볼 유형: Dynamic Symbol 동적 심볼 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 3e15af341a..cd613117b3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6171,6 +6171,11 @@ breakText Glyphs Glyphs Export All Open Documents as SVG Alle geopende documenten exporteren als SVG @msgplural Exported {n} document|Exported {n} documents {n} document geëxporteerd|{n} documenten geëxporteerd @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} document geëxporteerd; {title} is niet geschreven: {error}|{n} documenten geëxporteerd; {title} is niet geschreven: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Map in batch traceren +@msgplural Traced {n} image|Traced {n} images {n} afbeelding getraceerd|{n} afbeeldingen getraceerd +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} afbeelding kon niet worden getraceerd|{n} afbeeldingen konden niet worden getraceerd +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} afbeelding getraceerd; niet getraceerd: {failed}|{n} afbeeldingen getraceerd; niet getraceerd: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symbooltype: Dynamic Symbol Dynamisch symbool diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index cc5d041e7f..ea81961c77 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -6114,6 +6114,11 @@ breakText Glyphs Glify Export All Open Documents as SVG Eksportuj wszystkie otwarte dokumenty jako SVG @msgplural Exported {n} document|Exported {n} documents Wyeksportowano {n} dokument|Wyeksportowano {n} dokumenty|Wyeksportowano {n} dokumentów @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Wyeksportowano {n} dokument; nie zapisano {title}: {error}|Wyeksportowano {n} dokumenty; nie zapisano {title}: {error}|Wyeksportowano {n} dokumentów; nie zapisano {title}: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Obrysuj folder wsadowo +@msgplural Traced {n} image|Traced {n} images Obrysowano {n} obraz|Obrysowano {n} obrazy|Obrysowano {n} obrazów +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Nie udało się obrysować {n} obrazu|Nie udało się obrysować {n} obrazów|Nie udało się obrysować {n} obrazów +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Obrysowano {n} obraz; nieobrysowane: {failed}|Obrysowano {n} obrazy; nieobrysowane: {failed}|Obrysowano {n} obrazów; nieobrysowane: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Typ symbolu: Dynamic Symbol Symbol dynamiczny diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0921b0c728..7bab708578 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6177,6 +6177,11 @@ breakText Glyphs Glifos Export All Open Documents as SVG Exportar todos os documentos abertos como SVG @msgplural Exported {n} document|Exported {n} documents {n} documento exportado|{n} documentos exportados @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} documento exportado; {title} não foi gravado: {error}|{n} documentos exportados; {title} não foi gravado: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Rastrear Pasta em Lote +@msgplural Traced {n} image|Traced {n} images {n} imagem rastreada|{n} imagens rastreadas +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Não foi possível rastrear {n} imagem|Não foi possível rastrear {n} imagens +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} imagem rastreada; não rastreadas: {failed}|{n} imagens rastreadas; não rastreadas: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Tipo de símbolo: Dynamic Symbol Símbolo dinâmico diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f620e86595..c0106d85a6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6236,6 +6236,11 @@ breakText Glyphs Глифы Export All Open Documents as SVG Экспортировать все открытые документы в SVG @msgplural Exported {n} document|Exported {n} documents Экспортирован {n} документ|Экспортировано {n} документа|Экспортировано {n} документов @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Экспортирован {n} документ; {title} не записан: {error}|Экспортировано {n} документа; {title} не записан: {error}|Экспортировано {n} документов; {title} не записан: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Пакетная трассировка папки +@msgplural Traced {n} image|Traced {n} images Трассировано {n} изображение|Трассировано {n} изображения|Трассировано {n} изображений +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Не удалось трассировать {n} изображение|Не удалось трассировать {n} изображения|Не удалось трассировать {n} изображений +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Трассировано {n} изображение; не трассировано: {failed}|Трассировано {n} изображения; не трассировано: {failed}|Трассировано {n} изображений; не трассировано: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип символа: Dynamic Symbol Динамический символ diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 23a96006a0..a8bfc433f8 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6311,6 +6311,11 @@ breakText Glyphs Glyfer Export All Open Documents as SVG Exportera alla öppna dokument som SVG @msgplural Exported {n} document|Exported {n} documents Exporterade {n} dokument|Exporterade {n} dokument @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Exporterade {n} dokument; {title} skrevs inte: {error}|Exporterade {n} dokument; {title} skrevs inte: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Batchvektorisera mapp +@msgplural Traced {n} image|Traced {n} images Vektoriserade {n} bild|Vektoriserade {n} bilder +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} bild kunde inte vektoriseras|{n} bilder kunde inte vektoriseras +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Vektoriserade {n} bild; ej vektoriserade: {failed}|Vektoriserade {n} bilder; ej vektoriserade: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Symboltyp: Dynamic Symbol Dynamisk symbol diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e16c913b71..83dcfca101 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6216,6 +6216,11 @@ breakText Glyphs Glifler Export All Open Documents as SVG Tüm Açık Belgeleri SVG Olarak Dışa Aktar @msgplural Exported {n} document|Exported {n} documents {n} belge dışa aktarıldı @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} {n} belge dışa aktarıldı; {title} yazılamadı: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Klasörü Toplu İzle +@msgplural Traced {n} image|Traced {n} images {n} resim izlendi +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} resim izlenemedi +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} {n} resim izlendi; izlenemeyen: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Sembol Türü: Dynamic Symbol Dinamik Sembol diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 49dd42a05c..d7391112ff 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5859,6 +5859,11 @@ breakText Glyphs Гліфи Export All Open Documents as SVG Експортувати всі відкриті документи як SVG @msgplural Exported {n} document|Exported {n} documents Експортовано {n} документ|Експортовано {n} документи|Експортовано {n} документів @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Експортовано {n} документ; {title} не записано: {error}|Експортовано {n} документи; {title} не записано: {error}|Експортовано {n} документів; {title} не записано: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Пакетне трасування папки +@msgplural Traced {n} image|Traced {n} images Трасовано {n} зображення|Трасовано {n} зображення|Трасовано {n} зображень +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Не вдалося трасувати {n} зображення|Не вдалося трасувати {n} зображення|Не вдалося трасувати {n} зображень +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Трасовано {n} зображення; не трасовано: {failed}|Трасовано {n} зображення; не трасовано: {failed}|Трасовано {n} зображень; не трасовано: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Тип символу: Dynamic Symbol Динамічний символ diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 0bfce04b8f..6028148443 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5860,6 +5860,11 @@ breakText Glyphs Glyph Export All Open Documents as SVG Xuất tất cả tài liệu đang mở dưới dạng SVG @msgplural Exported {n} document|Exported {n} documents Đã xuất {n} tài liệu @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} Đã xuất {n} tài liệu; không ghi được {title}: {error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder Vector hóa thư mục hàng loạt +@msgplural Traced {n} image|Traced {n} images Đã vector hóa {n} hình ảnh +@msgplural {n} image couldn't be traced|{n} images couldn't be traced Không thể vector hóa {n} hình ảnh +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} Đã vector hóa {n} hình ảnh; không vector hóa được: {failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: Kiểu ký hiệu: Dynamic Symbol Ký hiệu động diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e70d78656c..ce2089a0c1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -6100,6 +6100,11 @@ breakText Glyphs 字形 Export All Open Documents as SVG 将所有打开的文档导出为 SVG @msgplural Exported {n} document|Exported {n} documents 已导出 {n} 个文档 @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} 已导出 {n} 个文档; 未写入 {title}:{error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder 批量描摹文件夹 +@msgplural Traced {n} image|Traced {n} images 已描摹 {n} 个图像 +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} 个图像无法描摹 +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} 已描摹 {n} 个图像; 无法描摹:{failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: 符号类型: Dynamic Symbol 动态符号 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b4a60cc3bd..eead8f7d46 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5897,6 +5897,11 @@ breakText Glyphs 字符 Export All Open Documents as SVG 將所有開啟的文件匯出為 SVG @msgplural Exported {n} document|Exported {n} documents 已匯出 {n} 份文件 @msgplural Exported {n} document; {title} wasn't written: {error}|Exported {n} documents; {title} wasn't written: {error} 已匯出 {n} 份文件; 未寫入 {title}:{error} +# Document Tools add-on: Batch Trace Folder (#4921). + Batch Trace Folder 批次描圖資料夾 +@msgplural Traced {n} image|Traced {n} images 已描圖 {n} 個影像 +@msgplural {n} image couldn't be traced|{n} images couldn't be traced {n} 個影像無法描圖 +@msgplural Traced {n} image; not traced: {failed}|Traced {n} images; not traced: {failed} 已描圖 {n} 個影像; 無法描圖:{failed} # Symbol Options › Symbol Type (dynamic symbols) Symbol Type: 符號類型: Dynamic Symbol 動態符號 diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index ec05966f9c..4818a0c159 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -288,52 +288,3 @@ mod tests { assert_eq!(app.session.prefs.screen_export_presets.iter().map(|p| p.name.as_str()).collect::>(), ["Pack", "Pack 2"]); } } - -/// Object › Image Trace › Batch Trace Folder (#4921) with params `p`: the source folder and then -/// the destination folder are asked for when not given; the status bar says how many images were -/// traced and how many weren't. -pub(crate) fn batch_trace(app: &mut VectorcraftApp, p: &Value) -> Result { - let mut p = if p.is_object() { p.clone() } else { json!({}) }; - for key in ["folder", "destinationFolder"] { - if p.get(key).is_none() { - p[key] = json!(crate::picks::folder(app).ok_or("cancelled")?); - } - } - let r = app.session.execute("imageTrace.batchFolder", &p).map_err(|e| e.to_string())?; - let traced = r["traced"].as_array().map_or(0, Vec::len) as u64; - let failed = r["failed"].as_array().map_or(0, Vec::len) as u64; - let mut status = crate::i18n::msg_n(traced, "Traced {n} image", "Traced {n} images", &[]); - if failed > 0 { - status = format!("{status}; {}", crate::i18n::msg_n(failed, "{n} image couldn't be traced", "{n} images couldn't be traced", &[])); - } - app.status(status); - Ok(r) -} - -#[cfg(test)] -mod batch_trace_tests { - use serde_json::json; - - use crate::VectorcraftApp; - - /// #4921: Batch Trace Folder from the menu asks for the source folder, then the destination, - /// traces each image there and reports the count; cancelling either does nothing. - #[test] - fn batch_trace_folder_asks_for_both_folders() { - let dir = std::env::temp_dir().join(format!("vc-ui-batch-trace-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let (src, out) = (dir.join("in"), dir.join("out")); - std::fs::create_dir_all(&src).unwrap(); - image::RgbaImage::from_pixel(16, 16, image::Rgba([0, 0, 0, 255])).save(src.join("a.png")).unwrap(); - let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); - let mut picks = vec![out.to_string_lossy().into_owned(), src.to_string_lossy().into_owned()]; - app.services.pick_folder = Some(Box::new(move || picks.pop())); - crate::menus::invoke(&mut app, "imageTrace.batchFolder", json!({})); - assert!(out.join("a.vectorcraft").exists(), "{}", app.ui.status); - assert!(app.ui.status.starts_with("Traced 1 image"), "{}", app.ui.status); - assert!(app.session.documents().is_empty(), "the image's document is closed"); - app.services.pick_folder = Some(Box::new(|| None)); - assert_eq!(app.run("imageTrace.batchFolder", json!({})).unwrap_err(), "cancelled"); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 8bf9b147d0..f4df9b88dd 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -565,8 +565,8 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::addons::pathtools::shared_edge::open(app), crate::addons::arrange::ZOOM => crate::addons::arrange::zoom(app), crate::addons::document::SAVE_COPY => crate::addons::document::save_copy(app, p), - "imageTrace.batchFolder" => crate::io::batch_trace(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), "tool.setOption" => app.session.set_tool_option_cmd(p), "effect.dialog" => crate::dialogs::open_effect_dialog(app, p), "ui.recolorDialog" => crate::dialogs::recolor::open(app, p), diff --git a/docs/mcp.md b/docs/mcp.md index 75ede6e30b..c68c6f1844 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1880,13 +1880,6 @@ already walks Image Trace. Short agent entry points: Its journal entry records the saved preset's settings as `savedPreset`, so a replay traces with them after the preset is changed, renamed or deleted. In the app, `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. - `imageTrace.batchFolder {folder, destinationFolder, preset?, expand?, format?, includeSubdirs?}` (Object › Image - Trace › Batch Trace Folder) opens each image in `folder` (PNG, JPEG, TIFF, BMP, GIF, WebP, PSD), traces it with - `preset` (Default by default; with `expand`, as Make and Expand), saves it into `destinationFolder` as - `.` in `format` (`vectorcraft` by default; `svg`, `pdf`, `ai`, `eps`), with `-2`, `-3`… added when the - name is taken so no file is replaced, and closes it again whether it traced or not; the active document stays - active. Up to 500 images and 8 folder levels (a folder with more than 1,000 entries is refused); not on the web. The app asks for both folders (#4921). - → `{traced: [{path, output}], failed: [{path, error}], format}` - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill of its front-most @@ -6918,6 +6911,19 @@ Documents as PDF and as SVG ask for the folder. → `{files: [{title, path, warn {"name":"run_command","arguments":{"command":"addon.document.exportAllOpen","params":{"folder":"/Users/me/Out","format":"svg"}}} ``` +`addon.document.batchTraceFolder {folder, destinationFolder, preset?, expand?, format?, includeSubdirs?}` opens each +image in `folder` (PNG, JPEG, TIFF, BMP, GIF, WebP, PSD; with `includeSubdirs`, in its subfolders too), traces it with +`preset` (an `imageTrace.presets` name; Default by default; with `expand`, as Make and Expand), saves it into +`destinationFolder` as `.` in `format` (`vectorcraft` by default; `svg`, `pdf`, `ai`, `eps`), with `-2`, +`-3`… added when the name is taken so no file is replaced, and closes it again whether it traced or not; the active +document stays active. Images that can't be traced are listed in `failed` and the others are still traced. Up to 500 +images and 8 folder levels (a folder with more than 1,000 entries is refused); not on the web. The desktop app's Batch +Trace Folder asks for both folders (#4921). → `{traced: [{path, output}], failed: [{path, error}], format}` + +```json +{"name":"run_command","arguments":{"command":"addon.document.batchTraceFolder","params":{"folder":"/Users/me/Scans","destinationFolder":"/Users/me/Traced","preset":"Black and White Logo","format":"svg"}}} +``` + `addon.document.symbolsFromLayers {layers?, replace?}` makes one symbol of each top-level layer's art, as `symbol.new` makes one (registration in the centre), named after the layer with a number added when a symbol has that name, as one undo step. `layers` lists layer ids (top-level layers only; anything else is refused); by default it takes the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 730eeed041..1959b42612 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-04 · **Change:** minor (area type vertical alignment in the Properties and Control panels, #3759; 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-04 · **Change:** minor (Document Tools add-on: Batch Trace Folder, #4921; 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-04 | minor | Document Tools add-on (a VectorCraft addition): Batch Trace Folder under Object › Plug-ins (`addon.document.batchTraceFolder`, #4921); evidence added; scores unchanged. | | 2026-11-04 | minor | Object › Expand turns selected symbol instances into their art as Break Link places it, one level deep, with the Expand dialog's Fill and Stroke reaching that art. Scores and estimates unchanged. | | 2026-11-03 | minor | The OpenType panel offers the selected font's stylistic sets by custom or numbered name, and allows several to be active. Scores and estimates unchanged. | | 2026-11-03 | minor | Actions panel: an expanded action's steps can be excluded from playback and Batch… by clearing their checkmarks; action and set checkmarks include or exclude all their steps, and exclusions survive restart, duplication and `.vcactions` save/load. Scores and estimates unchanged. | @@ -1571,9 +1572,9 @@ Symbols area (#4938), from the public symbol documentation ([create and place sy A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Export All Open Documents as PDF (or as SVG) asks for a folder and writes a copy of every open document there, each named after its document with `-2`, `-3`… added when a name is taken, so no file is replaced (`addon.document.exportAllOpen {folder, format?}`, #4920). Each copy is written as Save a Copy writes it: the documents keep their paths, titles and modified state, and the active one stays active. A document that can't be written is named in the status bar and the others are still written. Tests: `addons::document::tests::export_all_open_documents_writes_each_to_the_folder_picked` (ui-egui), `cmd::addons::document::tests::export_all_open_documents_writes_each_and_reports_failures` (engine). -## Batch Trace Folder (2026-11-01) +## Document Tools add-on: Batch Trace Folder (2026-11-04) -A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Image Trace › Batch Trace Folder (`imageTrace.batchFolder`) asks for a folder of images and a destination folder, traces each image with a preset (optionally expanded) and saves it there under its own name as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps`, without replacing files, closing each image's document again and reporting the images it couldn't trace (#4921). Tests: `cmd::fileio::trace_batch::tests::batch_trace_folder_traces_and_saves_each_image` (engine), `io::batch_trace_tests::batch_trace_folder_asks_for_both_folders` (ui-egui). +A VectorCraft addition (it replaces a script some users ran), so no area score moves. Object › Plug-ins › Document Tools › Batch Trace Folder (`addon.document.batchTraceFolder`) asks for a folder of images and a destination folder, traces each image with a preset (optionally expanded) and saves it there under its own name as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps`, without replacing files, closing each image's document again and reporting the images it couldn't trace (#4921). A folder with more than 1,000 entries is refused rather than traced in part. Tests: `cmd::addons::document::tests::batch_trace_folder_traces_and_saves_each_image` and `batch_trace_folder_refuses_a_folder_it_cannot_list_in_full` (engine), `addons::document::tests::batch_trace_folder_asks_for_both_folders` (ui-egui). ## Color Effects add-on: Find Nearest Swatch (2026-11-01) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index e9bbe627aa..f40288a3a3 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 (area type vertical alignment buttons in the Properties and Control panels, turned off for rows, columns and threads, #3759; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (Document Tools add-on: Batch Trace Folder under Object › Plug-ins, #4921; 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) ## 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 | Document Tools add-on (a VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images and a destination folder and traces each image into it (#4921); scores and estimates unchanged | | 2026-11-03 | minor | The Action Options row cites the public Actions panel page and describes its controls. Scores and estimates remain unchanged. | | 2026-11-03 | minor | Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | | 2026-11-03 | minor | Transform previews valid typed values while numeric fields remain focused. Effect dialogs use the object, group, or layer targeted in Appearance. | @@ -364,6 +365,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Arrange Tools add-on (VectorCraft addition): Object › Plug-ins › Arrange Tools › Sort Objects… sorts the selected objects by Sort By (width, height, area, X or Y position, opacity, stacking order) in an Order (Small to Large, Large to Small, Random) and gives them Apply To in that order, trading the values or with Distribute Evenly; Scale Strokes & Effects; Preview; one undo step | done | #4917; `addon.arrange.sort`, `crates/engine/src/cmd/addons/arrange.rs`, `crates/ui-egui/src/addons/arrange.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Save a Timestamped Copy writes `_YYYY-MM-DD_HH-MM.` next to the document (a folder picked for one never saved), which keeps its path, title and modified state; off on the web | done | #4926; `addon.document.saveTimestampedCopy`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | Document Tools add-on (VectorCraft addition): Export All Open Documents as PDF / as SVG (#4920) | done | asks for a folder, writes a copy of every open document named after it (taken names numbered, nothing replaced), documents and active tab unchanged; failures named in the status bar | +| Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images, then a destination folder, traces each image with a preset (optionally expanded) and saves it there as `.vectorcraft`, `.svg`, `.pdf`, `.ai` or `.eps` under its own name (taken names numbered, nothing replaced), closing each image again; the status bar counts the images traced and those that couldn't be; off on the web | done | #4921; `addon.document.batchTraceFolder`, `crates/engine/src/cmd/addons/document/batch_trace.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app | | Document Tools add-on (VectorCraft addition): Object › Plug-ins › Document Tools › New Symbols from Layers makes a symbol of each layer's art named after the layer (the highlighted layers when two or more are, else all); Convert Layers to Symbols also replaces each layer's art with an instance in place; empty layers skipped, one undo step | done | #4927; `addon.document.symbolsFromLayers`, `crates/engine/src/cmd/addons/document.rs`, `crates/ui-egui/src/addons/document.rs` and their tests; not a feature of the reference app, so it is not scored | | 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 | From 9d8be643f42668c791ff102b1704739352c2d32b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:15:51 -0800 Subject: [PATCH 065/482] Actions: Playback Options plays actions accelerated, step by step or with a pause between steps The Actions panel menu's Playback Options... sets how actions play (ui.action.playbackOptions {speed?, seconds?}). Accelerated, the default, plays every step at once as one undo step, as before. Step by Step plays one step per frame so the canvas draws each step's result, and Pause For waits 1 to 60 seconds between steps; each paced step is its own undo step. Stop Playing/Recording ends a paced playback, and another action does not play while one is paced. The setting is kept with the UI preferences. Batch... plays at full speed. --- crates/ui-egui/src/app.rs | 4 + crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/action_playback.rs | 48 +++ crates/ui-egui/src/i18n/bg.tsv | 8 + crates/ui-egui/src/i18n/bs.tsv | 8 + crates/ui-egui/src/i18n/ca.tsv | 8 + crates/ui-egui/src/i18n/cs.tsv | 8 + crates/ui-egui/src/i18n/da.tsv | 8 + crates/ui-egui/src/i18n/de.tsv | 8 + crates/ui-egui/src/i18n/el.tsv | 8 + crates/ui-egui/src/i18n/es.tsv | 8 + crates/ui-egui/src/i18n/fi.tsv | 8 + crates/ui-egui/src/i18n/fr.tsv | 8 + crates/ui-egui/src/i18n/hu.tsv | 8 + crates/ui-egui/src/i18n/id.tsv | 8 + crates/ui-egui/src/i18n/it.tsv | 8 + crates/ui-egui/src/i18n/ja.tsv | 8 + crates/ui-egui/src/i18n/ka.tsv | 8 + crates/ui-egui/src/i18n/ko.tsv | 8 + crates/ui-egui/src/i18n/nl.tsv | 8 + crates/ui-egui/src/i18n/pl.tsv | 8 + crates/ui-egui/src/i18n/pt-br.tsv | 8 + crates/ui-egui/src/i18n/ru.tsv | 8 + crates/ui-egui/src/i18n/sv.tsv | 8 + crates/ui-egui/src/i18n/tr.tsv | 8 + crates/ui-egui/src/i18n/uk.tsv | 8 + crates/ui-egui/src/i18n/vi.tsv | 8 + crates/ui-egui/src/i18n/zh-hans.tsv | 8 + crates/ui-egui/src/i18n/zh-hant.tsv | 8 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 10 +- crates/ui-egui/src/panels/actions.rs | 297 +++++++++++++++++- crates/ui-egui/src/state.rs | 8 + docs/mcp.md | 22 +- docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 36 files changed, 590 insertions(+), 12 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/action_playback.rs diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fbcf1dd0c2..c818001959 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -348,6 +348,10 @@ impl VectorcraftApp { // The timer and heartbeat run in an idle window too. ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } + // An action playing at Step by Step or Pause For runs its next step when it is due. + if let Some(wait) = crate::panels::actions::tick_playback(self, now) { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } crate::keymap::note_os(ctx); shortcut_editor::sync(&self.ui); crate::panels::actions::sync_function_keys(&self.ui); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 250f18647c..740326c433 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -9,6 +9,7 @@ mod about; pub mod action_batch; pub mod action_new; +pub mod action_playback; pub mod action_set_options; pub mod artboard_options; pub mod blend_options; @@ -365,6 +366,7 @@ registry! { ActionBatch: [action_batch::KIND] => action_batch::SPEC, ActionSetOptions: [action_set_options::KIND] => action_set_options::SPEC, ActionNew: [action_new::KIND] => action_new::SPEC, + ActionPlayback: [action_playback::KIND] => action_playback::SPEC, SliceOptions: [slices::OPTIONS] => slices::OPTIONS_SPEC, DivideSlices: [slices::DIVIDE] => slices::DIVIDE_SPEC, EpsOptions: [eps_options::KIND] => eps_options::SPEC, diff --git a/crates/ui-egui/src/dialogs/action_playback.rs b/crates/ui-egui/src/dialogs/action_playback.rs new file mode 100644 index 0000000000..67d6e35d41 --- /dev/null +++ b/crates/ui-egui/src/dialogs/action_playback.rs @@ -0,0 +1,48 @@ +//! Actions panel menu › Playback Options…: the speed actions play at (`ui.action.playbackOptions`). +//! +//! Fields: `speed` (`accelerated`, `step` or `pause`) and `seconds`, the pause between steps with +//! `pause`. OK sets them; an invalid value is an error, and the dialog stays open. + +use serde_json::{Value, json}; + +use super::DialogSpec; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Playback Options. +pub const KIND: &str = "actionPlayback"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Playback Options").into(), body, confirm, min_width: 260.0, ..DialogSpec::FORM }; + +/// Open Playback Options with the speed and pause actions play with now. +pub fn open(app: &mut VectorcraftApp) { + let o = app.ui.action_playback; + app.ui.dialog = Some(Dialog::new(KIND, json!({"speed": o.speed, "seconds": o.seconds}))); +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let speed = d.str("speed"); + for (value, label) in [("accelerated", tl!("Accelerated")), ("step", tl!("Step by Step"))] { + if widgets::radio(ui, label, speed == value, true) { + d.fields.insert("speed".into(), json!(value)); + } + } + ui.horizontal(|ui| { + let pause = tl!("Pause For"); + if widgets::radio(ui, pause, speed == "pause", true) { + d.fields.insert("speed".into(), json!("pause")); + } + let range = f64::from(*crate::panels::actions::PAUSE_SECONDS.start())..=f64::from(*crate::panels::actions::PAUSE_SECONDS.end()); + if let Some(n) = widgets::range_field_named(ui, "action-pause-seconds", Some(pause), d.f64("seconds", *range.start()), range, "s", 0, 50.0) { + d.fields.insert("seconds".into(), json!(n as u64)); + } + }); + false +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let params = json!({"speed": d.str("speed"), "seconds": d.fields.get("seconds").cloned().unwrap_or(Value::Null)}); + let r = app.run(crate::panels::actions::PLAYBACK_OPTIONS, params)?; + app.ui.dialog = None; + Ok(r) +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 6100b0b5cd..9361d3b37f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5502,6 +5502,9 @@ theme Appearance Външен вид Movie Clip Филмов клип @msg name is empty името е празно @msg an action is already recording вече се записва действие +@msg an action is already playing вече се възпроизвежда действие +@msg speed must be accelerated, step or pause speed трябва да е accelerated, step или pause +@msg seconds must be a whole number from 1 to 60 seconds трябва да е цяло число от 1 до 60 @msg no such function key няма такъв функционален клавиш @msg no such color няма такъв цвят @msg {_1} cannot be used on Windows {_1} не може да се използва в Windows @@ -5652,6 +5655,11 @@ axis Y Axis Y ос Set Options Опции на набора Action Options… Опции на действието… Action Options Опции на действието + Playback Options… Опции за възпроизвеждане… + Playback Options Опции за възпроизвеждане + Accelerated Ускорено + Step by Step Стъпка по стъпка + Pause For Пауза за Rename Action Преименуване на действие New Action… Ново действие… New Action Ново действие diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index e2aff10a9e..cfc1f39fa1 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5506,6 +5506,9 @@ mark-style Japanese Japanski Movie Clip Filmski klip @msg name is empty naziv je prazan @msg an action is already recording akcija se već snima +@msg an action is already playing akcija se već reproducira +@msg speed must be accelerated, step or pause speed mora biti accelerated, step ili pause +@msg seconds must be a whole number from 1 to 60 seconds mora biti cijeli broj od 1 do 60 @msg no such function key nema takve funkcijske tipke @msg no such color nema takve boje @msg {_1} cannot be used on Windows {_1} se ne može koristiti na Windowsu @@ -5675,6 +5678,11 @@ axis Y Axis Y osa Set Options Opcije skupa Action Options… Opcije akcije… Action Options Opcije akcije + Playback Options… Opcije reprodukcije… + Playback Options Opcije reprodukcije + Accelerated Ubrzano + Step by Step Korak po korak + Pause For Pauza od Rename Action Preimenuj akciju New Action… Nova akcija… New Action Nova akcija diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 5c5f7f9381..1929ffa58e 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3791,6 +3791,11 @@ digits Malayalam Malaiàlam Set Options Defineix les opcions Action Options… Opcions de l’acció… Action Options Opcions de l’acció + Playback Options… Opcions de reproducció… + Playback Options Opcions de reproducció + Accelerated Accelerada + Step by Step Pas a pas + Pause For Pausa de Rename Action Canvia el nom de l’acció New Action… Acció nova… New Action Acció nova @@ -5187,6 +5192,9 @@ digits Malayalam Malaiàlam @msg Multichannel PSD files can't be read: save it in RGB, CMYK or Grayscale mode Els fitxers PSD multicanal no es poden llegir: deseu-los en mode RGB, CMYK o escala de grisos @msg name is empty el nom és buit @msg an action is already recording ja s’està enregistrant una acció +@msg an action is already playing ja s’està reproduint una acció +@msg speed must be accelerated, step or pause speed ha de ser accelerated, step o pause +@msg seconds must be a whole number from 1 to 60 seconds ha de ser un nombre enter de l’1 al 60 @msg no such function key no existeix aquesta tecla de funció @msg no such color no existeix aquest color @msg {_1} cannot be used on Windows {_1} no es pot fer servir al Windows diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 77a0b8d1d4..73887e0f18 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5592,6 +5592,9 @@ mark-style Japanese Japonské Movie Clip Filmový klip @msg name is empty název je prázdný @msg an action is already recording akce se už zaznamenává +@msg an action is already playing akce se už přehrává +@msg speed must be accelerated, step or pause speed musí být accelerated, step nebo pause +@msg seconds must be a whole number from 1 to 60 seconds musí být celé číslo od 1 do 60 @msg no such function key taková funkční klávesa neexistuje @msg no such color taková barva neexistuje @msg {_1} cannot be used on Windows Zkratku {_1} nelze ve Windows použít @@ -5766,6 +5769,11 @@ axis Y Axis osa Y Set Options Možnosti sady Action Options… Možnosti akce… Action Options Možnosti akce + Playback Options… Možnosti přehrávání… + Playback Options Možnosti přehrávání + Accelerated Zrychleně + Step by Step Krok za krokem + Pause For Pozastavit na Rename Action Přejmenovat akci New Action… Nová akce… New Action Nová akce diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index d591b57262..7237702c66 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5387,6 +5387,9 @@ swatch Bright Violet Kraftig violet Movie Clip Filmklip @msg name is empty navnet er tomt @msg an action is already recording en handling optages allerede +@msg an action is already playing en handling afspilles allerede +@msg speed must be accelerated, step or pause speed skal være accelerated, step eller pause +@msg seconds must be a whole number from 1 to 60 seconds skal være et heltal fra 1 til 60 @msg no such function key ingen sådan funktionstast @msg no such color ingen sådan farve @msg {_1} cannot be used on Windows {_1} kan ikke bruges i Windows @@ -5669,6 +5672,11 @@ axis Y Axis Y-akse Set Options Indstillinger for sæt Action Options… Indstillinger for handling… Action Options Indstillinger for handling + Playback Options… Afspilningsindstillinger… + Playback Options Afspilningsindstillinger + Accelerated Accelereret + Step by Step Trin for trin + Pause For Pause på Rename Action Omdøb handling New Action… Ny handling… New Action Ny handling diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d6d73bf0b0..dbd5e3e216 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5170,6 +5170,9 @@ effect Soft Weich Movie Clip Movieclip @msg name is empty Name ist leer @msg an action is already recording eine Aktion wird bereits aufgezeichnet +@msg an action is already playing eine Aktion wird bereits abgespielt +@msg speed must be accelerated, step or pause speed muss accelerated, step oder pause sein +@msg seconds must be a whole number from 1 to 60 seconds muss eine ganze Zahl von 1 bis 60 sein @msg no such function key keine solche Funktionstaste @msg no such color keine solche Farbe @msg {_1} cannot be used on Windows {_1} kann unter Windows nicht verwendet werden @@ -5348,6 +5351,11 @@ axis Y Axis Y-Achse Set Options Satzoptionen Action Options… Aktionsoptionen… Action Options Aktionsoptionen + Playback Options… Wiedergabeoptionen… + Playback Options Wiedergabeoptionen + Accelerated Beschleunigt + Step by Step Schrittweise + Pause For Pause von Rename Action Aktion umbenennen New Action… Neue Aktion… New Action Neue Aktion diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 448cd26a1d..2ef7e8cb3b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5543,6 +5543,9 @@ effect Points Σημεία Movie Clip Κλιπ ταινίας @msg name is empty το όνομα είναι κενό @msg an action is already recording μια ενέργεια καταγράφεται ήδη +@msg an action is already playing μια ενέργεια αναπαράγεται ήδη +@msg speed must be accelerated, step or pause το speed πρέπει να είναι accelerated, step ή pause +@msg seconds must be a whole number from 1 to 60 το seconds πρέπει να είναι ακέραιος από 1 έως 60 @msg no such function key δεν υπάρχει τέτοιο πλήκτρο λειτουργίας @msg no such color δεν υπάρχει τέτοιο χρώμα @msg {_1} cannot be used on Windows Το {_1} δεν μπορεί να χρησιμοποιηθεί στα Windows @@ -5717,6 +5720,11 @@ axis Y Axis Άξονας Y Set Options Επιλογές συνόλου Action Options… Επιλογές ενέργειας… Action Options Επιλογές ενέργειας + Playback Options… Επιλογές αναπαραγωγής… + Playback Options Επιλογές αναπαραγωγής + Accelerated Επιταχυμένα + Step by Step Βήμα προς βήμα + Pause For Παύση για Rename Action Μετονομασία ενέργειας New Action… Νέα ενέργεια… New Action Νέα ενέργεια diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9de4042573..91f7670489 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5533,6 +5533,9 @@ mark-style Japanese Japonesas Movie Clip Clip de película @msg name is empty el nombre está vacío @msg an action is already recording ya se está grabando una acción +@msg an action is already playing ya se está reproduciendo una acción +@msg speed must be accelerated, step or pause speed debe ser accelerated, step o pause +@msg seconds must be a whole number from 1 to 60 seconds debe ser un número entero de 1 a 60 @msg no such function key no existe esa tecla de función @msg no such color no existe ese color @msg {_1} cannot be used on Windows {_1} no se puede usar en Windows @@ -5707,6 +5710,11 @@ axis Y Axis Eje Y Set Options Opciones de conjunto Action Options… Opciones de acción… Action Options Opciones de acción + Playback Options… Opciones de reproducción… + Playback Options Opciones de reproducción + Accelerated Acelerada + Step by Step Paso a paso + Pause For Pausa de Rename Action Cambiar nombre de acción New Action… Nueva acción… New Action Nueva acción diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 20317de484..1cda3c91dd 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5555,6 +5555,9 @@ mark-style Japanese Japanilainen Movie Clip Elokuvaleike @msg name is empty nimi on tyhjä @msg an action is already recording toimintoa nauhoitetaan jo +@msg an action is already playing toimintoa toistetaan jo +@msg speed must be accelerated, step or pause speed on oltava accelerated, step tai pause +@msg seconds must be a whole number from 1 to 60 seconds on oltava kokonaisluku 1:stä 60:een @msg no such function key toimintonäppäintä ei ole @msg no such color väriä ei ole @msg {_1} cannot be used on Windows {_1} ei ole käytettävissä Windowsissa @@ -5796,6 +5799,11 @@ axis Y Axis Y-akseli Set Options Sarjan asetukset Action Options… Toiminnon asetukset… Action Options Toiminnon asetukset + Playback Options… Toistoasetukset… + Playback Options Toistoasetukset + Accelerated Nopeutettu + Step by Step Vaihe kerrallaan + Pause For Tauko Rename Action Nimeä toiminto uudelleen New Action… Uusi toiminto… New Action Uusi toiminto diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 167792f461..0fb2551438 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5587,6 +5587,9 @@ theme Appearance Apparence Movie Clip Clip @msg name is empty le nom est vide @msg an action is already recording un script est déjà en cours d’enregistrement +@msg an action is already playing un script est déjà en cours d’exécution +@msg speed must be accelerated, step or pause speed doit valoir accelerated, step ou pause +@msg seconds must be a whole number from 1 to 60 seconds doit être un nombre entier de 1 à 60 @msg no such function key touche de fonction inexistante @msg no such color couleur inexistante @msg {_1} cannot be used on Windows {_1} ne peut pas être utilisé sous Windows @@ -5761,6 +5764,11 @@ axis Y Axis Axe Y Set Options Options du jeu Action Options… Options de script… Action Options Options de script + Playback Options… Options d’exécution… + Playback Options Options d’exécution + Accelerated Accélérée + Step by Step Pas à pas + Pause For Pause de Rename Action Renommer le script New Action… Nouveau script… New Action Nouveau script diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 4eceaca1e4..175e3908a2 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5575,6 +5575,9 @@ imageTrace Outline Körvonal Movie Clip Mozgóklip @msg name is empty a név üres @msg an action is already recording már folyik egy művelet felvétele +@msg an action is already playing már folyik egy művelet lejátszása +@msg speed must be accelerated, step or pause a speed értéke accelerated, step vagy pause lehet +@msg seconds must be a whole number from 1 to 60 a seconds értéke 1 és 60 közötti egész szám lehet @msg no such function key nincs ilyen funkcióbillentyű @msg no such color nincs ilyen szín @msg {_1} cannot be used on Windows A(z) {_1} nem használható Windows rendszeren @@ -5749,6 +5752,11 @@ axis Y Axis Y tengely Set Options Készlet beállításai Action Options… Művelet beállításai… Action Options Művelet beállításai + Playback Options… Lejátszási beállítások… + Playback Options Lejátszási beállítások + Accelerated Gyorsított + Step by Step Lépésenként + Pause For Szünet Rename Action Művelet átnevezése New Action… Új művelet… New Action Új művelet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0886dc7467..ed1c8a1685 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5387,6 +5387,9 @@ swatch Bright Violet Violet cerah Movie Clip Klip film @msg name is empty nama kosong @msg an action is already recording sebuah tindakan sedang direkam +@msg an action is already playing sebuah tindakan sedang diputar +@msg speed must be accelerated, step or pause speed harus accelerated, step, atau pause +@msg seconds must be a whole number from 1 to 60 seconds harus bilangan bulat dari 1 sampai 60 @msg no such function key tidak ada tombol fungsi seperti itu @msg no such color tidak ada warna seperti itu @msg {_1} cannot be used on Windows {_1} tidak dapat digunakan di Windows @@ -5669,6 +5672,11 @@ axis Y Axis Sumbu Y Set Options Opsi set Action Options… Opsi tindakan… Action Options Opsi tindakan + Playback Options… Opsi pemutaran… + Playback Options Opsi pemutaran + Accelerated Dipercepat + Step by Step Langkah demi langkah + Pause For Jeda selama Rename Action Ganti nama tindakan New Action… Tindakan baru… New Action Tindakan baru diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2bb5273022..ab5a5a6690 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5205,6 +5205,9 @@ lighting Light Luce Movie Clip Clip filmato @msg name is empty il nome è vuoto @msg an action is already recording è già in corso la registrazione di un’azione +@msg an action is already playing è già in corso la riproduzione di un’azione +@msg speed must be accelerated, step or pause speed deve essere accelerated, step o pause +@msg seconds must be a whole number from 1 to 60 seconds deve essere un numero intero da 1 a 60 @msg no such function key tasto funzione inesistente @msg no such color colore inesistente @msg {_1} cannot be used on Windows {_1} non può essere usato su Windows @@ -5382,6 +5385,11 @@ axis Y Axis Asse Y Set Options Opzioni set Action Options… Opzioni azione… Action Options Opzioni azione + Playback Options… Opzioni di riproduzione… + Playback Options Opzioni di riproduzione + Accelerated Accelerata + Step by Step Passo per passo + Pause For Pausa di Rename Action Rinomina azione New Action… Nuova azione… New Action Nuova azione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f57d7c21f0..92437db433 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5248,6 +5248,9 @@ lighting Light ライト Movie Clip ムービークリップ @msg name is empty 名前が空です @msg an action is already recording すでにアクションを記録中です +@msg an action is already playing すでにアクションを再生中です +@msg speed must be accelerated, step or pause speed には accelerated、step または pause を指定してください +@msg seconds must be a whole number from 1 to 60 seconds には 1 から 60 までの整数を指定してください @msg no such function key 指定されたファンクションキーが見つかりません @msg no such color 指定されたカラーが見つかりません @msg {_1} cannot be used on Windows {_1} は Windows では使用できません @@ -5447,6 +5450,11 @@ axis Y Axis Y 軸 Set Options セットオプション Action Options… アクションオプション… Action Options アクションオプション + Playback Options… 再生オプション… + Playback Options 再生オプション + Accelerated 高速 + Step by Step ステップ実行 + Pause For 一時停止 Rename Action アクション名を変更 New Action… 新規アクション… New Action 新規アクション diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index eff88f55b7..7957f671e8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5300,6 +5300,9 @@ imageTrace Outline კონტური Movie Clip ანიმაციური კლიპი @msg name is empty სახელი ცარიელია @msg an action is already recording მოქმედება უკვე იწერება +@msg an action is already playing მოქმედება უკვე სრულდება +@msg speed must be accelerated, step or pause speed უნდა იყოს accelerated, step ან pause +@msg seconds must be a whole number from 1 to 60 seconds უნდა იყოს მთელი რიცხვი 1-დან 60-მდე @msg no such function key ასეთი ფუნქციური კლავიში არ არის @msg no such color ასეთი ფერი არ არის @msg {_1} cannot be used on Windows {_1} ვერ გამოიყენება Windows-ში @@ -5688,6 +5691,11 @@ axis Y Axis Y ღერძი Set Options ნაკრების პარამეტრები Action Options… მოქმედების პარამეტრები… Action Options მოქმედების პარამეტრები + Playback Options… შესრულების პარამეტრები… + Playback Options შესრულების პარამეტრები + Accelerated დაჩქარებული + Step by Step ნაბიჯ-ნაბიჯ + Pause For პაუზა Rename Action მოქმედების სახელის შეცვლა New Action… ახალი მოქმედება… New Action ახალი მოქმედება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 90c4fe2eba..5e40783947 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5166,6 +5166,9 @@ lighting Light 광원 Movie Clip 무비 클립 @msg name is empty 이름이 비어 있습니다 @msg an action is already recording 이미 액션을 기록하고 있습니다 +@msg an action is already playing 이미 액션을 재생하고 있습니다 +@msg speed must be accelerated, step or pause speed는 accelerated, step 또는 pause여야 합니다 +@msg seconds must be a whole number from 1 to 60 seconds는 1에서 60 사이의 정수여야 합니다 @msg no such function key 해당 기능 키가 없습니다 @msg no such color 해당 색상이 없습니다 @msg {_1} cannot be used on Windows {_1}은(는) Windows에서 사용할 수 없습니다 @@ -5343,6 +5346,11 @@ axis Y Axis Y축 Set Options 세트 옵션 Action Options… 액션 옵션… Action Options 액션 옵션 + Playback Options… 재생 옵션… + Playback Options 재생 옵션 + Accelerated 가속 + Step by Step 단계별 + Pause For 일시 정지 Rename Action 액션 이름 바꾸기 New Action… 새 액션… New Action 새 액션 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index cd613117b3..c2aeadf939 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5395,6 +5395,9 @@ swatch Bright Violet Felviolet Movie Clip Filmclip @msg name is empty naam is leeg @msg an action is already recording er wordt al een actie opgenomen +@msg an action is already playing er wordt al een actie afgespeeld +@msg speed must be accelerated, step or pause speed moet accelerated, step of pause zijn +@msg seconds must be a whole number from 1 to 60 seconds moet een geheel getal van 1 tot 60 zijn @msg no such function key functietoets bestaat niet @msg no such color kleur bestaat niet @msg {_1} cannot be used on Windows {_1} kan niet worden gebruikt in Windows @@ -5713,6 +5716,11 @@ axis Y Axis Y-as Set Options Setopties Action Options… Actieopties… Action Options Actieopties + Playback Options… Afspeelopties… + Playback Options Afspeelopties + Accelerated Versneld + Step by Step Stap voor stap + Pause For Pauzeren Rename Action Actie hernoemen New Action… Nieuwe actie… New Action Nieuwe actie diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index ea81961c77..1ad694245c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5445,6 +5445,9 @@ mark-style Japanese Japońskie Movie Clip Klip filmowy @msg name is empty nazwa jest pusta @msg an action is already recording operacja jest już nagrywana +@msg an action is already playing operacja jest już odtwarzana +@msg speed must be accelerated, step or pause speed musi mieć wartość accelerated, step lub pause +@msg seconds must be a whole number from 1 to 60 seconds musi być liczbą całkowitą od 1 do 60 @msg no such function key brak takiego klawisza funkcyjnego @msg no such color brak takiego koloru @msg {_1} cannot be used on Windows Skrótu {_1} nie można używać w systemie Windows @@ -5619,6 +5622,11 @@ axis Y Axis Oś Y Set Options Opcje zestawu Action Options… Opcje operacji… Action Options Opcje operacji + Playback Options… Opcje odtwarzania… + Playback Options Opcje odtwarzania + Accelerated Przyspieszone + Step by Step Krok po kroku + Pause For Pauza Rename Action Zmień nazwę operacji New Action… Nowa operacja… New Action Nowa operacja diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7bab708578..8a4480488b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5507,6 +5507,9 @@ mark-style Japanese Japonesas # Symbol Options › Export Type @msg name is empty o nome está vazio @msg an action is already recording uma ação já está sendo gravada +@msg an action is already playing uma ação já está sendo reproduzida +@msg speed must be accelerated, step or pause speed deve ser accelerated, step ou pause +@msg seconds must be a whole number from 1 to 60 seconds deve ser um número inteiro de 1 a 60 @msg no such function key tecla de função inexistente @msg no such color cor inexistente @msg {_1} cannot be used on Windows {_1} não pode ser usado no Windows @@ -5681,6 +5684,11 @@ axis Y Axis Eixo Y Set Options Opções do Conjunto Action Options… Opções da Ação… Action Options Opções da Ação + Playback Options… Opções de Reprodução… + Playback Options Opções de Reprodução + Accelerated Acelerada + Step by Step Passo a Passo + Pause For Pausar Por Rename Action Renomear Ação New Action… Nova Ação… New Action Nova Ação diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index c0106d85a6..94c30e8c57 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5200,6 +5200,9 @@ lighting Light Свет Movie Clip Видеоклип @msg name is empty имя пустое @msg an action is already recording действие уже записывается +@msg an action is already playing действие уже воспроизводится +@msg speed must be accelerated, step or pause speed должен быть accelerated, step или pause +@msg seconds must be a whole number from 1 to 60 seconds должно быть целым числом от 1 до 60 @msg no such function key такой функциональной клавиши нет @msg no such color такого цвета нет @msg {_1} cannot be used on Windows Сочетание {_1} нельзя использовать в Windows @@ -5377,6 +5380,11 @@ axis Y Axis Ось Y Set Options Параметры набора Action Options… Параметры действия… Action Options Параметры действия + Playback Options… Параметры воспроизведения… + Playback Options Параметры воспроизведения + Accelerated Ускоренно + Step by Step Пошагово + Pause For Пауза Rename Action Переименовать действие New Action… Новое действие… New Action Новое действие diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index a8bfc433f8..e03ea97aea 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5547,6 +5547,9 @@ theme Appearance Utseende Movie Clip Filmklipp @msg name is empty namnet är tomt @msg an action is already recording en åtgärd spelas redan in +@msg an action is already playing en åtgärd spelas redan upp +@msg speed must be accelerated, step or pause speed måste vara accelerated, step eller pause +@msg seconds must be a whole number from 1 to 60 seconds måste vara ett heltal från 1 till 60 @msg no such function key funktionstangenten finns inte @msg no such color färgen finns inte @msg {_1} cannot be used on Windows {_1} kan inte användas i Windows @@ -5789,6 +5792,11 @@ axis Y Axis Y-axel Set Options Alternativ för uppsättning Action Options… Alternativ för åtgärd… Action Options Alternativ för åtgärd + Playback Options… Uppspelningsalternativ… + Playback Options Uppspelningsalternativ + Accelerated Accelererad + Step by Step Steg för steg + Pause For Paus i Rename Action Byt namn på åtgärd New Action… Ny åtgärd… New Action Ny åtgärd diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 83dcfca101..4e77e1f809 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5256,6 +5256,9 @@ theme Appearance Görünüm Movie Clip Film Klibi @msg name is empty isim boş @msg an action is already recording zaten bir eylem kaydediliyor +@msg an action is already playing zaten bir eylem oynatılıyor +@msg speed must be accelerated, step or pause speed accelerated, step veya pause olmalıdır +@msg seconds must be a whole number from 1 to 60 seconds 1 ile 60 arasında bir tam sayı olmalıdır @msg no such function key öyle bir işlev tuşu yok @msg no such color öyle bir renk yok @msg {_1} cannot be used on Windows {_1} Windows'ta kullanılamaz @@ -5723,6 +5726,11 @@ axis Y Axis Y ekseni Set Options Set Seçenekleri Action Options… Eylem Seçenekleri… Action Options Eylem Seçenekleri + Playback Options… Oynatma Seçenekleri… + Playback Options Oynatma Seçenekleri + Accelerated Hızlandırılmış + Step by Step Adım Adım + Pause For Duraklat Rename Action Eylemi Yeniden Adlandır New Action… Yeni Eylem… New Action Yeni Eylem diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index d7391112ff..9e60d3b950 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5185,6 +5185,9 @@ lighting Light Світло Movie Clip Кліп @msg name is empty ім’я порожнє @msg an action is already recording дія вже записується +@msg an action is already playing дія вже відтворюється +@msg speed must be accelerated, step or pause speed має бути accelerated, step або pause +@msg seconds must be a whole number from 1 to 60 seconds має бути цілим числом від 1 до 60 @msg no such function key такої функціональної клавіші немає @msg no such color такого кольору немає @msg {_1} cannot be used on Windows Сполучення {_1} не можна використовувати у Windows @@ -5362,6 +5365,11 @@ axis Y Axis Вісь Y Set Options Параметри набору Action Options… Параметри дії… Action Options Параметри дії + Playback Options… Параметри відтворення… + Playback Options Параметри відтворення + Accelerated Прискорено + Step by Step Покроково + Pause For Пауза Rename Action Перейменувати дію New Action… Нова дія… New Action Нова дія diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 6028148443..2fb5b8e472 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5186,6 +5186,9 @@ theme Appearance Giao diện Movie Clip Clip phim @msg name is empty tên trống @msg an action is already recording đang ghi một hành động +@msg an action is already playing đang phát một hành động +@msg speed must be accelerated, step or pause speed phải là accelerated, step hoặc pause +@msg seconds must be a whole number from 1 to 60 seconds phải là số nguyên từ 1 đến 60 @msg no such function key không có phím chức năng như vậy @msg no such color không có màu như vậy @msg {_1} cannot be used on Windows không thể dùng {_1} trên Windows @@ -5363,6 +5366,11 @@ axis Y Axis Trục Y Set Options Tùy chọn bộ Action Options… Tùy chọn hành động… Action Options Tùy chọn hành động + Playback Options… Tùy chọn phát lại… + Playback Options Tùy chọn phát lại + Accelerated Tăng tốc + Step by Step Từng bước + Pause For Tạm dừng Rename Action Đổi tên hành động New Action… Hành động mới… New Action Hành động mới diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index ce2089a0c1..082a32000c 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5425,6 +5425,9 @@ lighting Light 光源 Movie Clip 影片剪辑 @msg name is empty 名称为空 @msg an action is already recording 已在记录动作 +@msg an action is already playing 已在播放动作 +@msg speed must be accelerated, step or pause speed 必须为 accelerated、step 或 pause +@msg seconds must be a whole number from 1 to 60 seconds 必须为 1 到 60 之间的整数 @msg no such function key 没有此功能键 @msg no such color 没有此颜色 @msg {_1} cannot be used on Windows {_1} 在 Windows 上不能使用 @@ -5604,6 +5607,11 @@ axis Y Axis Y 轴 Set Options 组选项 Action Options… 动作选项… Action Options 动作选项 + Playback Options… 播放选项… + Playback Options 播放选项 + Accelerated 加速 + Step by Step 逐步 + Pause For 暂停 Rename Action 重命名动作 New Action… 新建动作… New Action 新建动作 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index eead8f7d46..31b7e5cf1e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5243,6 +5243,9 @@ lighting Light 光源 Movie Clip 影片片段 @msg name is empty 名稱為空 @msg an action is already recording 已在錄製動作 +@msg an action is already playing 已在播放動作 +@msg speed must be accelerated, step or pause speed 必須為 accelerated、step 或 pause +@msg seconds must be a whole number from 1 to 60 seconds 必須為 1 到 60 之間的整數 @msg no such function key 沒有這個功能鍵 @msg no such color 沒有這個顏色 @msg {_1} cannot be used on Windows {_1} 無法在 Windows 上使用 @@ -5400,6 +5403,11 @@ axis Y Axis Y 軸 Set Options 組選項 Action Options… 動作選項… Action Options 動作選項 + Playback Options… 播放選項… + Playback Options 播放選項 + Accelerated 加速 + Step by Step 逐步 + Pause For 暫停 Rename Action 重新命名動作 New Action… 新增動作… New Action 新增動作 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index f4df9b88dd..80fe0a1845 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -826,6 +826,7 @@ fn run_ui_part11(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::panels::actions::new_action(app, p), crate::panels::actions::ACTION_OPTIONS => crate::panels::actions::action_options(app, p), crate::panels::actions::PLAY_ACTION => crate::panels::actions::play_action(app, p), + crate::panels::actions::PLAYBACK_OPTIONS => crate::panels::actions::playback_options(app, p), crate::panels::actions::START_RECORDING => crate::panels::actions::record(app, p), crate::panels::actions::STOP_RECORDING => crate::panels::actions::stop(app, p), "ui.batchDialog" => { diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 5e9c10e355..bf9ecdbfe6 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1239,7 +1239,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::PLAY_ACTION, "Play Action", "", - "{action: name, set?: name} play the Actions panel's action named action as one undoable batch; set names the set to look in (default: every set). A name no action has, or one that more than one action in the sets looked in has, is an error and nothing plays → what command.batch returns", + "{action: name, set?: name} play the Actions panel's action named action at the speed ui.action.playbackOptions sets; set names the set to look in (default: every set). Accelerated plays it as one undoable batch → what command.batch returns. Step by Step and Pause For play its first step now and the others one at a time, each its own undo step, until the last or ui.action.stop → {results: [the first step's result], pending: the steps left}. A name no action has, or one that more than one action in the sets looked in has, or an action played while another is still playing step by step or with pauses, is an error and nothing plays", + ), + ( + crate::panels::actions::PLAYBACK_OPTIONS, + "Playback Options", + "", + "{speed?: accelerated|step|pause, seconds?: 1-60} set how the Actions panel plays actions: accelerated (the default) plays every step at once, step plays one step at a time and draws the window after each, and pause waits seconds (a whole number, 1 to 60, VectorCraft's own range) between steps. A param left out keeps its value; the setting is kept with the UI preferences. Any other speed or seconds is an error and changes nothing. The panel menu's Playback Options… (dialog `actionPlayback` with speed and seconds) runs this on OK → {speed, seconds}", ), ( crate::panels::actions::START_RECORDING, @@ -1251,7 +1257,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::STOP_RECORDING, "Stop Playing/Recording", "", - "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. With nothing recording it changes nothing → {stopped}", + "{} end the Actions panel's recording and keep its steps, in the action ui.action.new made for it, else in a new action after the last action of its set, as the panel's Stop Playing/Recording button does. It also ends an action playing step by step or with pauses: the steps played stay and the rest do not run. With nothing recording or playing it changes nothing → {stopped}", ), ( "ui.batchDialog", diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 7c9edc6a55..12d0bd4760 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -203,14 +203,154 @@ pub fn default_sets() -> Vec { )] } -/// Run an action as a single undoable batch. +/// Plays an action at the speed [`UiState::action_playback`](crate::UiState::action_playback) sets. +/// Accelerated runs every included step at once as a single undoable batch → what `command.batch` +/// returns. Step by Step and Pause For run the first step now, each as its own undo step, and leave +/// the rest to [`tick_playback`] → {results: [the first step's result], pending: the steps left}. +/// While a paced playback is in progress, another action does not play. pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result { let Some(a) = app.ui.action_sets.get(set).and_then(|s| s.actions.get(idx)).cloned() else { return Err("no such action".into()) }; let commands = a.included_commands(); if commands.is_empty() { return Err("the action has no included steps".into()); } - app.run("command.batch", json!({"label": a.name, "commands": commands})) + if app.ui.action_playing.is_some() { + return Err("an action is already playing".into()); + } + let options = app.ui.action_playback; + if options.speed == PlaybackSpeed::Accelerated { + return app.run("command.batch", json!({"label": a.name, "commands": commands})); + } + let mut steps: std::collections::VecDeque = commands.into(); + let Some(first) = steps.pop_front() else { return Err("the action has no included steps".into()) }; + let result = play_step(app, &a.name, first)?; + let pending = steps.len(); + if pending > 0 { + app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None }); + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + } + Ok(json!({"results": [result], "pending": pending})) +} + +/// Runs one step of a paced playback as its own undo step, named `label` → the step's result. +fn play_step(app: &mut VectorcraftApp, label: &str, step: Value) -> Result { + let r = app.run("command.batch", json!({"label": label, "commands": [step]}))?; + Ok(r.get("results").and_then(|r| r.get(0)).cloned().unwrap_or(Value::Null)) +} + +/// The speed actions play at (Actions panel menu › Playback Options…). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum PlaybackSpeed { + /// Every included step at once. + #[default] + Accelerated, + /// One step per frame, so the window draws each step's result before the next step runs. + Step, + /// [`PlaybackOptions::seconds`] between steps. + Pause, +} + +/// The pause between steps that Pause For takes, in whole seconds: VectorCraft's own range. +pub const PAUSE_SECONDS: std::ops::RangeInclusive = 1..=60; + +/// How actions play, kept with the UI preferences. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct PlaybackOptions { + pub speed: PlaybackSpeed, + /// The pause between steps with [`PlaybackSpeed::Pause`], within [`PAUSE_SECONDS`]. It is kept + /// while another speed is chosen. + pub seconds: u32, +} + +impl Default for PlaybackOptions { + fn default() -> Self { + Self { speed: PlaybackSpeed::Accelerated, seconds: *PAUSE_SECONDS.start() } + } +} + +/// Reads saved [`PlaybackOptions`]: a value that is not a valid one loads as the default. +pub fn deserialize_playback<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(serde_json::from_value::(v).ok().filter(|o| PAUSE_SECONDS.contains(&o.seconds)).unwrap_or_default()) +} + +/// A paced playback in progress: the steps still to run. +#[derive(Clone, Debug)] +pub struct Playing { + /// The action's name, which names each step's undo step. + label: String, + steps: std::collections::VecDeque, + /// The options the action started playing with. + options: PlaybackOptions, + /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame + /// after the first step, which starts the first pause. + next_at: Option, +} + +/// Runs the next step of the paced playback in progress when it is due at `now` (seconds on the +/// app's clock): with Step by Step at each call, so each frame runs one step; with Pause For once +/// the pause after the step before has passed. A step that fails ends the playback and shows its +/// error. → the seconds until the window should draw again while playback goes on +pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { + let playing = app.ui.action_playing.as_mut()?; + let pause = f64::from(playing.options.seconds); + if playing.options.speed == PlaybackSpeed::Pause { + let due = *playing.next_at.get_or_insert(now + pause); + if now < due { + return Some(due - now); + } + // The next pause starts when this step runs. + playing.next_at = Some(now + pause); + } + let Some(step) = playing.steps.pop_front() else { + app.ui.action_playing = None; + return None; + }; + let label = playing.label.clone(); + if playing.steps.is_empty() { + app.ui.action_playing = None; + } + if let Err(e) = play_step(app, &label, step) { + app.ui.action_playing = None; + app.status(e); + return None; + } + let playing = app.ui.action_playing.as_ref()?; + Some(if playing.options.speed == PlaybackSpeed::Pause { pause } else { 0.0 }) +} + +/// The command behind Playback Options… ([`playback_options`]). +pub const PLAYBACK_OPTIONS: &str = "ui.action.playbackOptions"; + +/// `ui.action.playbackOptions {speed?, seconds?}`: sets how actions play. `speed` is +/// `accelerated` (every step at once, the default), `step` (one step at a time, the window drawn +/// after each) or `pause` (`seconds` between steps); `seconds` is a whole number in +/// [`PAUSE_SECONDS`]. A param left out keeps its value. Any other value is an error, and then +/// nothing changes. An action already playing keeps its speed. → {speed, seconds} +pub fn playback_options(app: &mut VectorcraftApp, p: &Value) -> Result { + let current = app.ui.action_playback; + let speed = match p.get("speed") { + None => current.speed, + Some(v) => match v.as_str() { + Some("accelerated") => PlaybackSpeed::Accelerated, + Some("step") => PlaybackSpeed::Step, + Some("pause") => PlaybackSpeed::Pause, + _ => return Err("speed must be accelerated, step or pause".into()), + }, + }; + let seconds = match p.get("seconds") { + None => current.seconds, + Some(v) => v + .as_u64() + .and_then(|s| u32::try_from(s).ok()) + .filter(|s| PAUSE_SECONDS.contains(s)) + .ok_or("seconds must be a whole number from 1 to 60")?, + }; + app.ui.action_playback = PlaybackOptions { speed, seconds }; + Ok(json!({"speed": speed, "seconds": seconds})) } /// The command behind the Actions panel's set, action and step checkmarks. @@ -444,11 +584,14 @@ pub fn record(app: &mut VectorcraftApp, p: &Value) -> Result { /// `ui.action.stop {}`: ends the recording in progress and keeps its steps, in the action New /// Action made for it, else in a new action after the last action of its set, as the bottom bar's -/// Stop Playing/Recording does. With nothing recording it changes nothing. → {stopped} +/// Stop Playing/Recording does. It also ends a playback at Step by Step or Pause For: the steps +/// already played stay, and the rest do not run. With nothing recording or playing it changes +/// nothing. → {stopped} pub fn stop(app: &mut VectorcraftApp, _: &Value) -> Result { - let stopped = app.ui.recording.is_some(); + let playing = app.ui.action_playing.take().is_some(); + let recording = app.ui.recording.is_some(); stop_recording(app); - Ok(json!({ "stopped": stopped })) + Ok(json!({ "stopped": recording || playing })) } /// The command that `chord` runs under `km`, pressed once or pressed twice. @@ -801,6 +944,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut egui::Ui) { { crate::dialogs::action_set_options::open_action(app, s, a); } + if widgets::menu_item(ui, tl!("Playback Options…"), true, false) { + crate::dialogs::action_playback::open(app); + } ui.separator(); // As commands, so a file dialog shown off the UI thread saves or loads when it answers. // Save Actions… names the current set by its id, so a file dialog that answers later saves that set. @@ -2662,4 +2808,145 @@ mod tests { "the command keeps its shortcut" ); } + + /// A document with one rectangle selected and the set "Moves" with one action that moves it + /// right three times, by 1, 2 and 4 pt → (the app, the rectangle's left edge as it moves). + fn app_with_three_moves() -> (VectorcraftApp, impl Fn(&VectorcraftApp) -> f64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let id = vectorcraft_doc::NodeId( + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(), + ); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + let step = |dx: u32| ("object.move".to_string(), json!({"dx": dx, "dy": 0})); + app.ui.action_sets = vec![ActionSet::new("Moves", vec![Action::new("Three Moves", vec![step(1), step(2), step(4)])])]; + let x = move |app: &VectorcraftApp| app.session.active().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().x0 - 10.0; + (app, x) + } + + fn undo_steps(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + #[test] + fn playback_options_sets_each_speed_and_refuses_bad_values() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.ui.action_playback, PlaybackOptions { speed: PlaybackSpeed::Accelerated, seconds: 1 }, "Accelerated is the default"); + assert_eq!(app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(), json!({"speed": "step", "seconds": 1})); + assert_eq!(app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 2})).unwrap(), json!({"speed": "pause", "seconds": 2})); + assert_eq!( + app.run(PLAYBACK_OPTIONS, json!({"speed": "accelerated"})).unwrap(), + json!({"speed": "accelerated", "seconds": 2}), + "seconds kept" + ); + assert_eq!(app.run(PLAYBACK_OPTIONS, json!({"seconds": 60})).unwrap(), json!({"speed": "accelerated", "seconds": 60}), "speed kept"); + let kept = app.ui.action_playback; + for bad in [json!({"speed": "fast"}), json!({"speed": null}), json!({"speed": 1})] { + assert_eq!(app.run(PLAYBACK_OPTIONS, bad.clone()).unwrap_err(), "speed must be accelerated, step or pause", "{bad}"); + } + for bad in [json!(0), json!(61), json!(2.5), json!(-1), json!("2"), json!(null)] { + let p = json!({"speed": "pause", "seconds": bad}); + assert_eq!(app.run(PLAYBACK_OPTIONS, p).unwrap_err(), "seconds must be a whole number from 1 to 60", "{bad}"); + } + assert_eq!(app.ui.action_playback, kept, "a refused value changes nothing"); + // Kept with the UI preferences; a saved value that is not valid loads as the default. + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 5})).unwrap(); + let mut saved = serde_json::to_value(&app.ui).unwrap(); + let ui = serde_json::from_value::(saved.clone()).unwrap(); + assert_eq!(ui.action_playback, PlaybackOptions { speed: PlaybackSpeed::Pause, seconds: 5 }); + for bad in [json!({"speed": "pause", "seconds": 0}), json!({"speed": "slow", "seconds": 5}), json!("step")] { + saved["action_playback"] = bad; + assert_eq!(serde_json::from_value::(saved.clone()).unwrap().action_playback, PlaybackOptions::default()); + } + } + + #[test] + fn the_playback_options_dialog_sets_the_speed_and_pause() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step", "seconds": 3})).unwrap(); + crate::dialogs::action_playback::open(&mut app); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.kind.as_str(), d.str("speed"), d.fields["seconds"].clone()), ("actionPlayback", "step".to_string(), json!(3))); + d.fields.insert("speed".into(), json!("pause")); + d.fields.insert("seconds".into(), json!(4)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.ui.action_playback, PlaybackOptions { speed: PlaybackSpeed::Pause, seconds: 4 }); + } + + #[test] + fn accelerated_playback_plays_every_step_as_one_undo_step() { + let (mut app, x) = app_with_three_moves(); + let before = undo_steps(&app); + play(&mut app, 0, 0).unwrap(); + assert_eq!(x(&app), 7.0); + assert_eq!(undo_steps(&app), before + 1); + assert!(app.ui.action_playing.is_none()); + assert_eq!(tick_playback(&mut app, 0.0), None, "nothing waits for a frame"); + } + + #[test] + fn step_by_step_plays_one_step_per_frame_and_redraws_between_steps() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + let before = undo_steps(&app); + assert_eq!(play(&mut app, 0, 0).unwrap()["pending"], json!(2)); + assert_eq!(x(&app), 1.0, "the first step runs at once"); + assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the window draws again before the next step"); + assert_eq!(x(&app), 3.0, "one more step in this frame"); + assert_eq!(tick_playback(&mut app, 0.0), None, "the last step ends the playback"); + assert_eq!(x(&app), 7.0); + assert!(app.ui.action_playing.is_none()); + assert_eq!(tick_playback(&mut app, 0.0), None); + assert_eq!(x(&app), 7.0); + assert_eq!(undo_steps(&app), before + 3, "each step is its own undo step"); + assert_eq!(app.session.active().unwrap().history.undo.last().unwrap().label, "Three Moves"); + } + + #[test] + fn pause_for_waits_the_seconds_between_steps() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 2})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(x(&app), 1.0); + assert_eq!(tick_playback(&mut app, 10.0), Some(2.0), "the pause starts in the frame after the first step"); + assert_eq!(tick_playback(&mut app, 11.5), Some(0.5)); + assert_eq!(x(&app), 1.0, "nothing runs before the pause has passed"); + assert_eq!(tick_playback(&mut app, 12.0), Some(2.0)); + assert_eq!(x(&app), 3.0, "the second step runs after 2 s"); + assert!(tick_playback(&mut app, 13.9).is_some_and(|wait| (wait - 0.1).abs() < 1e-9)); + assert_eq!(x(&app), 3.0); + assert_eq!(tick_playback(&mut app, 14.0), None); + assert_eq!(x(&app), 7.0, "the third step runs 2 s after the second"); + assert!(app.ui.action_playing.is_none()); + } + + #[test] + fn stop_ends_a_paced_playback_and_another_action_waits_for_it() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 1})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(play(&mut app, 0, 0).unwrap_err(), "an action is already playing"); + assert_eq!(app.run(PLAY_ACTION, json!({"action": "Three Moves"})).unwrap_err(), "an action is already playing"); + assert_eq!(x(&app), 1.0); + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": true})); + assert_eq!(tick_playback(&mut app, 100.0), None); + assert_eq!(x(&app), 1.0, "the steps after Stop do not run; the one played stays"); + assert_eq!(app.run(STOP_RECORDING, json!({})).unwrap(), json!({"stopped": false})); + play(&mut app, 0, 0).unwrap(); + assert_eq!(x(&app), 2.0, "an action plays again after Stop"); + } + + #[test] + fn a_failing_step_ends_a_paced_playback_with_its_error() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + app.ui.action_sets[0].actions[0].steps[1] = ("no.such.command".into(), json!({})); + play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), None); + assert!(app.ui.action_playing.is_none()); + assert!(!app.ui.status.is_empty(), "the step's error shows"); + assert_eq!(tick_playback(&mut app, 0.0), None); + assert_eq!(x(&app), 1.0, "the step after the failing one does not run"); + } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 84cf014c86..77c19753fc 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -496,6 +496,12 @@ pub struct UiState { /// adds a new action, as after Begin Recording. #[serde(skip)] pub recording_into: Option, + /// How actions play (Actions panel menu › Playback Options…), kept with the UI preferences. + #[serde(default, deserialize_with = "crate::panels::actions::deserialize_playback")] + pub action_playback: crate::panels::actions::PlaybackOptions, + /// The playback at Step by Step or Pause For in progress, if any. Not saved. + #[serde(skip)] + pub action_playing: Option, /// Keyboard shortcut overrides: command id, `tool:` or `panel:` → chord ("" = none), /// stored in the form every earlier version reads. #[serde(default, with = "crate::keymap::stored")] @@ -970,6 +976,8 @@ impl Default for UiState { action_sets_selected: vec![], recording: None, recording_into: None, + action_playback: Default::default(), + action_playing: None, shortcut_overrides: Default::default(), shortcut_set: default_shortcut_set(), workspace: default_workspace(), diff --git a/docs/mcp.md b/docs/mcp.md index c68c6f1844..db349923a4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1848,12 +1848,24 @@ already walks Image Trace. Short agent entry points: a text field has the keyboard, or while a tool is busy. Editing command shortcuts (`shortcuts.set`, Keyboard Shortcuts), loading preferences and `ui.actionSet.load` preserve action function keys. When several actions have the same key, the first in panel order plays. A stored key reserved on the current platform does not play an action. -- Actions: `ui.action.play {action, set?}` plays the action named `action` as one undoable batch; `set` names the set - to look in (default: every set), and a `set` that is not a string is an error. A name that no action has, or that - more than one action in the sets looked in has, or whose every step is excluded, is an error, and then nothing plays. +- Actions: `ui.action.play {action, set?}` plays the action named `action` at the speed `ui.action.playbackOptions` + sets; `set` names the set to look in (default: every set), and a `set` that is not a string is an error. At + Accelerated it plays the action as one undoable batch and returns what `command.batch` returns. At Step by Step and + Pause For it plays the first step at once and returns `{results: [the first step's result], pending}`, where + `pending` counts the steps still to play; the app plays them one at a time, each as its own undo step. A name that no + action has, or that more than one action in the sets looked in has, or whose every step is excluded, is an error, and + then nothing plays. So is an action played while another is still playing at Step by Step or Pause For. +- Actions: `ui.action.playbackOptions {speed?, seconds?}` sets how the Actions panel plays actions and returns + `{speed, seconds}`. `speed` is `accelerated` (the default: every step at once), `step` (one step at a time, with the + window drawn after each step before the next runs) or `pause` (a pause of `seconds` between steps). `seconds` is a + whole number from 1 to 60, VectorCraft's own range, and stays set while another speed is chosen. A param left out + keeps its value. Any other `speed` or `seconds` is an error, and then nothing changes. The setting is kept with the UI + preferences. The panel menu's Playback Options… opens the `actionPlayback` dialog (`speed`, `seconds`), whose OK runs + this. Batch… (`action.batch`) plays every step at once whatever the setting. - Actions: `ui.action.stop {}` ends the recording in progress and keeps its steps, in the action `ui.action.new` made - for it, else in a new action after the last action of its set, and returns `{stopped}`. With nothing recording it - changes nothing. The panel's Stop Playing/Recording button runs this. + for it, else in a new action after the last action of its set, and returns `{stopped}`. It also ends an action + playing at Step by Step or Pause For: the steps already played stay, and the rest do not play. With nothing + recording or playing it changes nothing. The panel's Stop Playing/Recording button runs this. - Action sets: `ui.actionSet.delete {sets?: [index], ids?: [id]}` deletes the Actions panel's sets at these indexes (0 is the top set) with their actions, by default the current set, and returns `{deleted}`. An index past the last set is an error, and then no set is deleted. `ids` holds the panel's own set ids, which its question passes: the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1959b42612..733422604e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -581,6 +581,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: expand an action to show its recorded steps, then clear a step's checkmark to keep it in the action but skip it during playback. The action and set checkmarks include or exclude all their steps; a mixed checkmark includes all. Alt/Option-clicking a step checkmark keeps that step as it was and applies the opposite inclusion state to the other steps in its action. This follows the public [Exclude commands from an action](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) guide; the scope of the mixed-state and Alt-click behavior is VectorCraft's design. The exclusion survives UI restart, action duplication, and `.vcactions` save/load. Existing version 1 action set files load with every step included. + - Actions panel: the panel menu's Playback Options… sets how actions play: Accelerated (the default) plays every step at once, Step by Step plays one step at a time with the canvas drawn after each, and Pause For waits the given number of seconds between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html); `ui.action.playbackOptions`). VectorCraft's own rules, which the page does not cover: the pause is a whole number of seconds from 1 to 60, the setting is kept with the UI preferences, Stop Playing/Recording ends a paced playback, each step of a paced playback is its own undo step, and Batch… plays at full speed. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index f40288a3a3..62d62e5d92 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -320,6 +320,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls | | Actions panel: ≡ › Save Actions… saves the current set with all its actions to a file and ≡ › Load Actions… adds a saved set ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html)) | partial | `ui.actionSet.save`, `ui.actionSet.load`; `panels/actions.rs` tests. The file is VectorCraft's own `.vcactions` JSON; the reference app's `.aia` files and Reset, Clear and Replace Actions remain | | Actions panel: ≡ › Action Options… renames the selected action and sets its function key and color ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html)) | partial | `ui.action.options`; `panels/actions.rs` tests (part of #1629). The color shows nowhere until Button Mode exists | +| Actions panel: ≡ › Playback Options… plays actions Accelerated, Step by Step or with a pause between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html)) | done | `ui.action.playbackOptions`; `panels/actions.rs` tests. The pause is a whole number of seconds from 1 to 60 (VectorCraft's own range); Batch… plays at full speed | | Actions panel: a clicked action stays selected for Play Current Selection and Delete Selection | partial | #1853 (part of #1629); editing actions and action shortcuts remain | | Actions panel: Create New Set (bottom bar, ≡ › New Set…) names a new set and Set Options… renames the current one; a click on a set's name makes it current and a recording goes into the current set ([helpx: Automation with actions](https://helpx.adobe.com/illustrator/using/automation-actions.html)); the current set is kept with the UI preferences, and with no set current a recording goes into the first set, which becomes current | partial | #3712; dragging actions between sets remains | | Actions panel: Create New Action (bottom bar, ≡ › New Action…) asks for the name, set, function key and color, and Record adds the action and records into it ([Create new actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/record-actions.html)) | partial | `ui.action.new`, `ui.action.play`; `panels/actions.rs` tests. A function key plays its action, even when a command has the same shortcut, and the command keeps it. Button Mode, which shows the color, remains | From f5f3ca428699c6ba24590b7c327766cde3641290 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 01:44:12 -0800 Subject: [PATCH 066/482] Actions: Step by Step draws the first step, and recorded batches play as their steps Step by Step holds the frame after Play, so the first step's result is drawn before the second step runs, also when the panel's Play button runs after the canvas drew. An action step recorded as command.batch (an action played while recording, including one playing at Step by Step or Pause For, or a panel operation that runs as one batch) now plays as its own steps in Play and Batch..., instead of failing with "batches cannot nest". --- crates/ui-egui/src/panels/actions.rs | 54 +++++++++++++++++++++++++--- docs/mcp.md | 4 ++- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 12d0bd4760..72b66d56c1 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -61,12 +61,18 @@ impl Action { } } + /// The included steps as `command.batch` takes them. A recorded `command.batch` step (an action + /// played, or a panel operation that runs as one batch, while recording) gives its own steps, + /// since batches do not nest. pub(crate) fn included_commands(&self) -> Vec { self.steps .iter() .enumerate() .filter(|(i, _)| !self.excluded_steps.contains(i)) - .map(|(_, (command, params))| json!({"command": command, "params": params})) + .flat_map(|(_, (command, params))| match params.get("commands").and_then(Value::as_array) { + Some(steps) if command == "command.batch" => steps.clone(), + _ => vec![json!({"command": command, "params": params})], + }) .collect() } } @@ -226,7 +232,8 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result 0 { - app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None }); + let hold = options.speed == PlaybackSpeed::Step; + app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None, hold }); if let Some(ctx) = &app.ui_ctx { ctx.request_repaint(); } @@ -288,14 +295,21 @@ pub struct Playing { /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame /// after the first step, which starts the first pause. next_at: Option, + /// With Step by Step, set until the first frame after the first step: that frame draws the + /// first step's result and runs no step, since Play in the panel can run after the canvas drew. + hold: bool, } /// Runs the next step of the paced playback in progress when it is due at `now` (seconds on the -/// app's clock): with Step by Step at each call, so each frame runs one step; with Pause For once -/// the pause after the step before has passed. A step that fails ends the playback and shows its -/// error. → the seconds until the window should draw again while playback goes on +/// app's clock): with Step by Step at each call after the first, so each frame runs one step and the +/// frame after Play draws the first step; with Pause For once the pause after the step before has +/// passed. A step that fails ends the playback and shows its error. → the seconds until the window +/// should draw again while playback goes on pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { let playing = app.ui.action_playing.as_mut()?; + if std::mem::take(&mut playing.hold) { + return Some(0.0); + } let pause = f64::from(playing.options.seconds); if playing.options.speed == PlaybackSpeed::Pause { let due = *playing.next_at.get_or_insert(now + pause); @@ -2892,6 +2906,8 @@ mod tests { let before = undo_steps(&app); assert_eq!(play(&mut app, 0, 0).unwrap()["pending"], json!(2)); assert_eq!(x(&app), 1.0, "the first step runs at once"); + assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the frame after Play draws the first step"); + assert_eq!(x(&app), 1.0, "and runs no step, even when Play ran after the canvas drew"); assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the window draws again before the next step"); assert_eq!(x(&app), 3.0, "one more step in this frame"); assert_eq!(tick_playback(&mut app, 0.0), None, "the last step ends the playback"); @@ -2937,12 +2953,40 @@ mod tests { assert_eq!(x(&app), 2.0, "an action plays again after Stop"); } + #[test] + fn an_action_recorded_while_another_plays_plays_its_steps() { + let (mut app, x) = app_with_three_moves(); + // Accelerated: the recording gets the played action as one batch step. + app.run(START_RECORDING, json!({"set": 0})).unwrap(); + play(&mut app, 0, 0).unwrap(); + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(app.ui.action_sets[0].actions[1].steps.iter().map(|s| s.0.as_str()).collect::>(), ["command.batch"]); + assert_eq!(x(&app), 7.0); + play(&mut app, 0, 1).unwrap(); + assert_eq!(x(&app), 14.0, "the batch step plays its moves"); + // Step by Step: recording begins after the first step, and gets each later step as a batch. + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + play(&mut app, 0, 0).unwrap(); + app.run(START_RECORDING, json!({"set": 0})).unwrap(); + while tick_playback(&mut app, 0.0).is_some() {} + app.run(STOP_RECORDING, json!({})).unwrap(); + assert_eq!(x(&app), 21.0); + assert_eq!(app.ui.action_sets[0].actions[2].steps.len(), 2); + play(&mut app, 0, 2).unwrap(); + while tick_playback(&mut app, 0.0).is_some() {} + assert_eq!(x(&app), 27.0, "paced: the recorded batches play the second and third moves"); + app.run(PLAYBACK_OPTIONS, json!({"speed": "accelerated"})).unwrap(); + play(&mut app, 0, 2).unwrap(); + assert_eq!(x(&app), 33.0, "accelerated: the recorded batches play inside the action's batch"); + } + #[test] fn a_failing_step_ends_a_paced_playback_with_its_error() { let (mut app, x) = app_with_three_moves(); app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); app.ui.action_sets[0].actions[0].steps[1] = ("no.such.command".into(), json!({})); play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the frame after Play draws the first step"); assert_eq!(tick_playback(&mut app, 0.0), None); assert!(app.ui.action_playing.is_none()); assert!(!app.ui.status.is_empty(), "the step's error shows"); diff --git a/docs/mcp.md b/docs/mcp.md index db349923a4..4539da74cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1854,7 +1854,9 @@ already walks Image Trace. Short agent entry points: Pause For it plays the first step at once and returns `{results: [the first step's result], pending}`, where `pending` counts the steps still to play; the app plays them one at a time, each as its own undo step. A name that no action has, or that more than one action in the sets looked in has, or whose every step is excluded, is an error, and - then nothing plays. So is an action played while another is still playing at Step by Step or Pause For. + then nothing plays. So is an action played while another is still playing at Step by Step or Pause For. A + `command.batch` step, which an action played or a panel operation run as one batch records, plays as its own steps, + here and in Batch…. - Actions: `ui.action.playbackOptions {speed?, seconds?}` sets how the Actions panel plays actions and returns `{speed, seconds}`. `speed` is `accelerated` (the default: every step at once), `step` (one step at a time, with the window drawn after each step before the next runs) or `pause` (a pause of `seconds` between steps). `seconds` is a From 64c9bfa720aefc9ed5bf687d29d514398464fe36 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:18:22 -0800 Subject: [PATCH 067/482] Actions: a paced playback ends when a step comes due in another document Step by Step and Pause For remember the document that was active after each step. When the next step is due and a different document is active (another one was made active, or that one was closed), the playback ends with a status and the rest of the steps do not run. A step that makes another document active itself does not end the playback. --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/actions.rs | 59 +++++++++++++++++++++++-- docs/mcp.md | 5 ++- docs/target-app-parity.md | 2 +- 30 files changed, 87 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 9361d3b37f..8e6fe27116 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5503,6 +5503,7 @@ theme Appearance Външен вид @msg name is empty името е празно @msg an action is already recording вече се записва действие @msg an action is already playing вече се възпроизвежда действие +@msg the action stopped playing: its document is no longer active действието спря: документът му вече не е активен @msg speed must be accelerated, step or pause speed трябва да е accelerated, step или pause @msg seconds must be a whole number from 1 to 60 seconds трябва да е цяло число от 1 до 60 @msg no such function key няма такъв функционален клавиш diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index cfc1f39fa1..ee46902140 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5507,6 +5507,7 @@ mark-style Japanese Japanski @msg name is empty naziv je prazan @msg an action is already recording akcija se već snima @msg an action is already playing akcija se već reproducira +@msg the action stopped playing: its document is no longer active reprodukcija akcije je zaustavljena: njen dokument više nije aktivan @msg speed must be accelerated, step or pause speed mora biti accelerated, step ili pause @msg seconds must be a whole number from 1 to 60 seconds mora biti cijeli broj od 1 do 60 @msg no such function key nema takve funkcijske tipke diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 1929ffa58e..4ecb3fb3b4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5193,6 +5193,7 @@ digits Malayalam Malaiàlam @msg name is empty el nom és buit @msg an action is already recording ja s’està enregistrant una acció @msg an action is already playing ja s’està reproduint una acció +@msg the action stopped playing: its document is no longer active l’acció s’ha aturat: el seu document ja no és l’actiu @msg speed must be accelerated, step or pause speed ha de ser accelerated, step o pause @msg seconds must be a whole number from 1 to 60 seconds ha de ser un nombre enter de l’1 al 60 @msg no such function key no existeix aquesta tecla de funció diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 73887e0f18..0b568e67d4 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5593,6 +5593,7 @@ mark-style Japanese Japonské @msg name is empty název je prázdný @msg an action is already recording akce se už zaznamenává @msg an action is already playing akce se už přehrává +@msg the action stopped playing: its document is no longer active přehrávání akce se zastavilo: její dokument už není aktivní @msg speed must be accelerated, step or pause speed musí být accelerated, step nebo pause @msg seconds must be a whole number from 1 to 60 seconds musí být celé číslo od 1 do 60 @msg no such function key taková funkční klávesa neexistuje diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7237702c66..abf41f3fc5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5388,6 +5388,7 @@ swatch Bright Violet Kraftig violet @msg name is empty navnet er tomt @msg an action is already recording en handling optages allerede @msg an action is already playing en handling afspilles allerede +@msg the action stopped playing: its document is no longer active handlingen stoppede: dens dokument er ikke længere aktivt @msg speed must be accelerated, step or pause speed skal være accelerated, step eller pause @msg seconds must be a whole number from 1 to 60 seconds skal være et heltal fra 1 til 60 @msg no such function key ingen sådan funktionstast diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index dbd5e3e216..9b9d7c8393 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5171,6 +5171,7 @@ effect Soft Weich @msg name is empty Name ist leer @msg an action is already recording eine Aktion wird bereits aufgezeichnet @msg an action is already playing eine Aktion wird bereits abgespielt +@msg the action stopped playing: its document is no longer active die Aktion wurde angehalten: ihr Dokument ist nicht mehr aktiv @msg speed must be accelerated, step or pause speed muss accelerated, step oder pause sein @msg seconds must be a whole number from 1 to 60 seconds muss eine ganze Zahl von 1 bis 60 sein @msg no such function key keine solche Funktionstaste diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 2ef7e8cb3b..d909fe3ed6 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5544,6 +5544,7 @@ effect Points Σημεία @msg name is empty το όνομα είναι κενό @msg an action is already recording μια ενέργεια καταγράφεται ήδη @msg an action is already playing μια ενέργεια αναπαράγεται ήδη +@msg the action stopped playing: its document is no longer active η αναπαραγωγή της ενέργειας σταμάτησε: το έγγραφό της δεν είναι πλέον ενεργό @msg speed must be accelerated, step or pause το speed πρέπει να είναι accelerated, step ή pause @msg seconds must be a whole number from 1 to 60 το seconds πρέπει να είναι ακέραιος από 1 έως 60 @msg no such function key δεν υπάρχει τέτοιο πλήκτρο λειτουργίας diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 91f7670489..2b85aefddc 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5534,6 +5534,7 @@ mark-style Japanese Japonesas @msg name is empty el nombre está vacío @msg an action is already recording ya se está grabando una acción @msg an action is already playing ya se está reproduciendo una acción +@msg the action stopped playing: its document is no longer active la acción se detuvo: su documento ya no es el activo @msg speed must be accelerated, step or pause speed debe ser accelerated, step o pause @msg seconds must be a whole number from 1 to 60 seconds debe ser un número entero de 1 a 60 @msg no such function key no existe esa tecla de función diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1cda3c91dd..f110474e40 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5556,6 +5556,7 @@ mark-style Japanese Japanilainen @msg name is empty nimi on tyhjä @msg an action is already recording toimintoa nauhoitetaan jo @msg an action is already playing toimintoa toistetaan jo +@msg the action stopped playing: its document is no longer active toiminnon toisto pysähtyi: sen asiakirja ei ole enää aktiivinen @msg speed must be accelerated, step or pause speed on oltava accelerated, step tai pause @msg seconds must be a whole number from 1 to 60 seconds on oltava kokonaisluku 1:stä 60:een @msg no such function key toimintonäppäintä ei ole diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0fb2551438..3eeb02dbf5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5588,6 +5588,7 @@ theme Appearance Apparence @msg name is empty le nom est vide @msg an action is already recording un script est déjà en cours d’enregistrement @msg an action is already playing un script est déjà en cours d’exécution +@msg the action stopped playing: its document is no longer active le script s’est arrêté : son document n’est plus le document actif @msg speed must be accelerated, step or pause speed doit valoir accelerated, step ou pause @msg seconds must be a whole number from 1 to 60 seconds doit être un nombre entier de 1 à 60 @msg no such function key touche de fonction inexistante diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 175e3908a2..0ff5d8cd89 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5576,6 +5576,7 @@ imageTrace Outline Körvonal @msg name is empty a név üres @msg an action is already recording már folyik egy művelet felvétele @msg an action is already playing már folyik egy művelet lejátszása +@msg the action stopped playing: its document is no longer active a művelet lejátszása leállt: a dokumentuma már nem az aktív @msg speed must be accelerated, step or pause a speed értéke accelerated, step vagy pause lehet @msg seconds must be a whole number from 1 to 60 a seconds értéke 1 és 60 közötti egész szám lehet @msg no such function key nincs ilyen funkcióbillentyű diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ed1c8a1685..d0194dcc7d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5388,6 +5388,7 @@ swatch Bright Violet Violet cerah @msg name is empty nama kosong @msg an action is already recording sebuah tindakan sedang direkam @msg an action is already playing sebuah tindakan sedang diputar +@msg the action stopped playing: its document is no longer active tindakan berhenti diputar: dokumennya tidak lagi aktif @msg speed must be accelerated, step or pause speed harus accelerated, step, atau pause @msg seconds must be a whole number from 1 to 60 seconds harus bilangan bulat dari 1 sampai 60 @msg no such function key tidak ada tombol fungsi seperti itu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ab5a5a6690..2bbdc4bfa9 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -5206,6 +5206,7 @@ lighting Light Luce @msg name is empty il nome è vuoto @msg an action is already recording è già in corso la registrazione di un’azione @msg an action is already playing è già in corso la riproduzione di un’azione +@msg the action stopped playing: its document is no longer active la riproduzione dell’azione si è interrotta: il suo documento non è più attivo @msg speed must be accelerated, step or pause speed deve essere accelerated, step o pause @msg seconds must be a whole number from 1 to 60 seconds deve essere un numero intero da 1 a 60 @msg no such function key tasto funzione inesistente diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 92437db433..b8d45181f0 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5249,6 +5249,7 @@ lighting Light ライト @msg name is empty 名前が空です @msg an action is already recording すでにアクションを記録中です @msg an action is already playing すでにアクションを再生中です +@msg the action stopped playing: its document is no longer active アクションの再生を停止しました: そのドキュメントはアクティブではなくなりました @msg speed must be accelerated, step or pause speed には accelerated、step または pause を指定してください @msg seconds must be a whole number from 1 to 60 seconds には 1 から 60 までの整数を指定してください @msg no such function key 指定されたファンクションキーが見つかりません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 7957f671e8..dac1278fcc 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5301,6 +5301,7 @@ imageTrace Outline კონტური @msg name is empty სახელი ცარიელია @msg an action is already recording მოქმედება უკვე იწერება @msg an action is already playing მოქმედება უკვე სრულდება +@msg the action stopped playing: its document is no longer active მოქმედება შეჩერდა: მისი დოკუმენტი აღარ არის აქტიური @msg speed must be accelerated, step or pause speed უნდა იყოს accelerated, step ან pause @msg seconds must be a whole number from 1 to 60 seconds უნდა იყოს მთელი რიცხვი 1-დან 60-მდე @msg no such function key ასეთი ფუნქციური კლავიში არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 5e40783947..76c60eda46 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5167,6 +5167,7 @@ lighting Light 광원 @msg name is empty 이름이 비어 있습니다 @msg an action is already recording 이미 액션을 기록하고 있습니다 @msg an action is already playing 이미 액션을 재생하고 있습니다 +@msg the action stopped playing: its document is no longer active 액션 재생이 중지되었습니다: 해당 문서가 더 이상 활성 상태가 아닙니다 @msg speed must be accelerated, step or pause speed는 accelerated, step 또는 pause여야 합니다 @msg seconds must be a whole number from 1 to 60 seconds는 1에서 60 사이의 정수여야 합니다 @msg no such function key 해당 기능 키가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index c2aeadf939..d3e7864974 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5396,6 +5396,7 @@ swatch Bright Violet Felviolet @msg name is empty naam is leeg @msg an action is already recording er wordt al een actie opgenomen @msg an action is already playing er wordt al een actie afgespeeld +@msg the action stopped playing: its document is no longer active de actie is gestopt: het document ervan is niet meer actief @msg speed must be accelerated, step or pause speed moet accelerated, step of pause zijn @msg seconds must be a whole number from 1 to 60 seconds moet een geheel getal van 1 tot 60 zijn @msg no such function key functietoets bestaat niet diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1ad694245c..db43a45cd4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5446,6 +5446,7 @@ mark-style Japanese Japońskie @msg name is empty nazwa jest pusta @msg an action is already recording operacja jest już nagrywana @msg an action is already playing operacja jest już odtwarzana +@msg the action stopped playing: its document is no longer active odtwarzanie operacji zatrzymano: jej dokument nie jest już aktywny @msg speed must be accelerated, step or pause speed musi mieć wartość accelerated, step lub pause @msg seconds must be a whole number from 1 to 60 seconds musi być liczbą całkowitą od 1 do 60 @msg no such function key brak takiego klawisza funkcyjnego diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8a4480488b..0ddff27775 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5508,6 +5508,7 @@ mark-style Japanese Japonesas @msg name is empty o nome está vazio @msg an action is already recording uma ação já está sendo gravada @msg an action is already playing uma ação já está sendo reproduzida +@msg the action stopped playing: its document is no longer active a ação parou: o documento dela não está mais ativo @msg speed must be accelerated, step or pause speed deve ser accelerated, step ou pause @msg seconds must be a whole number from 1 to 60 seconds deve ser um número inteiro de 1 a 60 @msg no such function key tecla de função inexistente diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 94c30e8c57..077f033acd 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5201,6 +5201,7 @@ lighting Light Свет @msg name is empty имя пустое @msg an action is already recording действие уже записывается @msg an action is already playing действие уже воспроизводится +@msg the action stopped playing: its document is no longer active воспроизведение действия остановлено: его документ больше не активен @msg speed must be accelerated, step or pause speed должен быть accelerated, step или pause @msg seconds must be a whole number from 1 to 60 seconds должно быть целым числом от 1 до 60 @msg no such function key такой функциональной клавиши нет diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index e03ea97aea..4789dcbedc 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -5548,6 +5548,7 @@ theme Appearance Utseende @msg name is empty namnet är tomt @msg an action is already recording en åtgärd spelas redan in @msg an action is already playing en åtgärd spelas redan upp +@msg the action stopped playing: its document is no longer active åtgärden stoppades: dess dokument är inte längre aktivt @msg speed must be accelerated, step or pause speed måste vara accelerated, step eller pause @msg seconds must be a whole number from 1 to 60 seconds måste vara ett heltal från 1 till 60 @msg no such function key funktionstangenten finns inte diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 4e77e1f809..c89c627673 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -5257,6 +5257,7 @@ theme Appearance Görünüm @msg name is empty isim boş @msg an action is already recording zaten bir eylem kaydediliyor @msg an action is already playing zaten bir eylem oynatılıyor +@msg the action stopped playing: its document is no longer active eylemin oynatılması durdu: belgesi artık etkin değil @msg speed must be accelerated, step or pause speed accelerated, step veya pause olmalıdır @msg seconds must be a whole number from 1 to 60 seconds 1 ile 60 arasında bir tam sayı olmalıdır @msg no such function key öyle bir işlev tuşu yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 9e60d3b950..5cc74b986c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -5186,6 +5186,7 @@ lighting Light Світло @msg name is empty ім’я порожнє @msg an action is already recording дія вже записується @msg an action is already playing дія вже відтворюється +@msg the action stopped playing: its document is no longer active відтворення дії зупинено: її документ більше не активний @msg speed must be accelerated, step or pause speed має бути accelerated, step або pause @msg seconds must be a whole number from 1 to 60 seconds має бути цілим числом від 1 до 60 @msg no such function key такої функціональної клавіші немає diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2fb5b8e472..d23c1250de 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5187,6 +5187,7 @@ theme Appearance Giao diện @msg name is empty tên trống @msg an action is already recording đang ghi một hành động @msg an action is already playing đang phát một hành động +@msg the action stopped playing: its document is no longer active hành động đã dừng phát: tài liệu của nó không còn hoạt động @msg speed must be accelerated, step or pause speed phải là accelerated, step hoặc pause @msg seconds must be a whole number from 1 to 60 seconds phải là số nguyên từ 1 đến 60 @msg no such function key không có phím chức năng như vậy diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 082a32000c..42ac3614f8 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5426,6 +5426,7 @@ lighting Light 光源 @msg name is empty 名称为空 @msg an action is already recording 已在记录动作 @msg an action is already playing 已在播放动作 +@msg the action stopped playing: its document is no longer active 动作已停止播放:其文档不再是现用文档 @msg speed must be accelerated, step or pause speed 必须为 accelerated、step 或 pause @msg seconds must be a whole number from 1 to 60 seconds 必须为 1 到 60 之间的整数 @msg no such function key 没有此功能键 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 31b7e5cf1e..ede034f66f 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5244,6 +5244,7 @@ lighting Light 光源 @msg name is empty 名稱為空 @msg an action is already recording 已在錄製動作 @msg an action is already playing 已在播放動作 +@msg the action stopped playing: its document is no longer active 動作已停止播放:其文件不再是作用中文件 @msg speed must be accelerated, step or pause speed 必須為 accelerated、step 或 pause @msg seconds must be a whole number from 1 to 60 seconds 必須為 1 到 60 之間的整數 @msg no such function key 沒有這個功能鍵 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index bf9ecdbfe6..14322a3f37 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1239,7 +1239,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ crate::panels::actions::PLAY_ACTION, "Play Action", "", - "{action: name, set?: name} play the Actions panel's action named action at the speed ui.action.playbackOptions sets; set names the set to look in (default: every set). Accelerated plays it as one undoable batch → what command.batch returns. Step by Step and Pause For play its first step now and the others one at a time, each its own undo step, until the last or ui.action.stop → {results: [the first step's result], pending: the steps left}. A name no action has, or one that more than one action in the sets looked in has, or an action played while another is still playing step by step or with pauses, is an error and nothing plays", + "{action: name, set?: name} play the Actions panel's action named action at the speed ui.action.playbackOptions sets; set names the set to look in (default: every set). Accelerated plays it as one undoable batch → what command.batch returns. Step by Step and Pause For play its first step now and the others one at a time, each its own undo step, until the last, ui.action.stop, or a step that comes due while a different document is active than after the step before → {results: [the first step's result], pending: the steps left}. A name no action has, or one that more than one action in the sets looked in has, or an action played while another is still playing step by step or with pauses, is an error and nothing plays", ), ( crate::panels::actions::PLAYBACK_OPTIONS, diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 72b66d56c1..984ad5703e 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -233,7 +233,8 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result 0 { let hold = options.speed == PlaybackSpeed::Step; - app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None, hold }); + let doc = active_doc(app); + app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None, hold, doc }); if let Some(ctx) = &app.ui_ctx { ctx.request_repaint(); } @@ -298,14 +299,24 @@ pub struct Playing { /// With Step by Step, set until the first frame after the first step: that frame draws the /// first step's result and runs no step, since Play in the panel can run after the canvas drew. hold: bool, + /// The [`uid`](vectorcraft_engine::DocState::uid) of the document that was active after the + /// last step played, if any. + doc: Option, +} + +fn active_doc(app: &VectorcraftApp) -> Option { + app.session.active().map(|d| d.uid) } /// Runs the next step of the paced playback in progress when it is due at `now` (seconds on the /// app's clock): with Step by Step at each call after the first, so each frame runs one step and the /// frame after Play draws the first step; with Pause For once the pause after the step before has -/// passed. A step that fails ends the playback and shows its error. → the seconds until the window -/// should draw again while playback goes on +/// passed. A step that fails ends the playback and shows its error. When a step is due and the active +/// document is not the one that was active after the last step (another document was made active, +/// or that one was closed), the playback ends with a status and the rest do not run. → the seconds +/// until the window should draw again while playback goes on pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { + let doc = active_doc(app); let playing = app.ui.action_playing.as_mut()?; if std::mem::take(&mut playing.hold) { return Some(0.0); @@ -319,6 +330,11 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { // The next pause starts when this step runs. playing.next_at = Some(now + pause); } + if playing.doc != doc { + app.ui.action_playing = None; + app.status("the action stopped playing: its document is no longer active"); + return None; + } let Some(step) = playing.steps.pop_front() else { app.ui.action_playing = None; return None; @@ -332,7 +348,10 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { app.status(e); return None; } - let playing = app.ui.action_playing.as_ref()?; + let doc = active_doc(app); + let playing = app.ui.action_playing.as_mut()?; + // A step of the action may open, close or switch documents itself. + playing.doc = doc; Some(if playing.options.speed == PlaybackSpeed::Pause { pause } else { 0.0 }) } @@ -2980,6 +2999,38 @@ mod tests { assert_eq!(x(&app), 33.0, "accelerated: the recorded batches play inside the action's batch"); } + #[test] + fn a_paced_playback_ends_when_another_document_becomes_active() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 1})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), Some(1.0)); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + assert_eq!(tick_playback(&mut app, 0.5), Some(0.5), "nothing ends before the next step is due"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(tick_playback(&mut app, 1.0), Some(1.0)); + assert_eq!(x(&app), 3.0, "the document is active again when the step is due, so it runs"); + app.run("document.activate", json!({"index": 1})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + assert_eq!(tick_playback(&mut app, 5.0), None, "the playback ends"); + assert!(app.ui.action_playing.is_none()); + assert_eq!(app.ui.status, "the action stopped playing: its document is no longer active"); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &other), "no step ran in the other document"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(tick_playback(&mut app, 10.0), None); + assert_eq!(x(&app), 3.0, "the rest of the steps do not run in the first document either"); + // A step that makes another document active itself does not end the playback. + app.ui.action_sets[0].actions[0].steps.insert(0, ("document.activate".into(), json!({"index": 0}))); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + app.ui.status.clear(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), Some(0.0)); + while tick_playback(&mut app, 0.0).is_some() {} + assert_ne!(app.ui.status, "the action stopped playing: its document is no longer active"); + assert_eq!(x(&app), 10.0, "the moves after the step ran in the document it made active"); + } + #[test] fn a_failing_step_ends_a_paced_playback_with_its_error() { let (mut app, x) = app_with_three_moves(); diff --git a/docs/mcp.md b/docs/mcp.md index 4539da74cd..7076ce5ed5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1852,7 +1852,10 @@ already walks Image Trace. Short agent entry points: sets; `set` names the set to look in (default: every set), and a `set` that is not a string is an error. At Accelerated it plays the action as one undoable batch and returns what `command.batch` returns. At Step by Step and Pause For it plays the first step at once and returns `{results: [the first step's result], pending}`, where - `pending` counts the steps still to play; the app plays them one at a time, each as its own undo step. A name that no + `pending` counts the steps still to play; the app plays them one at a time, each as its own undo step. When the next + step is due and the active document is not the one that was active after the step before (another document was + made active, or that document was closed), the playback ends with a status and the rest do not play; a step that + makes another document active itself does not end it. A name that no action has, or that more than one action in the sets looked in has, or whose every step is excluded, is an error, and then nothing plays. So is an action played while another is still playing at Step by Step or Pause For. A `command.batch` step, which an action played or a panel operation run as one batch records, plays as its own steps, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 733422604e..fa2bc1f7da 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -581,7 +581,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel (record/playback, persisted), generic parameter dialogs for every "…" command. - Actions panel: the current set is kept with the UI preferences, so after a restart a recording goes into the set that was current, not into the first set. With no set current, Begin Recording records into the first set and makes it current. - Actions panel: expand an action to show its recorded steps, then clear a step's checkmark to keep it in the action but skip it during playback. The action and set checkmarks include or exclude all their steps; a mixed checkmark includes all. Alt/Option-clicking a step checkmark keeps that step as it was and applies the opposite inclusion state to the other steps in its action. This follows the public [Exclude commands from an action](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/exclude-commands-from-actions.html) guide; the scope of the mixed-state and Alt-click behavior is VectorCraft's design. The exclusion survives UI restart, action duplication, and `.vcactions` save/load. Existing version 1 action set files load with every step included. - - Actions panel: the panel menu's Playback Options… sets how actions play: Accelerated (the default) plays every step at once, Step by Step plays one step at a time with the canvas drawn after each, and Pause For waits the given number of seconds between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html); `ui.action.playbackOptions`). VectorCraft's own rules, which the page does not cover: the pause is a whole number of seconds from 1 to 60, the setting is kept with the UI preferences, Stop Playing/Recording ends a paced playback, each step of a paced playback is its own undo step, and Batch… plays at full speed. + - Actions panel: the panel menu's Playback Options… sets how actions play: Accelerated (the default) plays every step at once, Step by Step plays one step at a time with the canvas drawn after each, and Pause For waits the given number of seconds between steps ([Specify playback speed](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/specify-playback-speed.html); `ui.action.playbackOptions`). VectorCraft's own rules, which the page does not cover: the pause is a whole number of seconds from 1 to 60, the setting is kept with the UI preferences, a paced playback ends at Stop Playing/Recording or when a step comes due while another document is active, each step of a paced playback is its own undo step, and Batch… plays at full speed. - Actions panel: Delete Selection deletes the selected action set with its actions and keeps the other sets ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.delete`). VectorCraft's own rules, which the overview does not cover: deleting a set asks first, Shift-click on a set's name selects a range of sets to delete together, the panel menu's Delete does the same, and Default Actions and the last set can be deleted. Undo does not bring a deleted set back. - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. From 22f8be1c5dbad28f03ba3bfb07cdf2d19ac744fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:37:21 -0800 Subject: [PATCH 068/482] Actions: ui.action.play's doc comment names what each playback speed returns --- crates/ui-egui/src/panels/actions.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 984ad5703e..725c1aa453 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -553,10 +553,11 @@ pub fn action_options(app: &mut VectorcraftApp, p: &Value) -> Result Result { let name = p.get("action").and_then(Value::as_str).ok_or("no such action")?; let in_set = match p.get("set") { From 7f795682331b35372ea0fdcef0ea211889e6adab Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 02:51:15 -0800 Subject: [PATCH 069/482] Actions: Pause For starts each pause in the frame after the step --- crates/ui-egui/src/panels/actions.rs | 35 +++++++++++++++++++++------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 725c1aa453..36be11e22f 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -294,7 +294,7 @@ pub struct Playing { /// The options the action started playing with. options: PlaybackOptions, /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame - /// after the first step, which starts the first pause. + /// after each step, which starts the pause before the next one. next_at: Option, /// With Step by Step, set until the first frame after the first step: that frame draws the /// first step's result and runs no step, since Play in the panel can run after the canvas drew. @@ -310,8 +310,8 @@ fn active_doc(app: &VectorcraftApp) -> Option { /// Runs the next step of the paced playback in progress when it is due at `now` (seconds on the /// app's clock): with Step by Step at each call after the first, so each frame runs one step and the -/// frame after Play draws the first step; with Pause For once the pause after the step before has -/// passed. A step that fails ends the playback and shows its error. When a step is due and the active +/// frame after Play draws the first step; with Pause For once the pause has passed, which starts in +/// the frame after the step before, so a slow step or a late frame does not shorten it. A step that fails ends the playback and shows its error. When a step is due and the active /// document is not the one that was active after the last step (another document was made active, /// or that one was closed), the playback ends with a status and the rest do not run. → the seconds /// until the window should draw again while playback goes on @@ -327,8 +327,6 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { if now < due { return Some(due - now); } - // The next pause starts when this step runs. - playing.next_at = Some(now + pause); } if playing.doc != doc { app.ui.action_playing = None; @@ -352,7 +350,9 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { let playing = app.ui.action_playing.as_mut()?; // A step of the action may open, close or switch documents itself. playing.doc = doc; - Some(if playing.options.speed == PlaybackSpeed::Pause { pause } else { 0.0 }) + // With Pause For, the next frame starts the next pause. + playing.next_at = None; + Some(0.0) } /// The command behind Playback Options… ([`playback_options`]). @@ -2948,8 +2948,9 @@ mod tests { assert_eq!(tick_playback(&mut app, 10.0), Some(2.0), "the pause starts in the frame after the first step"); assert_eq!(tick_playback(&mut app, 11.5), Some(0.5)); assert_eq!(x(&app), 1.0, "nothing runs before the pause has passed"); - assert_eq!(tick_playback(&mut app, 12.0), Some(2.0)); + assert_eq!(tick_playback(&mut app, 12.0), Some(0.0), "the next frame comes promptly"); assert_eq!(x(&app), 3.0, "the second step runs after 2 s"); + assert_eq!(tick_playback(&mut app, 12.0), Some(2.0), "and starts the next pause"); assert!(tick_playback(&mut app, 13.9).is_some_and(|wait| (wait - 0.1).abs() < 1e-9)); assert_eq!(x(&app), 3.0); assert_eq!(tick_playback(&mut app, 14.0), None); @@ -2957,6 +2958,21 @@ mod tests { assert!(app.ui.action_playing.is_none()); } + #[test] + fn pause_for_starts_each_pause_in_the_frame_after_the_step() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 2})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), Some(2.0)); + assert!(tick_playback(&mut app, 2.0).is_some()); + assert_eq!(x(&app), 3.0, "the second step runs"); + // The next frame comes later than the pause, for example after a slow step. + assert_eq!(tick_playback(&mut app, 9.0), Some(2.0), "the pause starts in this frame"); + assert_eq!(x(&app), 3.0, "no step runs without a pause before it"); + assert_eq!(tick_playback(&mut app, 11.0), None); + assert_eq!(x(&app), 7.0, "the third step runs 2 s after the frame that started the pause"); + } + #[test] fn stop_ends_a_paced_playback_and_another_action_waits_for_it() { let (mut app, x) = app_with_three_moves(); @@ -3009,11 +3025,12 @@ mod tests { app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); assert_eq!(tick_playback(&mut app, 0.5), Some(0.5), "nothing ends before the next step is due"); app.run("document.activate", json!({"index": 0})).unwrap(); - assert_eq!(tick_playback(&mut app, 1.0), Some(1.0)); + assert_eq!(tick_playback(&mut app, 1.0), Some(0.0)); assert_eq!(x(&app), 3.0, "the document is active again when the step is due, so it runs"); app.run("document.activate", json!({"index": 1})).unwrap(); let other = app.session.active().unwrap().doc.clone(); - assert_eq!(tick_playback(&mut app, 5.0), None, "the playback ends"); + assert_eq!(tick_playback(&mut app, 5.0), Some(1.0), "the next pause starts"); + assert_eq!(tick_playback(&mut app, 6.0), None, "the playback ends"); assert!(app.ui.action_playing.is_none()); assert_eq!(app.ui.status, "the action stopped playing: its document is no longer active"); assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &other), "no step ran in the other document"); From f06b8040eb3c64bc1f1c8dc53314bc34bd9de796 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 03:24:08 -0800 Subject: [PATCH 070/482] Actions: Step by Step runs each step after the window shows the one before A Step by Step playback now waits after each step until a UI pass that the window shows has drawn it. A logic-only iteration, a pass in a minimized or covered window and a discarded pass do not count, so a hidden window no longer runs the steps unseen and does not ask for frames while it waits. --- crates/ui-egui/src/app.rs | 6 ++ crates/ui-egui/src/panels/actions.rs | 148 +++++++++++++++++++++++---- 2 files changed, 132 insertions(+), 22 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index c818001959..5e2bbcefea 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -498,6 +498,8 @@ impl VectorcraftApp { return; } crate::state::sync_zoom_stops_display_print_size(self.session.prefs.display_print_size); + // Whether this pass draws the last step of an action playing at Step by Step. + let step_held = crate::panels::actions::playback_held(self); let t0 = now_ms(); widgets::set_dialog_open(&ctx, self.ui.dialog.is_some()); // The canvas records this pass's IME caret geometry; a pass that draws no canvas has none. @@ -562,6 +564,10 @@ impl VectorcraftApp { if !ctx.will_discard() { self.perf.frame_ms = now_ms() - t0; self.issue_screenshots(&ctx); + // A hidden window's pass shows nothing, so the step waits for a pass the user sees. + if step_held && !self.viewport_hidden(&ctx) { + crate::panels::actions::playback_drawn(self); + } } let _ = json!(null); } diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 36be11e22f..80b00a87e4 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -255,7 +255,7 @@ pub enum PlaybackSpeed { /// Every included step at once. #[default] Accelerated, - /// One step per frame, so the window draws each step's result before the next step runs. + /// One step at a time, with the window drawn after each step before the next step runs. Step, /// [`PlaybackOptions::seconds`] between steps. Pause, @@ -296,8 +296,10 @@ pub struct Playing { /// With Pause For, when the next step runs (seconds on the app's clock); none until the frame /// after each step, which starts the pause before the next one. next_at: Option, - /// With Step by Step, set until the first frame after the first step: that frame draws the - /// first step's result and runs no step, since Play in the panel can run after the canvas drew. + /// With Step by Step, set after each step until the window shows a frame drawn after it + /// ([`playback_drawn`]): no step runs while it is set, so the window shows each step's result + /// before the next one runs, also when Play in the panel ran after the canvas drew and while the + /// window is minimized or covered. hold: bool, /// The [`uid`](vectorcraft_engine::DocState::uid) of the document that was active after the /// last step played, if any. @@ -309,17 +311,19 @@ fn active_doc(app: &VectorcraftApp) -> Option { } /// Runs the next step of the paced playback in progress when it is due at `now` (seconds on the -/// app's clock): with Step by Step at each call after the first, so each frame runs one step and the -/// frame after Play draws the first step; with Pause For once the pause has passed, which starts in -/// the frame after the step before, so a slow step or a late frame does not shorten it. A step that fails ends the playback and shows its error. When a step is due and the active -/// document is not the one that was active after the last step (another document was made active, -/// or that one was closed), the playback ends with a status and the rest do not run. → the seconds -/// until the window should draw again while playback goes on +/// app's clock): with Step by Step once the window has shown a frame drawn after the step before +/// ([`playback_drawn`]), so it shows each step before the next one runs; with Pause For once +/// the pause has passed, which starts in the frame after the step before, so a slow step or a late +/// frame does not shorten it. A step that fails ends the playback and shows its error. When a step +/// is due and the active document is not the one that was active after the last step (another +/// document was made active, or that one was closed), the playback ends with a status and the rest +/// do not run. → the seconds until the window should draw again while playback goes on (none while +/// Step by Step waits for a UI pass, which asks for the next frame itself) pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { let doc = active_doc(app); let playing = app.ui.action_playing.as_mut()?; - if std::mem::take(&mut playing.hold) { - return Some(0.0); + if playing.hold { + return None; } let pause = f64::from(playing.options.seconds); if playing.options.speed == PlaybackSpeed::Pause { @@ -352,9 +356,26 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { playing.doc = doc; // With Pause For, the next frame starts the next pause. playing.next_at = None; + playing.hold = playing.options.speed == PlaybackSpeed::Step; Some(0.0) } +/// Whether a Step by Step playback waits for a frame that shows its last step ([`playback_drawn`]). +pub fn playback_held(app: &VectorcraftApp) -> bool { + app.ui.action_playing.as_ref().is_some_and(|p| p.hold) +} + +/// Called after a UI pass that the window shows, when [`playback_held`] was true as the pass began: +/// the Step by Step playback runs its next step in the frame after this one, which it asks for. +pub fn playback_drawn(app: &mut VectorcraftApp) { + if let Some(playing) = app.ui.action_playing.as_mut().filter(|p| p.hold) { + playing.hold = false; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + } +} + /// The command behind Playback Options… ([`playback_options`]). pub const PLAYBACK_OPTIONS: &str = "ui.action.playbackOptions"; @@ -2862,6 +2883,25 @@ mod tests { app.session.active().unwrap().history.undo.len() } + /// One frame of a shown window at `now`: the logic pass, then a UI pass that draws → what the + /// logic pass's [`tick_playback`] returns. + fn frame(app: &mut VectorcraftApp, now: f64) -> Option { + let wait = tick_playback(app, now); + playback_drawn(app); + wait + } + + /// Draws frames until the playback in progress ends (at most 20). + fn play_out(app: &mut VectorcraftApp) { + for _ in 0..20 { + if app.ui.action_playing.is_none() { + return; + } + frame(app, 0.0); + } + panic!("the playback did not end"); + } + #[test] fn playback_options_sets_each_speed_and_refuses_bad_values() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -2926,19 +2966,83 @@ mod tests { let before = undo_steps(&app); assert_eq!(play(&mut app, 0, 0).unwrap()["pending"], json!(2)); assert_eq!(x(&app), 1.0, "the first step runs at once"); - assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the frame after Play draws the first step"); + assert_eq!(frame(&mut app, 0.0), None, "the frame after Play draws the first step"); assert_eq!(x(&app), 1.0, "and runs no step, even when Play ran after the canvas drew"); - assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the window draws again before the next step"); + assert_eq!(frame(&mut app, 0.0), Some(0.0), "the window draws again before the next step"); assert_eq!(x(&app), 3.0, "one more step in this frame"); - assert_eq!(tick_playback(&mut app, 0.0), None, "the last step ends the playback"); + assert_eq!(frame(&mut app, 0.0), None, "the last step ends the playback"); assert_eq!(x(&app), 7.0); assert!(app.ui.action_playing.is_none()); - assert_eq!(tick_playback(&mut app, 0.0), None); + assert_eq!(frame(&mut app, 0.0), None); assert_eq!(x(&app), 7.0); assert_eq!(undo_steps(&app), before + 3, "each step is its own undo step"); assert_eq!(app.session.active().unwrap().history.undo.last().unwrap().label, "Three Moves"); } + #[test] + fn step_by_step_runs_no_step_until_the_window_draws_the_one_before() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + play(&mut app, 0, 0).unwrap(); + // A hidden window runs logic passes only, which draw nothing. + for _ in 0..3 { + assert_eq!(tick_playback(&mut app, 0.0), None, "no step runs and no frame is asked for"); + } + assert_eq!(x(&app), 1.0); + playback_drawn(&mut app); + assert_eq!(tick_playback(&mut app, 0.0), Some(0.0)); + assert_eq!(x(&app), 3.0, "the step after a drawn frame runs"); + for _ in 0..3 { + assert_eq!(tick_playback(&mut app, 0.0), None); + } + assert_eq!(x(&app), 3.0, "the next step waits until the window draws this one"); + playback_drawn(&mut app); + assert_eq!(tick_playback(&mut app, 0.0), None, "the last step ends the playback"); + assert_eq!(x(&app), 7.0); + } + + #[test] + fn step_by_step_waits_while_the_window_is_hidden() { + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + let ctx = egui::Context::default(); + // One host iteration: `tick`, then a UI pass, in a shown or an occluded window. + let frame = |app: &mut VectorcraftApp, hidden: bool| { + let mut raw = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))), ..Default::default() }; + if hidden { + raw.viewports.entry(egui::ViewportId::ROOT).or_default().occluded = Some(true); + } + app.begin_host_iteration(); + let mut out = ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + // Fonts install on the first pass and are ready on the second. + frame(&mut app, false); + frame(&mut app, false); + play(&mut app, 0, 0).unwrap(); + for _ in 0..3 { + frame(&mut app, true); + } + assert_eq!(x(&app), 1.0, "no step runs while the window is hidden, even in a UI pass"); + frame(&mut app, false); + assert_eq!(x(&app), 1.0, "the shown frame draws the first step"); + frame(&mut app, true); + assert_eq!(x(&app), 3.0, "the first step was shown, so the second runs"); + for _ in 0..3 { + frame(&mut app, true); + } + assert_eq!(x(&app), 3.0, "the third step waits until the window shows the second"); + frame(&mut app, false); + assert_eq!(x(&app), 3.0, "the shown frame draws the second step"); + frame(&mut app, false); + assert_eq!(x(&app), 7.0); + assert!(app.ui.action_playing.is_none()); + } + #[test] fn pause_for_waits_the_seconds_between_steps() { let (mut app, x) = app_with_three_moves(); @@ -3004,12 +3108,12 @@ mod tests { app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); play(&mut app, 0, 0).unwrap(); app.run(START_RECORDING, json!({"set": 0})).unwrap(); - while tick_playback(&mut app, 0.0).is_some() {} + play_out(&mut app); app.run(STOP_RECORDING, json!({})).unwrap(); assert_eq!(x(&app), 21.0); assert_eq!(app.ui.action_sets[0].actions[2].steps.len(), 2); play(&mut app, 0, 2).unwrap(); - while tick_playback(&mut app, 0.0).is_some() {} + play_out(&mut app); assert_eq!(x(&app), 27.0, "paced: the recorded batches play the second and third moves"); app.run(PLAYBACK_OPTIONS, json!({"speed": "accelerated"})).unwrap(); play(&mut app, 0, 2).unwrap(); @@ -3043,8 +3147,8 @@ mod tests { app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); app.ui.status.clear(); play(&mut app, 0, 0).unwrap(); - assert_eq!(tick_playback(&mut app, 0.0), Some(0.0)); - while tick_playback(&mut app, 0.0).is_some() {} + assert_eq!(frame(&mut app, 0.0), None); + play_out(&mut app); assert_ne!(app.ui.status, "the action stopped playing: its document is no longer active"); assert_eq!(x(&app), 10.0, "the moves after the step ran in the document it made active"); } @@ -3055,11 +3159,11 @@ mod tests { app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); app.ui.action_sets[0].actions[0].steps[1] = ("no.such.command".into(), json!({})); play(&mut app, 0, 0).unwrap(); - assert_eq!(tick_playback(&mut app, 0.0), Some(0.0), "the frame after Play draws the first step"); - assert_eq!(tick_playback(&mut app, 0.0), None); + assert_eq!(frame(&mut app, 0.0), None, "the frame after Play draws the first step"); + assert_eq!(frame(&mut app, 0.0), None); assert!(app.ui.action_playing.is_none()); assert!(!app.ui.status.is_empty(), "the step's error shows"); - assert_eq!(tick_playback(&mut app, 0.0), None); + assert_eq!(frame(&mut app, 0.0), None); assert_eq!(x(&app), 1.0, "the step after the failing one does not run"); } } From e6e08af9ae754e3f814de7271cd4daaf4a2d3d2f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:01:17 -0800 Subject: [PATCH 071/482] Actions: test that closing the playing document ends a paced playback Step by Step with the only document closed, and Pause For with the playing document closed while another stays open: when the next step is due the playback ends with its status and no further step runs. --- crates/ui-egui/src/panels/actions.rs | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 80b00a87e4..209327519e 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -3153,6 +3153,44 @@ mod tests { assert_eq!(x(&app), 10.0, "the moves after the step ran in the document it made active"); } + #[test] + fn closing_the_playing_document_ends_a_paced_playback() { + let stopped = "the action stopped playing: its document is no longer active"; + // File › Close with `p`, answering Don't Save for the modified document. + let close = |app: &mut VectorcraftApp, p: Value| { + assert_eq!(app.run("file.close", p).unwrap(), json!({"pending": crate::unsaved::KIND})); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + crate::unsaved::confirm(app).unwrap(); + }; + // Step by Step, the only document closed: no document is active when the next step is due. + let (mut app, x) = app_with_three_moves(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "step"})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(x(&app), 1.0); + close(&mut app, json!({})); + assert!(app.session.active().is_none()); + assert_eq!(frame(&mut app, 0.0), None, "the frame after Play draws"); + assert_eq!(frame(&mut app, 0.0), None, "the next step is due, and the playback ends"); + assert!(app.ui.action_playing.is_none()); + assert_eq!(app.ui.status, stopped); + // Pause For, another document left active: no later step runs in it. + let (mut app, x) = app_with_three_moves(); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + let other = app.session.active().unwrap().doc.clone(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 1})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(x(&app), 1.0); + assert_eq!(tick_playback(&mut app, 0.0), Some(1.0)); + close(&mut app, json!({"index": 0})); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &other)); + assert_eq!(tick_playback(&mut app, 1.0), None, "the playback ends when the next step is due"); + assert!(app.ui.action_playing.is_none()); + assert_eq!(app.ui.status, stopped); + assert_eq!(tick_playback(&mut app, 10.0), None); + assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &other), "no step ran in the document left open"); + } + #[test] fn a_failing_step_ends_a_paced_playback_with_its_error() { let (mut app, x) = app_with_three_moves(); From 88f1e4e3378202d75912856115b193ed429dfa37 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:34:57 -0800 Subject: [PATCH 072/482] Actions: control requests run before a paced playback's next step A Stop or a document switch sent through the control channel in the frame a step comes due now takes effect before that step runs. An action played through the control channel at Pause For starts its first pause in the next frame, as the panel's Play does. --- crates/ui-egui/src/app.rs | 10 ++-- crates/ui-egui/src/panels/actions.rs | 69 +++++++++++++++++++++++++++- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5e2bbcefea..7826cdfe32 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -348,10 +348,6 @@ impl VectorcraftApp { // The timer and heartbeat run in an idle window too. ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); } - // An action playing at Step by Step or Pause For runs its next step when it is due. - if let Some(wait) = crate::panels::actions::tick_playback(self, now) { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); - } crate::keymap::note_os(ctx); shortcut_editor::sync(&self.ui); crate::panels::actions::sync_function_keys(&self.ui); @@ -374,6 +370,12 @@ impl VectorcraftApp { } self.flush_clipboard_out(ctx); self.drain_inbox(); + // An action playing at Step by Step or Pause For runs its next step when it is due, after + // the control requests and opened files above: a Stop or a document switch they bring + // comes first. + if let Some(wait) = crate::panels::actions::tick_playback(self, now) { + ctx.request_repaint_after(std::time::Duration::from_secs_f64(wait)); + } if self.viewport_hidden(ctx) && (self.needs_hidden_paint() || (!dialog_was_open && self.ui.dialog.is_some())) { // A plain repaint runs only logic in a hidden window: the ui that applies injected // input, shows a queued dialog or issues a capture needs this command. egui-winit diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 209327519e..3c9138f8d8 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -234,7 +234,8 @@ pub fn play(app: &mut VectorcraftApp, set: usize, idx: usize) -> Result 0 { let hold = options.speed == PlaybackSpeed::Step; let doc = active_doc(app); - app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None, hold, doc }); + let played_in = app.tick_iteration.filter(|&t| t == app.host_iteration); + app.ui.action_playing = Some(Playing { label: a.name, steps, options, next_at: None, hold, doc, played_in }); if let Some(ctx) = &app.ui_ctx { ctx.request_repaint(); } @@ -304,6 +305,12 @@ pub struct Playing { /// The [`uid`](vectorcraft_engine::DocState::uid) of the document that was active after the /// last step played, if any. doc: Option, + /// The host iteration in which Play ran the first step, when that iteration's [`tick`] had + /// already begun (a control request, or the UI pass after it): the pause before the second step + /// starts in a later iteration. + /// + /// [`tick`]: VectorcraftApp::tick + played_in: Option, } fn active_doc(app: &VectorcraftApp) -> Option { @@ -327,6 +334,9 @@ pub fn tick_playback(app: &mut VectorcraftApp, now: f64) -> Option { } let pause = f64::from(playing.options.seconds); if playing.options.speed == PlaybackSpeed::Pause { + if playing.next_at.is_none() && playing.played_in == Some(app.host_iteration) { + return Some(0.0); + } let due = *playing.next_at.get_or_insert(now + pause); if now < due { return Some(due - now); @@ -3093,6 +3103,63 @@ mod tests { assert_eq!(x(&app), 2.0, "an action plays again after Stop"); } + #[test] + fn control_requests_come_before_the_step_that_is_due() { + let ctx = egui::Context::default(); + // One host iteration's `tick` at `now`. + let tick = |app: &mut VectorcraftApp, now: f64| { + app.now_override = Some(now); + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + }; + // The same, with `method` and `params` queued on the control channel → its reply. + let iteration = + |app: &mut VectorcraftApp, tx: &std::sync::mpsc::Sender, now: f64, method: &str, params: Value| { + let (req, reply) = crate::control::ControlRequest::new(method, params); + tx.send(req).unwrap(); + tick(app, now); + reply.try_recv().unwrap() + }; + // Stop: the step that is due does not run. + let (app, x) = app_with_three_moves(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = app.with_control(rx); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 1})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), Some(1.0)); + let r = iteration(&mut app, &tx, 5.0, "engine.execute", json!({"command": STOP_RECORDING})); + assert_eq!(r["result"], json!({"stopped": true}), "{r}"); + assert!(app.ui.action_playing.is_none()); + assert_eq!(x(&app), 1.0, "the step that was due did not run"); + // A switch to another document: the playback ends, and the step does not run in the first one. + let (app, x) = app_with_three_moves(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = app.with_control(rx); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 1})).unwrap(); + play(&mut app, 0, 0).unwrap(); + assert_eq!(tick_playback(&mut app, 0.0), Some(1.0)); + let r = iteration(&mut app, &tx, 5.0, "engine.execute", json!({"command": "file.new", "params": {"width": 50, "height": 50}})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.ui.action_playing.is_none(), "the playback ends in the same iteration"); + assert_eq!(app.ui.status, "the action stopped playing: its document is no longer active"); + app.run("document.activate", json!({"index": 0})).unwrap(); + assert_eq!(x(&app), 1.0, "the step that was due did not run in the first document"); + // Play: the pause after the first step starts in the next iteration. + let (app, x) = app_with_three_moves(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = app.with_control(rx); + app.run(PLAYBACK_OPTIONS, json!({"speed": "pause", "seconds": 1})).unwrap(); + let r = iteration(&mut app, &tx, 0.0, "engine.execute", json!({"command": PLAY_ACTION, "params": {"action": "Three Moves"}})); + assert_eq!(r["result"]["pending"], json!(2), "{r}"); + assert_eq!(x(&app), 1.0); + tick(&mut app, 0.5); + tick(&mut app, 1.0); + assert_eq!(x(&app), 1.0, "the pause started at 0.5"); + tick(&mut app, 1.5); + assert_eq!(x(&app), 3.0); + } + #[test] fn an_action_recorded_while_another_plays_plays_its_steps() { let (mut app, x) = app_with_three_moves(); From c5d65ed8938cd321d39494bb8ad035e2e8bff451 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:45:36 -0800 Subject: [PATCH 073/482] i18n: French rows keep the no-break space before punctuation --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3eeb02dbf5..837ae7cb51 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -5588,7 +5588,7 @@ theme Appearance Apparence @msg name is empty le nom est vide @msg an action is already recording un script est déjà en cours d’enregistrement @msg an action is already playing un script est déjà en cours d’exécution -@msg the action stopped playing: its document is no longer active le script s’est arrêté : son document n’est plus le document actif +@msg the action stopped playing: its document is no longer active le script s’est arrêté : son document n’est plus le document actif @msg speed must be accelerated, step or pause speed doit valoir accelerated, step ou pause @msg seconds must be a whole number from 1 to 60 seconds doit être un nombre entier de 1 à 60 @msg no such function key touche de fonction inexistante From 9a2f1e5eb795e3b31562170a05c15a611a369726 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:23:14 -0800 Subject: [PATCH 074/482] Tests: the Render Threads restart test stays within the preference's range VECTORCRAFT_RENDER_THREADS can make default_threads() return more than 64, the largest value prefs.set accepts for renderThreads. The test now caps the value at 64, so it passes with the variable set to 100. --- crates/ui-egui/src/prefs_dialog/tests.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index cbc429b5f9..02789d35a6 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -88,7 +88,8 @@ fn reapply_restarts_the_renderer_after_a_render_threads_change() { apply_runtime(&mut app, &ctx); app.canvas.worker_started = true; // The automatic count as an explicit value: the process-wide count other tests read stays the same. - let threads = vectorcraft_render::default_threads(); + // `VECTORCRAFT_RENDER_THREADS` can give more than the 64 the preference accepts. + let threads = vectorcraft_render::default_threads().min(64); app.run("prefs.set", json!({"key": "renderThreads", "value": threads})).unwrap(); reapply(&mut app, &ctx); let restarted = !app.canvas.worker_started; From dd41552c30b8eccd0aa1ee1c6c8f43e69749088d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:32:40 -0800 Subject: [PATCH 075/482] PDF export: warn about spot stops in freeform gradients without points A freeform gradient whose field has no points of its own takes its colors from the stops, so spot-linked stops in it are written in process colors too. The export now warns in that case, as it does for the other gradients drawn as images. --- crates/engine/src/tests/linked_stops.rs | 16 ++++++++++++++++ crates/pdf/src/export/paint.rs | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/tests/linked_stops.rs b/crates/engine/src/tests/linked_stops.rs index f3c44535a5..354f072de2 100644 --- a/crates/engine/src/tests/linked_stops.rs +++ b/crates/engine/src/tests/linked_stops.rs @@ -321,3 +321,19 @@ fn spot_gradients_drawn_as_images_warn() { assert!(pdf.contains("/Subtype/Image") && !pdf.contains("/Separation"), "a process Perceptual gradient"); assert!(!spot_warning(&warnings), "{warnings:?}"); } + +#[test] +fn freeform_gradients_without_points_warn_about_spot_stops() { + let (mut s, id) = setup(); + run(&mut s, "paint.editGradient", with(ink_to_white(100.0), json!({"kind": "freeform"}))); + // A freeform field with no points of its own: the colors come from the stops, the first + // linked to the spot swatch. + let mut g = gradient(&s, id); + g.freeform = Some(vectorcraft_color::Freeform::default()); + g.gradient.stops[0].swatch = Some("Ink".into()); + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + d.node_mut(id).unwrap().appearance.set_fill(Paint::Gradient(Box::new(g))); + let (pdf, warnings) = pdf_of(&s); + assert!(pdf.contains("/Subtype/Image"), "an image"); + assert!(warnings.iter().any(|w| w.contains("spot colors in gradients exported as images")), "{warnings:?}"); +} diff --git a/crates/pdf/src/export/paint.rs b/crates/pdf/src/export/paint.rs index e8dfd4a07d..379ebbd506 100644 --- a/crates/pdf/src/export/paint.rs +++ b/crates/pdf/src/export/paint.rs @@ -431,7 +431,7 @@ impl Exporter<'_> { /// in process colors, so the spot inks have no plate of their own. fn warn_spot_image(&mut self, g: &vectorcraft_color::GradientPaint) { let doc = self.doc; - let from_stops = g.gradient.kind != GradientKind::Freeform || g.freeform.is_none(); + let from_stops = g.gradient.kind != GradientKind::Freeform || !g.has_freeform_points(); if from_stops && g.gradient.stops.iter().any(|s| s.swatch.as_deref().is_some_and(|n| doc.swatch(n).is_some_and(|w| w.spot))) { self.warn( "spot colors in gradients exported as images (freeform or dithered gradients, and Perceptual ones with RGB or Lab stops or too many stops) are written in process colors", From 336b1271dd5e9ca590edad372d2eba6e83b2d798 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:39:55 -0800 Subject: [PATCH 076/482] Type: Kerning menu checks neither method for a manual value A number typed into the Kerning field after Optical keeps the Optical flag on the type, and the manual value sets the spacing. The Kerning menu still checked Optical. It now checks neither Auto nor Optical while a manual value is set. --- crates/ui-egui/src/panels/character.rs | 6 +++--- crates/ui-egui/src/panels/character/tests.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/character.rs b/crates/ui-egui/src/panels/character.rs index 98c3be6bcd..068094eee7 100644 --- a/crates/ui-egui/src/panels/character.rs +++ b/crates/ui-egui/src/panels/character.rs @@ -317,10 +317,10 @@ fn caret_kerning(app: &VectorcraftApp, ui: &Ui) -> Option<(f64, bool)> { } /// The check marks of the Kerning menu's Auto and Optical entries for the selection's kerning -/// `mode` (Optical on, manual value). A selection that mixes modes checks neither, and the menu -/// still lists both. +/// `mode` (Optical on, manual value). A manual value checks neither, as it sets the spacing even +/// with Optical on. A selection that mixes modes checks neither, and the menu still lists both. fn kerning_methods(mode: Option<(bool, Option)>) -> (Option, Option) { - let (automatic, optical) = mode.map_or((false, false), |(optical, manual)| (!optical && manual.is_none(), optical)); + let (automatic, optical) = mode.map_or((false, false), |(optical, manual)| (!optical && manual.is_none(), optical && manual.is_none())); (Some(automatic), Some(optical)) } diff --git a/crates/ui-egui/src/panels/character/tests.rs b/crates/ui-egui/src/panels/character/tests.rs index 7cdfddad3a..4a4264fe70 100644 --- a/crates/ui-egui/src/panels/character/tests.rs +++ b/crates/ui-egui/src/panels/character/tests.rs @@ -278,6 +278,21 @@ fn kerning_menu_lists_auto_and_optical_for_mixed_modes() { assert_eq!(kerning_methods(mode), (Some(false), Some(false)), "both entries are listed, neither checked"); } +/// A number typed into the Kerning field after Optical keeps the Optical flag on the type, and +/// the manual value sets the spacing; the menu then checks neither Auto nor Optical. +#[test] +fn kerning_menu_checks_neither_method_for_a_manual_value_after_optical() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let a = app.run("text.create", json!({"x": 20, "y": 50, "text": "AV", "size": 12})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.run("text.setFormat", json!({"kerning": "optical"})).unwrap(); + app.run("text.setFormat", json!({"kerning": 50})).unwrap(); + let mode = shared(&app, |s| (s.optical_kerning, s.kerning)); + assert_eq!(mode, Some((true, Some(50.0))), "the manual value keeps the Optical flag"); + assert_eq!(kerning_methods(mode), (Some(false), Some(false)), "a manual value checks neither method"); +} + /// Highlight Kerning and Highlight Tracking show the Character panel and give its field the /// keyboard focus with the value selected: what is typed replaces it, and Enter applies it. /// Highlight Font Name opens the font family menu with its search field focused. Without From 49616e0a16942cf650e3f3e19e5207674ff75b81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:18:19 -0800 Subject: [PATCH 077/482] i18n: the package status stays English until the status bar shows it File > Package stored its status line in the interface language, so after a language switch the status bar kept the old language, and the control channel and MCP read a translated message. The status line and its notes are now English, and only the "Package created" dialog is translated when it is shown. Each catalog gets message rows for the notes, so the status bar translates them too. On the desktop, where the dialog names every font left out, a long font list is cut short in the status line so the line stays short enough to translate. --- crates/ui-egui/src/dialogs/package.rs | 63 +++++++++++++----- crates/ui-egui/src/dialogs/tests_package.rs | 72 +++++++++++++++++---- crates/ui-egui/src/i18n/bg.tsv | 6 ++ crates/ui-egui/src/i18n/bs.tsv | 6 ++ crates/ui-egui/src/i18n/ca.tsv | 6 ++ crates/ui-egui/src/i18n/cs.tsv | 6 ++ crates/ui-egui/src/i18n/da.tsv | 6 ++ crates/ui-egui/src/i18n/de.tsv | 6 ++ crates/ui-egui/src/i18n/el.tsv | 6 ++ crates/ui-egui/src/i18n/es.tsv | 6 ++ crates/ui-egui/src/i18n/fi.tsv | 6 ++ crates/ui-egui/src/i18n/fr.tsv | 6 ++ crates/ui-egui/src/i18n/hu.tsv | 6 ++ crates/ui-egui/src/i18n/id.tsv | 6 ++ crates/ui-egui/src/i18n/it.tsv | 6 ++ crates/ui-egui/src/i18n/ja.tsv | 6 ++ crates/ui-egui/src/i18n/ka.tsv | 6 ++ crates/ui-egui/src/i18n/ko.tsv | 6 ++ crates/ui-egui/src/i18n/nl.tsv | 6 ++ crates/ui-egui/src/i18n/pl.tsv | 6 ++ crates/ui-egui/src/i18n/pt-br.tsv | 6 ++ crates/ui-egui/src/i18n/ru.tsv | 6 ++ crates/ui-egui/src/i18n/sv.tsv | 6 ++ crates/ui-egui/src/i18n/tr.tsv | 6 ++ crates/ui-egui/src/i18n/uk.tsv | 6 ++ crates/ui-egui/src/i18n/vi.tsv | 6 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 6 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 6 ++ 28 files changed, 265 insertions(+), 26 deletions(-) diff --git a/crates/ui-egui/src/dialogs/package.rs b/crates/ui-egui/src/dialogs/package.rs index 2cc994be40..51cd7856de 100644 --- a/crates/ui-egui/src/dialogs/package.rs +++ b/crates/ui-egui/src/dialogs/package.rs @@ -154,17 +154,19 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later let missing = r["missingLinks"].as_array().map_or(0, Vec::len); // The fonts left out: their license doesn't allow it, or they aren't on this computer. let fonts = r["skippedFonts"].as_array().into_iter().flatten().filter_map(|f| f["font"].as_str()).collect::>().join(", "); - let shown_note = package_status_note(missing, &fonts); let n = n as u64; if web { let (name, data) = (r["name"].as_str().unwrap_or("package.zip"), r["dataBase64"].as_str().unwrap_or_default()); let bytes = vectorcraft_format::base64_decode(data).ok_or("the package came back damaged")?; io::write_named(app, None, name, &bytes)?; - app.status(package_status(n, None, &shown_note)); + // The web shows no dialog, so the status line names every font left out. + app.status(package_status(n, None, &package_status_note(missing, &fonts))); return Ok(r); } let folder = r["folder"].as_str().unwrap_or_default().to_string(); - app.status(package_status(n, Some(&folder), &shown_note)); + // The dialog names every font left out, so the status line may cut the list short. + app.status(package_status(n, Some(&folder), &package_status_note(missing, &status_fonts(&fonts)))); + let shown_note = package_dialog_note(missing, &fonts); let detail = if shown_note.is_empty() { crate::i18n::fmt( &crate::i18n::tn(n, "{n} file in {folder}. Show the package folder?", "{n} files in {folder}. Show the package folder?"), @@ -184,9 +186,10 @@ fn packaged(app: &mut VectorcraftApp, r: Result, web: bool, later /// The status bar's line for a package of `n` files written to `folder` (`None`: the web's /// download), with `note` from [`package_status_note`] when it isn't empty. With a note and a -/// folder, the note comes before the folder and the folder ends the line. Each catalog also has -/// `@msgplural` rows for the English line, shown after a language switch; the folder takes the rest -/// of the line after `) in `, so a folder name with spaces or parentheses stays whole. +/// folder, the note comes before the folder and the folder ends the line. The line is English +/// (the status bar translates it when it draws it): each catalog has `@msgplural` rows for it, and +/// the folder takes the rest of the line after `) in `, so a folder name with spaces or parentheses +/// stays whole. pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String { let (one, other) = match (folder.is_some(), note.is_empty()) { (false, true) => ("Packaged {n} file", "Packaged {n} files"), @@ -194,20 +197,50 @@ pub(super) fn package_status(n: u64, folder: Option<&str>, note: &str) -> String (true, true) => ("Packaged {n} file in {folder}", "Packaged {n} files in {folder}"), (true, false) => ("Packaged {n} file {note} in {folder}", "Packaged {n} files {note} in {folder}"), }; - crate::i18n::fmt(&crate::i18n::tn(n, one, other), &[("folder", folder.unwrap_or_default()), ("note", note)]) + crate::i18n::msg_n(n, one, other, &[("folder", folder.unwrap_or_default()), ("note", note)]) } -/// Parenthetical notes in a package status (`(2 linked files not found)` …), -/// joined with spaces and without a leading space (#3494). +/// Parenthetical notes in a package status (`(2 linked files not found)` …), in English, +/// joined with spaces and without a leading space (#3494). The catalogs' `@msg` and `@msgplural` +/// rows for each note, and for one or two notes in parentheses, translate them where the status +/// bar draws the line. pub(super) fn package_status_note(missing: usize, fonts: &str) -> String { - let mut parts = Vec::new(); - if missing > 0 { - parts.push(format!("({})", crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found"))); + let missing = (missing > 0).then(|| crate::i18n::msg_n(missing as u64, "{n} linked file not found", "{n} linked files not found", &[])); + join_notes(missing, (!fonts.is_empty()).then(|| format!("fonts not copied: {fonts}"))) +} + +/// The most bytes of font names a package status lists next to the dialog that names them all. +const STATUS_FONTS: usize = 500; + +/// `fonts` (names joined with `, `) as the desktop's status line lists them: whole, or the names +/// that fit in [`STATUS_FONTS`] bytes followed by `, …`, so the line stays short enough for the +/// status bar to translate it. +pub(super) fn status_fonts(fonts: &str) -> String { + if fonts.len() <= STATUS_FONTS { + return fonts.to_string(); } - if !fonts.is_empty() { - parts.push(format!("({})", crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))); + let mut kept = String::new(); + for name in fonts.split(", ") { + if kept.len() + name.len() + 2 > STATUS_FONTS { + break; + } + if !kept.is_empty() { + kept.push_str(", "); + } + kept.push_str(name); } - parts.join(" ") + if kept.is_empty() { "…".to_string() } else { format!("{kept}, …") } +} + +/// [`package_status_note`] in the interface language, for the dialog shown when the package is made. +pub(super) fn package_dialog_note(missing: usize, fonts: &str) -> String { + let missing = (missing > 0).then(|| crate::i18n::tn(missing as u64, "{n} linked file not found", "{n} linked files not found")); + join_notes(missing, (!fonts.is_empty()).then(|| crate::i18n::fmt(tl!("fonts not copied: {fonts}"), &[("fonts", fonts)]))) +} + +/// Each note in parentheses, joined with spaces. +fn join_notes(missing: Option, fonts: Option) -> String { + [missing, fonts].into_iter().flatten().map(|note| format!("({note})")).collect::>().join(" ") } /// `file.showPackage {folder}`: show a package folder in the file manager. diff --git a/crates/ui-egui/src/dialogs/tests_package.rs b/crates/ui-egui/src/dialogs/tests_package.rs index 816c6641d3..9aaeaa6bde 100644 --- a/crates/ui-egui/src/dialogs/tests_package.rs +++ b/crates/ui-egui/src/dialogs/tests_package.rs @@ -285,21 +285,61 @@ fn fonts_left_out_of_the_package_are_named() { assert!(app.ui.status.contains(gone), "{}", app.ui.status); } -/// The note on linked files left out of a package uses the form the language's plural rule picks -/// for the count. +/// A package made while the interface is in another language keeps its status line in English, +/// note included, so the status bar can show it in the language of the moment. The dialog shown +/// at once is in the interface language. +#[test] +fn a_package_status_is_stored_in_english() { + let dir = Folder::new("english"); + let mut app = saved(&dir); + app.run("text.create", json!({"x": 10, "y": 80, "text": "Gone", "font": "No Such Font Family"})).unwrap(); + app.run("ui.packageDialog", json!({})).unwrap(); + let out = dir.path("out"); + std::fs::create_dir_all(&out).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("folder".into(), json!(out)); + crate::i18n::set_current(crate::i18n::Lang::from_code("cs").unwrap()); + let r = confirm(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + r.unwrap(); + let status = &app.ui.status; + assert!(status.starts_with("Packaged "), "{status}"); + assert!(status.contains(&format!(" (fonts not copied: No Such Font Family Regular) in {out}")), "{status}"); + let detail = app.ui.dialog.as_ref().unwrap().str("detail"); + assert!(detail.contains("(nezkopírovaná písma: No Such Font Family Regular)"), "{detail}"); + assert!(detail.ends_with("Zobrazit složku balíčku?"), "{detail}"); +} + +/// The dialog's note on linked files left out of a package uses the form the language's plural +/// rule picks for the count. The status bar's note stays English. #[test] fn the_missing_links_note_uses_each_count_form() { let note = |code: &str, missing: usize| { crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap()); - let note = package::package_status_note(missing, ""); + let notes = (package::package_dialog_note(missing, ""), package::package_status_note(missing, "")); crate::i18n::set_current(crate::i18n::Lang::EN); - note + notes }; - assert_eq!(note("en", 1), "(1 linked file not found)"); - assert_eq!(note("en", 2), "(2 linked files not found)"); - assert_eq!(note("cs", 1), "(Nenalezen 1 propojený soubor)"); - assert_eq!(note("cs", 2), "(Nenalezeny 2 propojené soubory)"); - assert_eq!(note("cs", 5), "(Nenalezeno 5 propojených souborů)"); + assert_eq!(note("en", 1).0, "(1 linked file not found)"); + assert_eq!(note("en", 2).0, "(2 linked files not found)"); + assert_eq!(note("cs", 1).0, "(Nenalezen 1 propojený soubor)"); + assert_eq!(note("cs", 2).0, "(Nenalezeny 2 propojené soubory)"); + assert_eq!(note("cs", 5).0, "(Nenalezeno 5 propojených souborů)"); + assert_eq!(note("cs", 1).1, "(1 linked file not found)"); + assert_eq!(note("cs", 5).1, "(5 linked files not found)"); +} + +/// A long list of fonts left out is cut short in the desktop's status line, so the status bar can +/// still translate the line. The dialog names every font. +#[test] +fn a_long_list_of_fonts_left_out_is_cut_short_in_the_status() { + use crate::i18n::{Lang, message}; + let fonts = (0..200).map(|i| format!("Family {i} Regular")).collect::>().join(", "); + assert_eq!(package::status_fonts("Mono, Sans"), "Mono, Sans"); + let note = package::package_status_note(0, &package::status_fonts(&fonts)); + assert!(note.starts_with("(fonts not copied: Family 0 Regular, ") && note.ends_with(", …)"), "{note}"); + let shown = message(Lang::from_code("de").unwrap(), &package::package_status(3, Some("/out/card Folder"), ¬e)); + assert!(shown.starts_with("3 Dateien in /out/card Folder verpackt (nicht kopierte Schriften: Family 0 Regular, "), "{shown}"); + assert!(package::package_dialog_note(0, &fonts).contains("Family 199 Regular")); } /// A package status written in English, for one file or several, with or without a folder and a @@ -330,16 +370,26 @@ fn an_english_package_status_is_translated_after_a_language_switch() { // The folder stays whole in the translated line, and the note's font is still named. assert!(folder.is_none_or(|f| shown.contains(f)), "{}: {shown}", lang.code()); assert_eq!(note.contains("Mono"), shown.contains("Mono"), "{}: {shown}", lang.code()); + // The notes are translated too. + assert!(!shown.contains("linked file") && !shown.contains("not copied"), "{}: {shown}", lang.code()); } } let de = Lang::from_code("de").unwrap(); assert_eq!( message(de, &package::package_status(1, Some("/out/card (draft)"), "(fonts not copied: Mono)")), - "1 Datei in /out/card (draft) verpackt (fonts not copied: Mono)" + "1 Datei in /out/card (draft) verpackt (nicht kopierte Schriften: Mono)" ); assert_eq!( message(de, &package::package_status(3, Some("/out/card (draft)"), "(1 linked file not found) (fonts not copied: Mono)")), - "3 Dateien in /out/card (draft) verpackt (1 linked file not found) (fonts not copied: Mono)" + "3 Dateien in /out/card (draft) verpackt (1 verknüpfte Datei nicht gefunden) (nicht kopierte Schriften: Mono)" + ); + assert_eq!( + message(de, &package::package_status(3, None, "(1 linked file not found) (fonts not copied: Mono)")), + "3 Dateien verpackt (1 verknüpfte Datei nicht gefunden) (nicht kopierte Schriften: Mono)" + ); + assert_eq!( + message(de, &package::package_status(3, None, "(2 linked files not found)")), + "3 Dateien verpackt (2 verknüpfte Dateien nicht gefunden)" ); let cs = Lang::from_code("cs").unwrap(); assert_eq!(message(cs, "Packaged 1 file in /out"), "Zabalen 1 soubor do /out"); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8e6fe27116..1af49d9871 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3673,6 +3673,12 @@ digits Malayalam Малаялам Scrub Numeric Fields by Dragging Плъзгане на числени полета чрез влачене @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} файл в {folder} {note}. Показване на папката на пакета?|{n} файла в {folder} {note}. Показване на папката на пакета? @plural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени +@msgplural {n} linked file not found|{n} linked files not found {n} свързан файл не е намерен|{n} свързани файла не са намерени +@msg fonts not copied: {fonts} некопирани шрифтове: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} свързан файл не е намерен)|({n} свързани файла не са намерени) +@msg (fonts not copied: {fonts}) (некопирани шрифтове: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} некопирани шрифтове: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} свързано изображение е променено след запазването на този документ. Показване на новата версия?|{n} свързани изображения са променени след запазването на този документ. Показване на новите версии? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} свързано изображение е променено на диска. Показване на новата версия?|{n} свързани изображения са променени на диска. Показване на новите версии? diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index ee46902140..e87f4ad18c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2491,6 +2491,12 @@ digits Malayalam Malajalam Save the document first? Prvo sačuvati dokument? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa?|Datoteka u {folder}: {n} {note}. Prikazati folder paketa? @plural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} +@msgplural {n} linked file not found|{n} linked files not found Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n}|Povezanih datoteka nije pronađeno: {n} +@msg fonts not copied: {fonts} fontovi nisu kopirani: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Povezanih datoteka nije pronađeno: {n})|(Povezanih datoteka nije pronađeno: {n})|(Povezanih datoteka nije pronađeno: {n}) +@msg (fonts not copied: {fonts}) (fontovi nisu kopirani: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} fontovi nisu kopirani: {fonts} Built-in presets are read-only: New… starts an editable copy. Ugrađeni predlošci su samo za čitanje: Novo… započinje kopiju koja se može uređivati. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na radnoj ploči predstavlja {real} {unit} u sceni. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 4ecb3fb3b4..a6accb7bfd 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4742,6 +4742,12 @@ digits Malayalam Malaiàlam @plural {n} folder or file couldn't be read|{n} folders or files couldn't be read No s’ha pogut llegir {n} carpeta o fitxer|No s’han pogut llegir {n} carpetes o fitxers @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones S’ha omès {n} carpeta, com ara les d’altres aplicacions, les del sistema i les ocultes|S’han omès {n} carpetes, com ara les d’altres aplicacions, les del sistema i les ocultes @plural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@msgplural {n} linked file not found|{n} linked files not found No s’ha trobat {n} fitxer enllaçat|No s’han trobat {n} fitxers enllaçats +@msg fonts not copied: {fonts} tipus de lletra no copiats: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (No s’ha trobat {n} fitxer enllaçat)|(No s’han trobat {n} fitxers enllaçats) +@msg (fonts not copied: {fonts}) (tipus de lletra no copiats: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imatge enllaçada ha canviat al disc. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat al disc. Voleu mostrar les versions noves? @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imatge enllaçada ha canviat des que es va desar aquest document. Voleu mostrar la versió nova?|{n} imatges enllaçades han canviat des que es va desar aquest document. Voleu mostrar les versions noves? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regla més: l’exportació l’escriu.|{n} regles més: l’exportació les escriu totes. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0b568e67d4..3f4cefc214 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2522,6 +2522,12 @@ digits Malayalam Malajálamské @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} soubor v {folder} {note}. Zobrazit složku balíčku?|{n} soubory v {folder} {note}. Zobrazit složku balíčku?|{n} souborů v {folder} {note}. Zobrazit složku balíčku? @plural {n} linked file not found|{n} linked files not found Nenalezen {n} propojený soubor|Nenalezeny {n} propojené soubory|Nenalezeno {n} propojených souborů fonts not copied: {fonts} nezkopírovaná písma: {fonts} +@msgplural {n} linked file not found|{n} linked files not found Nenalezen {n} propojený soubor|Nenalezeny {n} propojené soubory|Nenalezeno {n} propojených souborů +@msg fonts not copied: {fonts} nezkopírovaná písma: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Nenalezen {n} propojený soubor)|(Nenalezeny {n} propojené soubory)|(Nenalezeno {n} propojených souborů) +@msg (fonts not copied: {fonts}) (nezkopírovaná písma: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} Built-in presets are read-only: New… starts an editable copy. Vestavěná přednastavení jsou jen pro čtení: Nový… vytvoří kopii, kterou lze upravit. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na pracovní ploše odpovídá {real} {unit} ve scéně. Grid Color & Opacity Barva a krytí mřížky diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index abf41f3fc5..b9d6c9806f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -2309,6 +2309,12 @@ digits Malayalam Malayalam Save the document first? Gem dokumentet først? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Vis pakkemappen?|{n} filer i {folder} {note}. Vis pakkemappen? @plural {n} linked file not found|{n} linked files not found {n} linket fil ikke fundet|{n} linkede filer ikke fundet +@msgplural {n} linked file not found|{n} linked files not found {n} linket fil ikke fundet|{n} linkede filer ikke fundet +@msg fonts not copied: {fonts} skrifttyper ikke kopieret: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} linket fil ikke fundet)|({n} linkede filer ikke fundet) +@msg (fonts not copied: {fonts}) (skrifttyper ikke kopieret: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} skrifttyper ikke kopieret: {fonts} Built-in presets are read-only: New… starts an editable copy. Indbyggede forudindstillinger er skrivebeskyttede: Ny… starter en redigerbar kopi. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} på tegnebrættet svarer til {real} {unit} i scenen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9b9d7c8393..a850882aff 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3667,6 +3667,12 @@ effect Points Punkte @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} Datei in {folder} {note}. Paketordner anzeigen?|{n} Dateien in {folder} {note}. Paketordner anzeigen? @plural {n} linked file not found|{n} linked files not found {n} verknüpfte Datei nicht gefunden|{n} verknüpfte Dateien nicht gefunden fonts not copied: {fonts} nicht kopierte Schriften: {fonts} +@msgplural {n} linked file not found|{n} linked files not found {n} verknüpfte Datei nicht gefunden|{n} verknüpfte Dateien nicht gefunden +@msg fonts not copied: {fonts} nicht kopierte Schriften: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} verknüpfte Datei nicht gefunden)|({n} verknüpfte Dateien nicht gefunden) +@msg (fonts not copied: {fonts}) (nicht kopierte Schriften: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} verknüpftes Bild wurde seit dem Speichern dieses Dokuments geändert. Die neue Version anzeigen?|{n} verknüpfte Bilder wurden seit dem Speichern dieses Dokuments geändert. Die neuen Versionen anzeigen? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} weitere Regel: Der Export schreibt sie.|{n} weitere Regeln: Der Export schreibt alle. @plural {n} unnamed object left out: name it, or turn on Unnamed Objects in the panel menu.|{n} unnamed objects left out: name them, or turn on Unnamed Objects in the panel menu. {n} unbenanntes Objekt ausgelassen: Benennen Sie es oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü.|{n} unbenannte Objekte ausgelassen: Benennen Sie sie oder aktivieren Sie „Unbenannte Objekte“ im Bedienfeldmenü. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index d909fe3ed6..2510a2a978 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3994,6 +3994,12 @@ digits Malayalam Μαλαγιάλαμ Scrub Numeric Fields by Dragging Ρύθμιση αριθμητικών πεδίων με σύρσιμο @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} αρχείο στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας;|{n} αρχεία στον φάκελο {folder} {note}. Να εμφανιστεί ο φάκελος συσκευασίας; @plural {n} linked file not found|{n} linked files not found Δεν βρέθηκε {n} συνδεδεμένο αρχείο|Δεν βρέθηκαν {n} συνδεδεμένα αρχεία +@msgplural {n} linked file not found|{n} linked files not found Δεν βρέθηκε {n} συνδεδεμένο αρχείο|Δεν βρέθηκαν {n} συνδεδεμένα αρχεία +@msg fonts not copied: {fonts} γραμματοσειρές που δεν αντιγράφηκαν: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Δεν βρέθηκε {n} συνδεδεμένο αρχείο)|(Δεν βρέθηκαν {n} συνδεδεμένα αρχεία) +@msg (fonts not copied: {fonts}) (γραμματοσειρές που δεν αντιγράφηκαν: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} γραμματοσειρές που δεν αντιγράφηκαν: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} συνδεδεμένη εικόνα άλλαξε μετά την αποθήκευση του εγγράφου. Να εμφανιστεί η νέα έκδοση;|{n} συνδεδεμένες εικόνες άλλαξαν μετά την αποθήκευση του εγγράφου. Να εμφανιστούν οι νέες εκδόσεις; @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} συνδεδεμένη εικόνα άλλαξε στον δίσκο. Να εμφανιστεί η νέα έκδοση;|{n} συνδεδεμένες εικόνες άλλαξαν στον δίσκο. Να εμφανιστούν οι νέες εκδόσεις; diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 2b85aefddc..2d37d779c0 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3756,6 +3756,12 @@ digits Malayalam Malayálam Scrub Numeric Fields by Dragging Ajustar campos numéricos arrastrando @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} archivo en {folder} {note}. ¿Mostrar la carpeta del paquete?|{n} archivos en {folder} {note}. ¿Mostrar la carpeta del paquete? @plural {n} linked file not found|{n} linked files not found No se encontró {n} archivo vinculado|No se encontraron {n} archivos vinculados +@msgplural {n} linked file not found|{n} linked files not found No se encontró {n} archivo vinculado|No se encontraron {n} archivos vinculados +@msg fonts not copied: {fonts} fuentes no copiadas: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (No se encontró {n} archivo vinculado)|(No se encontraron {n} archivos vinculados) +@msg (fonts not copied: {fonts}) (fuentes no copiadas: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} fuentes no copiadas: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imagen vinculada cambió desde que se guardó este documento. ¿Mostrar la versión nueva?|{n} imágenes vinculadas cambiaron desde que se guardó este documento. ¿Mostrar las versiones nuevas? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} imagen vinculada cambió en el disco. ¿Mostrar la versión nueva?|{n} imágenes vinculadas cambiaron en el disco. ¿Mostrar las versiones nuevas? diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f110474e40..9e856f29f7 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2465,6 +2465,12 @@ digits Malayalam Malajalam Save the document first? Tallennetaanko asiakirja ensin? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} tiedosto kansiossa {folder} {note}. Näytetäänkö pakettikansio?|{n} tiedostoa kansiossa {folder} {note}. Näytetäänkö pakettikansio? @plural {n} linked file not found|{n} linked files not found {n} linkitettyä tiedostoa ei löytynyt|{n} linkitettyä tiedostoa ei löytynyt +@msgplural {n} linked file not found|{n} linked files not found {n} linkitettyä tiedostoa ei löytynyt|{n} linkitettyä tiedostoa ei löytynyt +@msg fonts not copied: {fonts} fontteja ei kopioitu: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} linkitettyä tiedostoa ei löytynyt)|({n} linkitettyä tiedostoa ei löytynyt) +@msg (fonts not copied: {fonts}) (fontteja ei kopioitu: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} fontteja ei kopioitu: {fonts} Built-in presets are read-only: New… starts an editable copy. Sisäiset esiasetukset ovat vain luku -tilassa: Uusi… luo muokattavan kopion. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} piirtoalustalla vastaa {real} {unit} näkymässä. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 837ae7cb51..88cbbfb05d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3748,6 +3748,12 @@ digits Malayalam Malayalam Scrub Numeric Fields by Dragging Modifier les champs numériques en faisant glisser @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fichier dans {folder} {note}. Afficher le dossier de l’assemblage ?|{n} fichiers dans {folder} {note}. Afficher le dossier de l’assemblage ? @plural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables +@msgplural {n} linked file not found|{n} linked files not found {n} fichier lié introuvable|{n} fichiers liés introuvables +@msg fonts not copied: {fonts} polices non copiées : {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} fichier lié introuvable)|({n} fichiers liés introuvables) +@msg (fonts not copied: {fonts}) (polices non copiées : {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} polices non copiées : {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} image liée modifiée depuis l’enregistrement de ce document. Afficher la nouvelle version ?|{n} images liées modifiées depuis l’enregistrement de ce document. Afficher les nouvelles versions ? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} image liée modifiée sur le disque. Afficher la nouvelle version ?|{n} images liées modifiées sur le disque. Afficher les nouvelles versions ? diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0ff5d8cd89..b6a95e05fe 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4487,6 +4487,12 @@ mark-style Japanese Japán @plural {n} folder or file couldn't be read|{n} folders or files couldn't be read Nem olvasható mappák vagy fájlok: {n} @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Kihagyott mappák: {n} (például más alkalmazások, a rendszer és a rejtett mappák) @plural {n} linked file not found|{n} linked files not found Nem található csatolt fájlok: {n} +@msgplural {n} linked file not found|{n} linked files not found Nem található csatolt fájlok: {n} +@msg fonts not copied: {fonts} nem másolt betűtípusok: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Nem található csatolt fájlok: {n}) +@msg (fonts not copied: {fonts}) (nem másolt betűtípusok: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? A lemezen módosult csatolt képek: {n}. Megjelenítsük az új változatokat? @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? A dokumentum mentése óta módosult csatolt képek: {n}. Megjelenítsük az új változatokat? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. További szabályok: {n}. Az exportálás mindet kiírja. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index d0194dcc7d..5e6fab9817 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2309,6 +2309,12 @@ digits Malayalam Malayalam Save the document first? Simpan dokumen terlebih dahulu? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file dalam {folder} {note}. Tampilkan folder paket? @plural {n} linked file not found|{n} linked files not found {n} file tertaut tidak ditemukan +@msgplural {n} linked file not found|{n} linked files not found {n} file tertaut tidak ditemukan +@msg fonts not copied: {fonts} font tidak disalin: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} file tertaut tidak ditemukan) +@msg (fonts not copied: {fonts}) (font tidak disalin: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} font tidak disalin: {fonts} Built-in presets are read-only: New… starts an editable copy. Preset bawaan bersifat hanya-baca: Baru… memulai salinan yang dapat diedit. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} pada artboard mewakili {real} {unit} dalam scene. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 2bbdc4bfa9..c7885a3318 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3793,6 +3793,12 @@ digits Malayalam Malayalam Scrub Numeric Fields by Dragging Regola i campi numerici trascinando @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto?|{n} file in {folder} {note}. Vuoi mostrare la cartella del pacchetto? @plural {n} linked file not found|{n} linked files not found File collegati non trovati: {n}|File collegati non trovati: {n} +@msgplural {n} linked file not found|{n} linked files not found File collegati non trovati: {n}|File collegati non trovati: {n} +@msg fonts not copied: {fonts} font non copiati: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (File collegati non trovati: {n})|(File collegati non trovati: {n}) +@msg (fonts not copied: {fonts}) (font non copiati: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} font non copiati: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? Immagini collegate modificate dopo il salvataggio di questo documento: {n}. Vuoi mostrare le nuove versioni?|Immagini collegate modificate dopo il salvataggio di questo documento: {n}. Vuoi mostrare le nuove versioni? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? Immagini collegate modificate su disco: {n}. Vuoi mostrare le nuove versioni?|Immagini collegate modificate su disco: {n}. Vuoi mostrare le nuove versioni? diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index b8d45181f0..586a6c2734 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3388,6 +3388,12 @@ mark-style Japanese 日本式 to → @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} に {n} 個のファイル{note}。パッケージフォルダーを表示しますか? @plural {n} linked file not found|{n} linked files not found リンクファイルが {n} 個見つかりません +@msgplural {n} linked file not found|{n} linked files not found リンクファイルが {n} 個見つかりません +@msg fonts not copied: {fonts} コピーされなかったフォント:{fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (リンクファイルが {n} 個見つかりません) +@msg (fonts not copied: {fonts}) (コピーされなかったフォント:{fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} コピーされなかったフォント:{fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 保存後に {n} 個のリンク画像が変更されています。新しいバージョンを表示しますか? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} 個のリンク画像がディスク上で変更されました。新しいバージョンを表示しますか? diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index dac1278fcc..6067c70c2a 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2211,6 +2211,12 @@ digits Malayalam მალაიალამური Save the document first? ჯერ შევინახოთ დოკუმენტი? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? ფაილები: {n}, ადგილი: {folder} {note}. ვაჩვენოთ შეფუთვის საქაღალდე? @plural {n} linked file not found|{n} linked files not found ვერ მოიძებნა დაკავშირებული ფაილები: {n} +@msgplural {n} linked file not found|{n} linked files not found ვერ მოიძებნა დაკავშირებული ფაილები: {n} +@msg fonts not copied: {fonts} არ დაკოპირდა შრიფტები: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (ვერ მოიძებნა დაკავშირებული ფაილები: {n}) +@msg (fonts not copied: {fonts}) (არ დაკოპირდა შრიფტები: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} არ დაკოპირდა შრიფტები: {fonts} Built-in presets are read-only: New… starts an editable copy. ჩაშენებული პრესეტები მხოლოდ წასაკითხია: „ახალი…“ ქმნის რედაქტირებად ასლს. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} სამუშაო დაფაზე სცენაში {real} {unit}-ს შეესაბამება. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 76c60eda46..8ac96cd972 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3377,6 +3377,12 @@ mark-style Japanese 일본식 to ~ @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder}에 파일 {n}개 {note}. 패키지 폴더를 표시하시겠습니까? @plural {n} linked file not found|{n} linked files not found 연결된 파일 {n}개를 찾을 수 없습니다 +@msgplural {n} linked file not found|{n} linked files not found 연결된 파일 {n}개를 찾을 수 없습니다 +@msg fonts not copied: {fonts} 복사되지 않은 글꼴: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (연결된 파일 {n}개를 찾을 수 없습니다) +@msg (fonts not copied: {fonts}) (복사되지 않은 글꼴: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} 복사되지 않은 글꼴: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 이 문서를 저장한 이후 연결된 이미지 {n}개가 변경되었습니다. 새 버전을 표시하시겠습니까? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 연결된 이미지 {n}개가 디스크에서 변경되었습니다. 새 버전을 표시하시겠습니까? diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d3e7864974..e8035f8f1f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2323,6 +2323,12 @@ digits Malayalam Malayalam Save the document first? Wil je het document eerst opslaan? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} bestand in {folder} {note}. De pakketmap openen?|{n} bestanden in {folder} {note}. De pakketmap openen? @plural {n} linked file not found|{n} linked files not found {n} gekoppeld bestand niet gevonden|{n} gekoppelde bestanden niet gevonden +@msgplural {n} linked file not found|{n} linked files not found {n} gekoppeld bestand niet gevonden|{n} gekoppelde bestanden niet gevonden +@msg fonts not copied: {fonts} niet gekopieerde lettertypen: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} gekoppeld bestand niet gevonden)|({n} gekoppelde bestanden niet gevonden) +@msg (fonts not copied: {fonts}) (niet gekopieerde lettertypen: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} niet gekopieerde lettertypen: {fonts} Built-in presets are read-only: New… starts an editable copy. Ingebouwde voorinstellingen zijn alleen-lezen: Nieuw… start een bewerkbare kopie. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} op het tekenbord staat voor {real} {unit} in de scène. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index db43a45cd4..330f317449 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2435,6 +2435,12 @@ digits Malayalam Malajalam Save the document first? Najpierw zapisać dokument? @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Pliki: {n} w {folder} {note}. Pokazać folder pakietu?|Pliki: {n} w {folder} {note}. Pokazać folder pakietu?|Pliki: {n} w {folder} {note}. Pokazać folder pakietu? @plural {n} linked file not found|{n} linked files not found Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n} +@msgplural {n} linked file not found|{n} linked files not found Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n}|Nie znaleziono połączonych plików: {n} +@msg fonts not copied: {fonts} nieskopiowane czcionki: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Nie znaleziono połączonych plików: {n})|(Nie znaleziono połączonych plików: {n})|(Nie znaleziono połączonych plików: {n}) +@msg (fonts not copied: {fonts}) (nieskopiowane czcionki: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} nieskopiowane czcionki: {fonts} Built-in presets are read-only: New… starts an editable copy. Wbudowane ustawienia są tylko do odczytu: Nowe… tworzy edytowalną kopię. 1 {unit} on the artboard stands for {real} {unit} in the scene. 1 {unit} na obszarze kompozycji odpowiada {real} {unit} w scenie. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0ddff27775..cb3af6490c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3097,6 +3097,12 @@ digits Malayalam Malaiala to para @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} arquivo em {folder} {note}. Mostrar a pasta do pacote?|{n} arquivos em {folder} {note}. Mostrar a pasta do pacote? @plural {n} linked file not found|{n} linked files not found {n} arquivo vinculado não encontrado|{n} arquivos vinculados não encontrados +@msgplural {n} linked file not found|{n} linked files not found {n} arquivo vinculado não encontrado|{n} arquivos vinculados não encontrados +@msg fonts not copied: {fonts} fontes não copiadas: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} arquivo vinculado não encontrado)|({n} arquivos vinculados não encontrados) +@msg (fonts not copied: {fonts}) (fontes não copiadas: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} fontes não copiadas: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} imagem vinculada alterada desde que este documento foi salvo. Mostrar a nova versão?|{n} imagens vinculadas alteradas desde que este documento foi salvo. Mostrar as novas versões? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. {n} regra a mais: a Exportação a escreve.|{n} regras a mais: a Exportação escreve cada uma. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 077f033acd..c2e9f88ef0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3788,6 +3788,12 @@ digits Malayalam Малаялам Scrub Numeric Fields by Dragging Изменять числовые поля перетаскиванием @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета?|Файлов: {n} в {folder} {note}. Показать папку пакета? @plural {n} linked file not found|{n} linked files not found Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n} +@msgplural {n} linked file not found|{n} linked files not found Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n}|Не найдено связанных файлов: {n} +@msg fonts not copied: {fonts} шрифты не скопированы: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Не найдено связанных файлов: {n})|(Не найдено связанных файлов: {n})|(Не найдено связанных файлов: {n}) +@msg (fonts not copied: {fonts}) (шрифты не скопированы: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} шрифты не скопированы: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} связанное изображение изменилось с момента сохранения этого документа. Показать новую версию?|{n} связанных изображения изменились с момента сохранения этого документа. Показать новые версии?|{n} связанных изображений изменились с момента сохранения этого документа. Показать новые версии? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} связанное изображение изменилось на диске. Показать новую версию?|{n} связанных изображения изменились на диске. Показать новые версии?|{n} связанных изображений изменились на диске. Показать новые версии? diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4789dcbedc..0c1a4403a5 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3678,6 +3678,12 @@ digits Malayalam Malayalam Scrub Numeric Fields by Dragging Ändra numeriska fält genom att dra @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {n} fil i {folder} {note}. Visa paketmappen?|{n} filer i {folder} {note}. Visa paketmappen? @plural {n} linked file not found|{n} linked files not found {n} länkad fil hittades inte|{n} länkade filer hittades inte +@msgplural {n} linked file not found|{n} linked files not found {n} länkad fil hittades inte|{n} länkade filer hittades inte +@msg fonts not copied: {fonts} typsnitt som inte kopierats: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} länkad fil hittades inte)|({n} länkade filer hittades inte) +@msg (fonts not copied: {fonts}) (typsnitt som inte kopierats: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} typsnitt som inte kopierats: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} länkad bild har ändrats sedan dokumentet sparades. Visa den nya versionen?|{n} länkade bilder har ändrats sedan dokumentet sparades. Visa de nya versionerna? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} länkad bild har ändrats på disken. Visa den nya versionen?|{n} länkade bilder har ändrats på disken. Visa de nya versionerna? diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index c89c627673..2332baf167 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3566,6 +3566,12 @@ digits Malayalam Malayalam Scrub Numeric Fields by Dragging Sayısal Alanları Sürükleyerek Fırçalayın @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} içinde {n} dosya {note}. Paket klasörü gösterilsin mi? @plural {n} linked file not found|{n} linked files not found {n} bağlantılı dosya bulunamadı +@msgplural {n} linked file not found|{n} linked files not found {n} bağlantılı dosya bulunamadı +@msg fonts not copied: {fonts} kopyalanmayan yazı tipleri: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) ({n} bağlantılı dosya bulunamadı) +@msg (fonts not copied: {fonts}) (kopyalanmayan yazı tipleri: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} kopyalanmayan yazı tipleri: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} bağlantılı görsel bu belgenin kaydedilmesinden bu yana değiştirildi. Yeni sürümler gösterilsin mi? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} bağlantılı görsel diskte değiştirildi. Yeni sürümler gösterilsin mi? diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 5cc74b986c..6816dbecd4 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3786,6 +3786,12 @@ effect Points Точки Scrub Numeric Fields by Dragging Змінювати числові поля перетягуванням @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета?|файлів: {n} {folder} {note}. Показати папку пакета? @plural {n} linked file not found|{n} linked files not found не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n} +@msgplural {n} linked file not found|{n} linked files not found не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n}|не знайдено пов’язаних файлів: {n} +@msg fonts not copied: {fonts} шрифти не скопійовано: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (не знайдено пов’язаних файлів: {n})|(не знайдено пов’язаних файлів: {n})|(не знайдено пов’язаних файлів: {n}) +@msg (fonts not copied: {fonts}) (шрифти не скопійовано: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} шрифти не скопійовано: {fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії?|пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії?|пов’язані зображення ({n}) змінилися з моменту збереження цього документа. Показати нові версії? @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? пов’язані зображення ({n}) змінилися на диску. Показати нові версії?|пов’язані зображення ({n}) змінилися на диску. Показати нові версії?|пов’язані зображення ({n}) змінилися на диску. Показати нові версії? diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d23c1250de..86db175fc9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4150,6 +4150,12 @@ mark-style Japanese Kiểu Nhật @plural {n} folder or file couldn't be read|{n} folders or files couldn't be read {n} thư mục hoặc tệp không thể đọc được @plural {n} folder skipped, such as another app's or the system's folder or a hidden one|{n} folders skipped, such as other apps' and the system's folders and hidden ones Đã bỏ qua {n} thư mục, chẳng hạn thư mục của ứng dụng khác, thư mục hệ thống và thư mục ẩn @plural {n} linked file not found|{n} linked files not found Không tìm thấy {n} tệp liên kết +@msgplural {n} linked file not found|{n} linked files not found Không tìm thấy {n} tệp liên kết +@msg fonts not copied: {fonts} phông chữ chưa được sao chép: {fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (Không tìm thấy {n} tệp liên kết) +@msg (fonts not copied: {fonts}) (phông chữ chưa được sao chép: {fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} @plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? {n} ảnh liên kết đã thay đổi trên đĩa. Hiện phiên bản mới? @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? {n} ảnh liên kết đã thay đổi kể từ khi lưu tài liệu. Hiện phiên bản mới? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. Còn {n} quy tắc nữa: Xuất sẽ ghi tất cả. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 42ac3614f8..bea443d8ef 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3637,6 +3637,12 @@ digits Malayalam 马拉雅拉姆数字 Scrub Numeric Fields by Dragging 拖动以调整数值字段 @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 个文件{note}。要显示打包文件夹吗? @plural {n} linked file not found|{n} linked files not found 找不到 {n} 个链接文件 +@msgplural {n} linked file not found|{n} linked files not found 找不到 {n} 个链接文件 +@msg fonts not copied: {fonts} 未复制的字体:{fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (找不到 {n} 个链接文件) +@msg (fonts not copied: {fonts}) (未复制的字体:{fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} 未复制的字体:{fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 自存储此文档后,有 {n} 个链接图像已更改。要显示新版本吗? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 另有 {n} 条规则:导出时会全部写出。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index ede034f66f..a61287b96d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4665,6 +4665,12 @@ digits Malayalam 馬來亞拉姆數字 Scrub Numeric Fields by Dragging 拖曳以調整數值欄位 @plural {n} file in {folder} {note}. Show the package folder?|{n} files in {folder} {note}. Show the package folder? {folder} 中有 {n} 個檔案{note}。要顯示封裝資料夾嗎? @plural {n} linked file not found|{n} linked files not found 找不到 {n} 個連結檔案 +@msgplural {n} linked file not found|{n} linked files not found 找不到 {n} 個連結檔案 +@msg fonts not copied: {fonts} 未複製的字體:{fonts} +@msgplural ({n} linked file not found)|({n} linked files not found) (找不到 {n} 個連結檔案) +@msg (fonts not copied: {fonts}) (未複製的字體:{fonts}) +@msg ({note}) ({more}) ({note}) ({more}) +@msg {note}) ({more} {note}) ({more} fonts not copied: {fonts} 未複製的字體:{fonts} @plural {n} linked image changed since this document was saved. Show the new version?|{n} linked images changed since this document was saved. Show the new versions? 自儲存此文件後,有 {n} 個連結影像已變更。要顯示新版本嗎? @plural {n} more rule: Export writes it.|{n} more rules: Export writes every one. 另有 {n} 條規則:匯出時會全部寫出。 From db6a0d786e994cec8c24258e6795728788e01d43 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:42:19 -0800 Subject: [PATCH 078/482] Shortcuts: an Escape that cancels a Tools or ruler move runs no Escape command A command bound to plain Escape no longer runs when that Escape cancels a floating Tools panel move or a ruler-origin drag, nor on the key repeats while Escape stays held. The next separate Escape press runs it as before. A test binds Select None to Escape and holds Escape through both cancels. --- crates/ui-egui/src/shortcuts.rs | 4 +++- crates/ui-egui/src/tests/screenmode.rs | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index f8aaf2dd2f..c2e5497404 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -350,10 +350,12 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context) { let row_key = |chord: &craft_keymap::Chord| { rows_keys && chord.is_plain() && !chord.mods.shift && matches!(chord.key, craft_keymap::Key::Delete | craft_keymap::Key::Backspace) }; + // An Escape that ended a ruler-origin drag or floating Tools move runs no command bound to it. + let gesture_escape = |chord: &craft_keymap::Chord| escape_ended_gesture && chord.is_plain() && chord.key == craft_keymap::Key::Escape; let hits = dispatch(app, ctx, |hit| { let chord = &hit.trigger.chord; let shifted_punctuation = chord.mods.shift && chord.key.name().chars().all(|c| !c.is_alphanumeric()); - !(chord.is_plain() && types_text(chord.key) && !shifted_punctuation || row_key(chord)) + !(chord.is_plain() && types_text(chord.key) && !shifted_punctuation || row_key(chord) || gesture_escape(chord)) }); let ran = !hits.is_empty(); for c in hits { diff --git a/crates/ui-egui/src/tests/screenmode.rs b/crates/ui-egui/src/tests/screenmode.rs index 2e35006300..3dffb4aa83 100644 --- a/crates/ui-egui/src/tests/screenmode.rs +++ b/crates/ui-egui/src/tests/screenmode.rs @@ -465,6 +465,29 @@ fn held_escape_that_cancels_ruler_origin_drag_keeps_the_tool() { } } +#[test] +fn held_escape_that_cancels_a_move_skips_a_command_bound_to_escape() { + for ruler in [false, true] { + let ctx = egui::Context::default(); + let mut app = in_screen_mode(&ctx, 0); + app.run("shortcuts.set", json!({"id": "select.none", "shortcut": "Escape", "force": true})).unwrap(); + let selected = app.session.active().unwrap().selection.objects.clone(); + assert!(!selected.is_empty()); + let to = if ruler { begin_ruler_origin_drag(&mut app, &ctx) } else { begin_tools_move(&mut app, &ctx).1 }; + frame(&mut app, &ctx, escape_event(true, false)); + assert_eq!(app.session.active().unwrap().selection.objects, selected, "the cancelling Escape runs no command (ruler: {ruler})"); + for _ in 0..3 { + frame(&mut app, &ctx, escape_event(true, true)); + } + release_drag(&mut app, &ctx, to); + frame(&mut app, &ctx, escape_event(true, true)); + assert_eq!(app.session.active().unwrap().selection.objects, selected, "held Escape runs no command (ruler: {ruler})"); + frame(&mut app, &ctx, escape_event(false, false)); + frame(&mut app, &ctx, escape()); + assert!(app.session.active().unwrap().selection.objects.is_empty(), "the next Escape runs the command (ruler: {ruler})"); + } +} + #[test] fn a_popup_takes_escape_before_full_screen_exits() { let ctx = egui::Context::default(); From 88aeee8f8ec2cdcf97e9a9d30c285237159b5769 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:32:17 -0800 Subject: [PATCH 079/482] Shape Builder Tool Options: a highlight color with an alpha part is refused OK in Shape Builder Tool Options sent highlightColor to tool.setOption, which keeps only #rrggbb, so #ff000080 was applied as #ff0000 with no error. OK now gives the same error as the Live Paint tool options for a hex color with an alpha part (#rrggbbaa or #rgba), the dialog stays open and the tool's options do not change. The tool.options params text, docs/mcp.md and the progress doc say so. --- .../src/dialogs/shape_builder_options.rs | 26 +++++++++++++++++-- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 3 ++- docs/target-app-parity.md | 1 + 4 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 2262c94297..9393e0707e 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -13,7 +13,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; -use super::tile_edge_color::resolve; +use super::tile_edge_color::{checked, resolve}; use super::{DialogSpec, form, run_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -118,8 +118,11 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// OK: set the Shape Builder's options. +/// OK: set the Shape Builder's options, or an error for a `highlightColor` that is not a color. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.contains_key("highlightColor") { + checked(&d.str("highlightColor"))?; + } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) } @@ -251,6 +254,25 @@ mod tests { assert_eq!(bounds, vec![[100.0, 100.0, 300.0, 100.0], [100.0, 100.0, 300.0, 200.0]]); } + /// A highlight color with an alpha part is refused and leaves the tool's options as they were; + /// `#rrggbb` still sets them. + #[test] + fn a_highlight_color_with_an_alpha_part_is_refused() { + let mut app = app(); + app.run("tool.options", json!({"tool": "shapeBuilder"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("highlightColor".into(), json!("#ff000080")); + d.fields.insert("highlightFill".into(), json!(false)); + let err = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(err, "`#ff000080` is not a colour (#rrggbb or a preset name)"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + let o = app.session.tool_options_of("shapeBuilder"); + assert_eq!((o["highlightColor"].as_str(), o["highlightFill"].as_bool()), (Some("#ff4f4f"), Some(true)), "nothing changes"); + app.ui.dialog.as_mut().unwrap().fields.insert("highlightColor".into(), json!("#00ff00")); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("shapeBuilder")["highlightColor"], json!("#00ff00")); + } + #[test] fn a_straight_line_drag_merges_only_the_regions_the_line_crosses() { // A wide rectangle and a tall one over the middle of its top edge: three regions, the wide diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 14322a3f37..a3bda35231 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}), 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 (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)", ), ( "ui.colorGuideOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 7076ce5ed5..5bb5a0c29d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5919,7 +5919,8 @@ pointer show the current fill and the swatches before and after it), `selection` `straightLine`: a drag touches what the line from its first point to the pointer crosses), `highlightFill` (on by default; when it is off, merge mode shades no regions), `gapDetection` (off) with `gapLength` (pt, 0 to 72; 3), `clickStrokeSplitsPath` (In Merge Mode, Clicking Stroke Splits the Path; off), `highlightStroke` (Highlight Stroke When Editable; on) and `highlightColor` -(`#rrggbb` or a layer color's name; `#ff4f4f`, the layer color Red). With `clickStrokeSplitsPath` on, in merge mode, +(`#rrggbb` or a layer color's name; `#ff4f4f`, the layer color Red). The dialog's OK gives an error for a +`highlightColor` with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. With `clickStrokeSplitsPath` on, in merge mode, the pointer shows scissors within 4 screen pixels of a stroke, `highlightStroke` draws the run of stroke under it in `highlightColor`, and a click splits that run off its path: the run goes from the anchor or crossing point before the pointer to the one after it, the path keeps the rest of it, and a copy of the path with the run, in the path's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fa2bc1f7da..7f87708727 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -814,6 +814,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). + As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). From 535d423d6cb003805569fc3ea8bbe65f0b8279da Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:41:40 -0800 Subject: [PATCH 080/482] Appearance: Add New Fill and Add New Stroke params text match the code appearance.addFill copies the active fill row only when the call has no `ids`, no `id` and no `target: "contents"`; the params text now names `id` too. appearance.addStroke gives the new stroke at least 1 pt, so a 0.5 pt top stroke gives a 1 pt stroke; the params text now says so. Tests pin both: `id` alone leaves the active row alone and puts the new fill on top, and Add New Stroke on a 0.5 pt stroke adds a 1 pt one. --- crates/engine/src/cmd/appearance.rs | 4 ++-- crates/engine/src/tests/appearance.rs | 30 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 27f5aee810..4fb14ec31c 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -45,7 +45,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row", has_doc, |s, p| add_item(s, p, true) ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint and weight (else the default stroke)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt", has_doc, |s, p| add_item(s, p, false) ), diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 4fea39bdfb..9bed4eb343 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -323,6 +323,36 @@ fn add_fill_copies_the_active_fill_row_right_above_it() { assert_eq!(s.appearance_item(), Some(0)); } +/// With a fill row active, Add New Fill given `id` alone also puts a copy of the top fill on top, +/// and the active row stays. +#[test] +fn add_fill_with_id_leaves_the_active_fill_row_alone() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "appearance.setItem", json!({"index": 2, "color": "#0000ff"})); // [red, Stroke, blue] + run(&mut s, "appearance.setActiveItem", json!({"index": 0})); + run(&mut s, "appearance.addFill", json!({"id": id.0})); + let n = node(&s, id); + assert_eq!(n.appearance.items.iter().map(AppearanceItem::kind_name).collect::>(), ["fill", "stroke", "fill", "fill"]); + assert_eq!(fill_paint(&n, 0).color().unwrap().to_hex(), "#ff0000"); + assert_eq!(fill_paint(&n, 3).color().unwrap().to_hex(), "#0000ff"); + assert_eq!(s.appearance_item(), Some(0)); +} + +/// Add New Stroke copies the top stroke's weight but makes the new stroke at least 1 pt. +#[test] +fn add_stroke_is_at_least_one_point() { + let mut s = session(); + let id = rect(&mut s, 100.0); + run(&mut s, "stroke.set", json!({"weight": 0.5})); + run(&mut s, "appearance.addStroke", json!({})); // [Fill, Stroke, Stroke] + let n = node(&s, id); + assert_eq!(stroke(&n, 1).width, 0.5); + assert_eq!(stroke(&n, 2).width, 1.0); +} + /// The new fill above the active fill row takes only the row's paint: the row's opacity, blend /// mode, visibility, overprint and effects are not copied (Duplicate Item copies those). #[test] From be52e4e8afe865056e993c4d99b0b02a58daa654 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:45:13 -0800 Subject: [PATCH 081/482] Tabs: setting the stops a paragraph already has records no undo step text.tabs.set and text.tabs.clear return without an edit when every targeted paragraph already holds the stops. A Ctrl-drag that the 0 pt bound keeps from moving, or a drag released where it started, no longer adds an undo step that changes nothing. When one targeted paragraph holds other stops, the command still sets them all. --- crates/engine/src/cmd/tabs.rs | 39 +++++++++++++++++++++++++ crates/ui-egui/src/panels/tabs/tests.rs | 34 +++++++++++++++++++++ docs/mcp.md | 3 +- docs/target-app-parity.md | 2 +- 4 files changed, 76 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/tabs.rs b/crates/engine/src/cmd/tabs.rs index 193ced2f79..e1ababf690 100644 --- a/crates/engine/src/cmd/tabs.rs +++ b/crates/engine/src/cmd/tabs.rs @@ -69,6 +69,18 @@ fn apply(s: &mut Session, p: &Value, stops: Vec, label: &str) -> Result let ids = text_targets(s, p, "text.tabs.set")?; let range = TextRange::parse(p, "text.tabs.set")?; let n = stops.len(); + // Every targeted paragraph already holds these stops: no edit and no undo step. + let doc = &s.doc()?.doc; + let unchanged = ids.iter().all(|id| match doc.node(*id).map(|node| &node.kind) { + Some(NodeKind::Text(t)) => match para_span(range, t) { + None => t.para_styles().all(|pa| pa.tabs == stops), + Some(mut r) => r.all(|i| t.para_at(i).tabs == stops), + }, + _ => true, + }); + if unchanged { + return Ok(json!({ "stops": n })); + } s.edit(label, |d, _| { for id in &ids { if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { @@ -114,6 +126,33 @@ mod tests { assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"], json!([])); } + /// Setting the stops every targeted paragraph already holds records no undo step. When one + /// targeted paragraph holds other stops, the command still sets them all. + #[test] + fn setting_the_same_stops_records_no_undo_step() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap(); + let stops = json!({"stops": [{"position": 0}, {"position": 20, "leader": "."}]}); + s.execute("text.tabs.set", &stops).unwrap(); + let undo = |s: &Session| s.active().unwrap().history.undo.len(); + let before = undo(&s); + s.execute("text.tabs.set", &stops).unwrap(); + s.execute("text.tabs.set", &json!({"stops": [{"position": 20, "leader": "."}, {"position": 0}]})).unwrap(); + assert_eq!(undo(&s), before); + s.execute("text.tabs.clear", &json!({})).unwrap(); + s.execute("text.tabs.clear", &json!({})).unwrap(); + assert_eq!(undo(&s), before + 1); + // The second paragraph (bytes 4 on) takes other stops; setting the first paragraph's stops + // on both paragraphs changes the second. + s.execute("text.tabs.set", &stops).unwrap(); + s.execute("text.tabs.set", &json!({"stops": [{"position": 50}], "start": 4, "end": 4})).unwrap(); + let before = undo(&s); + s.execute("text.tabs.set", &stops).unwrap(); + assert_eq!(undo(&s), before + 1); + assert_eq!(s.execute("text.tabs.get", &json!({"start": 4})).unwrap()["stops"][1]["position"], json!(20.0)); + } + /// #1877: a leader set the way the Tabs panel sets it fills the tab's gap with its dots. #[test] fn tab_leader_fills_the_gap_with_its_characters() { diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index 428b6945db..7a92ff80c7 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -690,6 +690,40 @@ fn command_drag_stops_at_zero_and_keeps_the_spacing() { assert!(moved_all(&[], 0, 10.0).is_none()); } +/// A drag that leaves the stops where they were records no undo step: a Ctrl-drag (Command on +/// macOS) to the left while the leftmost stop is at 0, and a plain drag that takes a stop away and +/// releases it where it started. The dragged stop is still selected. +#[test] +fn a_drag_that_moves_no_stop_records_no_undo_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap(); + app.session.execute("text.tabs.set", &json!({"stops": [{"position": 0}, {"position": 20}]})).unwrap(); + let ctx = egui::Context::default(); + let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::>(); + let before = app.session.active().unwrap().history.undo.len(); + command_drag_on_ruler(&ctx, &mut app, 20.0, 5.0); + assert_eq!(positions(&app), [0.0, 20.0]); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "Ctrl-drag"); + assert_eq!(pstate::(&ctx, "tabs-sel"), 1); + set_pstate(&ctx, "tabs-sel", 0usize); + let labels = ruler_frame(&ctx, &mut app, vec![], false); + let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") }; + assert_eq!(zero, "0"); + let per = next.parse::().unwrap() * app.session.general_unit().points(); + let x = |pt: f64| egui::pos2(a.x - 2.0 + (pt / per) as f32 * (b.x - a.x), a.y + 15.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ruler_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(x(20.0)), button(x(20.0), true)], false); + for pt in [40.0, 60.0, 30.0, 20.0] { + ruler_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(x(pt))], false); + } + ruler_frame(&ctx, &mut app, vec![button(x(20.0), false)], false); + ruler_frame(&ctx, &mut app, vec![], false); + assert_eq!(positions(&app), [0.0, 20.0]); + assert_eq!(app.session.active().unwrap().history.undo.len(), before, "plain drag"); + assert_eq!(pstate::(&ctx, "tabs-sel"), 1); +} + /// A Ctrl-drag (Command on macOS) that would put a stop past 100,000 pt stops when the rightmost /// stop reaches 100,000 pt, so the stops move and keep their spacing. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5bb5a0c29d..915d0ef8a1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5632,7 +5632,8 @@ spaceBefore, spaceAfter, hyphenate, mojikumi, burasagari, direction, leadingMode `start` / `end` byte offsets of the plain text (as `text.setRangeStyle` does): they change the paragraphs the range touches (a caret, `start == end`, touches its paragraph). Without a range they change every paragraph of the targeted objects, as before. With a range, the character attributes of `text.setStyle` and `text.setFormat` style -that range of characters. `text.tabs.get {start?}` and `paraStyle.new` / `paraStyle.redefine {id, start?}` read the +that range of characters. When every paragraph that `text.tabs.set` or `text.tabs.clear` targets already has those +stops, the command changes nothing and records no undo step. `text.tabs.get {start?}` and `paraStyle.new` / `paraStyle.redefine {id, start?}` read the paragraph at `start`; `paraStyle.list` counts paragraphs as uses, and `charStyle.list` counts runs; both count the type in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes. `charStyle.unused` and `paraStyle.unused` (Select All Unused in the Character Styles and Paragraph Styles panel menus) list the styles with no diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7f87708727..849d7fa00c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -529,7 +529,7 @@ since 2026-10-01. - **The text style panel menus' Duplicate and Delete:** in the Character Styles and Paragraph Styles panel menus, Duplicate highlights the copy, as Create New Style highlights the new style, and Delete leaves no style highlighted, as the Delete button does, so Duplicate, Clear Overrides, Redefine and Style Options are disabled until another style is clicked. A highlighted style that is renamed in Style Options or deleted by a command is no longer highlighted either. The tests `panels::text_styles::tests::panel_menu_duplicate_and_delete_update_the_highlighted_style` and `a_highlighted_style_that_is_no_longer_listed_is_not_highlighted` cover this. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Naming a new text style first:** Alt-click on New in the Character Styles or Paragraph Styles panel opens New Character Style or New Paragraph Style (`ui.newCharStyle`, `ui.newParaStyle`) with the name a plain click's style gets; OK makes the style from the text selected when the dialog opened, and Cancel adds none. Tests `panels::text_styles::tests::alt_clicking_new_character_style_asks_for_its_name` and `alt_clicking_new_paragraph_style_asks_for_its_name`. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), which lists Alt-click for opening panel options and names Actions, Brushes, Swatches and Symbols as exceptions. -- **Moving all tab stops:** in the Tabs panel, a stop dragged on the ruler with Ctrl held (Command on macOS) moves every stop by the same distance, in one `text.tabs.set` and one undo step; the stops keep their order, alignment and leaders, the ruler shows them moving during the drag, and a drag that would take the leftmost stop below 0 leaves it at 0, or the rightmost past 100,000 pt leaves it at 100,000 pt, with the other stops at their spacing from it. Ctrl must be held when the drag starts. Tests `panels::tabs::tests::command_drag_moves_all_the_stops_together`, `command_drag_stops_at_zero_and_keeps_the_spacing` and `command_drag_stops_at_the_largest_position_and_keeps_the_spacing`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which says that a Ctrl-drag (Windows) or Command-drag (macOS) of a tab moves all the tab stops at the same time. +- **Moving all tab stops:** in the Tabs panel, a stop dragged on the ruler with Ctrl held (Command on macOS) moves every stop by the same distance, in one `text.tabs.set` and one undo step; the stops keep their order, alignment and leaders, the ruler shows them moving during the drag, and a drag that would take the leftmost stop below 0 leaves it at 0, or the rightmost past 100,000 pt leaves it at 100,000 pt, with the other stops at their spacing from it. A drag that leaves every stop where it was records no undo step. Ctrl must be held when the drag starts. Tests `panels::tabs::tests::command_drag_moves_all_the_stops_together`, `command_drag_stops_at_zero_and_keeps_the_spacing`, `command_drag_stops_at_the_largest_position_and_keeps_the_spacing` and `a_drag_that_moves_no_stop_records_no_undo_step`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which says that a Ctrl-drag (Windows) or Command-drag (macOS) of a tab moves all the tab stops at the same time. - **Width Point Edit:** Shift-double-click enables Adjust Adjoining Width Points; plain double-click and direct opening retain the default. Tool dispatch and headless dialog tests cover neighboring widths, Undo/Redo and Cancel. Public reference: [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. From 0143e0f7065485dfc6db3664ef0fff9d15becc32 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:06:11 -0500 Subject: [PATCH 082/482] Fix #5483: a large font library no longer keeps the window from opening The menu bar builds Type > Font in every frame, the first included, and its family list waited for the scan of every installed font. When that scan took longer than the 20 s first-frame watchdog (thousands of fonts on a slow disk, or each file checked by antivirus), the app took the graphics adapter for hung and started again without it, until none was left and no window ever showed. The menu now lists the fonts already loaded until the scan ends, then all of them (FontDb::menu_family_list_now, installed_fonts_ready). --- crates/text/src/fontdb/db.rs | 26 ++++++++++++++++++++++++ crates/text/src/tests/sysfonts.rs | 30 ++++++++++++++++++++++++++++ crates/ui-egui/src/menus/submenus.rs | 22 ++++++++++++-------- docs/gaps.md | 3 ++- 4 files changed, 72 insertions(+), 9 deletions(-) diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 0d8eb0e3fd..1b14dd6dcb 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -152,6 +152,32 @@ impl FontDb { list } + /// Whether the installed fonts are cataloged, so lookups by family name no longer wait for + /// the scan. Always true on wasm, which has no installed fonts. + pub fn installed_fonts_ready(&self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + self.cataloged.get().is_some() + } + #[cfg(target_arch = "wasm32")] + true + } + + /// [`FontDb::menu_family_list`] without waiting for the installed fonts' scan: until it ends, + /// the families already loaded (the bundled fonts and any loaded meanwhile), sorted, without + /// the hidden ones. For what is built every frame, such as the menu bar's Type › Font, so the + /// window's first frame doesn't wait for the scan of a large font library (#5483). + /// [`FontDb::generation`] changes when the scan ends. + pub fn menu_family_list_now(&self) -> Arc<[String]> { + if self.installed_fonts_ready() { + return self.menu_family_list(); + } + let mut v: Vec = self.read_faces().iter().map(|f| f.family.clone()).filter(|f| !f.starts_with('.')).collect(); + v.sort_by_key(|a| a.to_lowercase()); + v.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + v.into() + } + /// How a font menu labels `family`: the English name when `english` is on (Preferences › Type › /// Show Font Names in English, the default), else the font's native-language name when it has /// one. The document and commands still use the English family ([`Self::canonical`]). diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 7ab8d9029c..d4068eb5da 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -308,6 +308,36 @@ fn a_background_scan_serves_the_first_lookup() { assert_eq!(db.load_system_fonts(), 2, "a rescan catalogs the two faces again"); } +/// The menu bar's Type › Font is built in the window's first frame, so its family list doesn't wait +/// for the scan of the installed fonts: a large library would hold the first frame past the +/// first-frame watchdog, and the app would never show its window (#5483). Once the scan ends, the +/// list has the installed fonts. +#[cfg(unix)] +#[test] +fn the_menu_family_list_now_does_not_wait_for_the_scan() { + let dir = font_dir("held-scan"); + // A named pipe with a font's name: the scan opens it and waits there until something writes. + let pipe = dir.join("Held.ttf"); + assert!(std::process::Command::new("mkfifo").arg(&pipe).status().unwrap().success()); + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![dir]))); + let generation = db.generation(); + db.scan_in_background(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send((db.installed_fonts_ready(), db.menu_family_list_now())); + }); + let listed = rx.recv_timeout(std::time::Duration::from_secs(10)); + // Let the scan go on whatever happened: the pipe is opened and closed with nothing written. + drop(std::fs::OpenOptions::new().write(true).open(&pipe).unwrap()); + let (ready, listed) = listed.expect("the list comes while the scan is held"); + assert!(!ready && !has(&listed, FAMILY), "before the scan ends, only the fonts already loaded"); + // Waits for the scan. + assert!(has(&db.menu_family_list(), FAMILY)); + assert!(db.installed_fonts_ready()); + assert_ne!(db.generation(), generation, "a menu built from the short list is built again"); + assert!(has(&db.menu_family_list_now(), FAMILY)); +} + #[test] fn the_family_list_is_shared_until_fonts_change() { let db = FontDb::with_font_dirs(vec![]); diff --git a/crates/ui-egui/src/menus/submenus.rs b/crates/ui-egui/src/menus/submenus.rs index a86b66c82f..a878f7f0cc 100644 --- a/crates/ui-egui/src/menus/submenus.rs +++ b/crates/ui-egui/src/menus/submenus.rs @@ -63,21 +63,27 @@ pub(super) fn insert_items(list: &[(&'static str, &'static str)]) -> Vec { /// Type → Font: one item per available family, the installed fonts included. Built again only when /// the fonts or Show Font Names in English change (the menu tree is built every frame); labels are /// interned once each, so rebuilding doesn't allocate forever. The command still sets the English -/// family name ([`vectorcraft_text::FontDb::canonical`]). +/// family name ([`vectorcraft_text::FontDb::canonical`]). Until the installed fonts are scanned it +/// lists the fonts already loaded, by their English names, rather than wait for the scan: the menu +/// bar is drawn in the window's first frame, which a large font library would otherwise hold up +/// past the first-frame watchdog (#5483). pub(super) fn font_items(english_names: bool) -> Vec { static NAMES: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeSet::new()); - static ITEMS: std::sync::Mutex<(u64, bool, Vec)> = std::sync::Mutex::new((u64::MAX, true, Vec::new())); + static ITEMS: std::sync::Mutex<(u64, bool, bool, Vec)> = std::sync::Mutex::new((u64::MAX, true, false, Vec::new())); let db = vectorcraft_text::FontDb::global(); - // Read first: fonts that load meanwhile make the next frame build the list again. + // Read first: fonts that load meanwhile make the next frame build the list again. The scan + // ends between changing the generation and counting as cataloged, so both are kept. + let cataloged = db.installed_fonts_ready(); let generation = db.generation(); - let fams = db.menu_family_list(); + let fams = db.menu_family_list_now(); let (Ok(mut names), Ok(mut items)) = (NAMES.lock(), ITEMS.lock()) else { return vec![] }; - if items.0 != generation || items.1 != english_names { + if items.0 != generation || items.1 != english_names || items.2 != cataloged { let list = fams .iter() .map(|f| { let english = f.as_str(); - let shown = db.family_display_name(english, english_names); + // A native name may be the catalog's, which isn't there to read yet. + let shown = if cataloged { db.family_display_name(english, english_names) } else { english.to_string() }; let label: &'static str = match names.get(shown.as_str()) { Some(n) => n, None => { @@ -97,9 +103,9 @@ pub(super) fn font_items(english_names: bool) -> Vec { cp(label, "text.setStyle", json!({ "font": font })) }) .collect(); - *items = (generation, english_names, list); + *items = (generation, english_names, cataloged, list); } - items.2.clone() + items.3.clone() } /// The raster effects' submenus of the Effect menu (the Photoshop-style effects, below the diff --git a/docs/gaps.md b/docs/gaps.md index 77acb709a2..2f3c5ea617 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **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-04 · **Change:** minor (the menu bar no longer waits for the installed fonts' scan, so a large font library doesn't keep the window from opening; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence @@ -191,6 +191,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall - **Unconfirmed (2026-10-14):** Tool cursors are painted into the window on Wayland (#1652; not run on Linux, #1645 stays open until confirmed). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). - **Done:** RPM required dependencies use 64-bit library capabilities and declare glibc 2.35, libm and libgcc_s (#1275); generated metadata and isolated synthetic-provider checks cover x86_64/aarch64. Real-distribution install/start-up QA is still missing. +- **Done (2026-11-04):** a large font library no longer keeps the window from opening (#5483). The menu bar's Type › Font, drawn in the first frame, waited for the scan of every installed font; when that took longer than the 20 s first-frame watchdog (thousands of fonts on a slow disk, or with each file checked by antivirus) the app took the graphics adapter for hung and started again without it until none was left. The menu now lists the fonts already loaded until the scan ends, then all of them (`the_menu_family_list_now_does_not_wait_for_the_scan`; checked on Linux with 3,923 extra font files, each open delayed 8 ms: the window opened in 1.5 s, where it never did before). Estimate unchanged. - **Done (2026-10-29):** the Linux Flatpak on GNOME no longer reconnects to the compositor and logs a warning every 250 ms when arboard has neither data-control nor X11 (267k warnings in 18 h filled the 16 MB log in 3 h): a clipboard that can't be opened is retried with a wait growing to a minute and logged once. Copy and Paste of text with other apps work there through the core Wayland protocol. - **Missing:** pictures (`image/png`) and SVG as `image/svg+xml` on the clipboard of the Flatpak on GNOME, where only text travels (smithay-clipboard 0.7 carries text only); the app not starting or staying in the background on some Windows 11 machines (#858, #964 fixed 2026-10-10, #620, #818), slow pointer on a Linux AppImage (#575), macOS paste from other apps (#954), a From b8269d7bdf07f7c7b61b6b0787a08c9e684be26b Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:34:44 -0500 Subject: [PATCH 083/482] Native menu: read the menus again when the fonts change On macOS the menu bar is native and is read again only when its state hash changes. Type > Font now lists the loaded fonts until the installed ones are scanned, so the hash takes the font generation and whether the scan has ended. The tests that wait for process-wide generations to hold still wait for the fonts too. --- crates/ui-egui/src/native_menu.rs | 5 ++- crates/ui-egui/src/tests/nativemenu.rs | 51 +++++++++++++++++++++----- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index c8d046a686..8d1b7ee083 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -590,7 +590,8 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { /// What the menus' rows depend on, cheaply (no allocation): commands run, the active document, /// its revision (edits, selection and view changes), history and clipboard, the language, -/// shortcuts, plug-ins and an open file dialog. `input` forces a change on frames with a click or +/// shortcuts, plug-ins, an open file dialog and the fonts (Type › Font lists the loaded fonts +/// until the installed ones are scanned, then all of them, #5483). `input` forces a change on frames with a click or /// a key press, which covers what the hash doesn't list (panels shown, a tool picked). While an /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the revision, which each of its previews changes, is left out: @@ -609,5 +610,7 @@ fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { app.file_dialog_open().hash(&mut h); (crate::i18n::current().code(), menus::plugin_revision()).hash(&mut h); crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed).hash(&mut h); + let fonts = vectorcraft_text::FontDb::global(); + (fonts.generation(), fonts.installed_fonts_ready()).hash(&mut h); h.finish() } diff --git a/crates/ui-egui/src/tests/nativemenu.rs b/crates/ui-egui/src/tests/nativemenu.rs index cc6e4b3466..5d1d1c26f1 100644 --- a/crates/ui-egui/src/tests/nativemenu.rs +++ b/crates/ui-egui/src/tests/nativemenu.rs @@ -388,12 +388,20 @@ fn click(at: Pos2, pressed: bool) -> Event { } /// Run `drag` on a new app with the fake native menu, and run it again on another new app until -/// the shortcut and plug-in generations hold still through a run (at most 20 runs). Return that app -/// and what `drag` returned. The generations are process-wide and only grow. A test running -/// alongside can bump them, and the app then reads the menus again, so every step whose menu -/// reads a test counts runs inside `drag`. +/// the shortcut, plug-in and font generations hold still through a run (at most 20 runs). Return +/// that app and what `drag` returned. The generations are process-wide and only grow. A test +/// running alongside can bump them (a font it adds, the installed fonts' scan ending), and the app +/// then reads the menus again, so every step whose menu reads a test counts runs inside `drag`. fn undisturbed(drag: impl Fn(&mut Mac) -> R) -> (Mac, R) { - let generations = || (crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed), crate::menus::plugin_revision()); + let fonts = vectorcraft_text::FontDb::global(); + let generations = || { + ( + crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed), + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + ) + }; for _ in 0..20 { let mut m = Mac::new(true); let before = generations(); @@ -420,10 +428,18 @@ fn key_equivalents_run_through_the_normal_shortcut_path_once() { m.key_equivalent("Cmd+Z"); assert_eq!(undo(&m), before - 1, "⌘Z undid one step"); assert!(m.fake.synced() >= 1, "the menus were built"); - // Idle frames don't read the menus again. The shortcut and plug-in generations are - // process-wide, and tests running alongside with other shortcuts bump them (rightly reading - // the menus again), so judge two idle frames in which they held still. - let globals = || (crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed), crate::menus::plugin_revision()); + // Idle frames don't read the menus again. The shortcut, plug-in and font generations are + // process-wide, and tests running alongside with other shortcuts or fonts bump them (rightly + // reading the menus again), so judge two idle frames in which they held still. + let fonts = vectorcraft_text::FontDb::global(); + let globals = || { + ( + crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed), + crate::menus::plugin_revision(), + fonts.generation(), + fonts.installed_fonts_ready(), + ) + }; let quiet = (0..50).any(|_| { let (before, synced) = (globals(), m.fake.synced()); m.frame(vec![]); @@ -540,6 +556,23 @@ fn applying_a_dialog_preview_reads_the_menus() { assert_eq!(find(&m.fake.last(), "edit.undo").label, "Undo Rotate"); } +/// Fonts that come in after the menus were read (the installed fonts' scan ending, #5483) make the +/// next frame read them again, with no click or key, so Type › Font lists them. +#[test] +fn fonts_that_load_read_the_menus_again() { + use vectorcraft_text::test_fonts as t; + let db = vectorcraft_text::FontDb::global(); + // A test font no other test loaded yet, so adding it changes the fonts. + let fonts = [t::vertical_font(true), t::two_axis_font(), t::variable_font()]; + let mut m = Mac::new(true); + let synced = m.fake.synced(); + if !fonts.into_iter().flatten().any(|data| db.add_font(data) > 0) { + return; + } + m.frame(vec![]); + assert!(m.fake.synced() > synced, "the menus were read again"); +} + /// The font menu previews each font it highlights on the selected type, in one interaction: the /// menus are read as the preview begins and as it ends, and not for the fonts between. #[test] From 21be9e6b6e1892a80082e431dd0e1ab0efcbfe03 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:21:38 -0800 Subject: [PATCH 084/482] Tests: the opening queue tests wait on the worker's signal instead of the clock The opening tests waited 400 or 500 ms of wall-clock time for files read off the UI thread, and up to 30 s in loops that polled until the queue emptied. Under load a read could take longer, and a_file_that_opens_and_asks_holds_back_the_next_one_ready failed. wait_read now blocks on each pending file's own result channel and keeps the result for poll, and open_ready waits and then polls once. The background save in long_operation_busy_while_a_file_opens_or_a_background_save_runs waits with background::wait_all, and its job waits on the release channel without a timeout. Shipped code is unchanged. --- crates/ui-egui/src/opening/tests.rs | 132 +++++++++------------------- 1 file changed, 40 insertions(+), 92 deletions(-) diff --git a/crates/ui-egui/src/opening/tests.rs b/crates/ui-egui/src/opening/tests.rs index fa90d3cd51..40e2e6009b 100644 --- a/crates/ui-egui/src/opening/tests.rs +++ b/crates/ui-egui/src/opening/tests.rs @@ -9,11 +9,7 @@ fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() { assert!(!long_operation_busy(&app)); start(&mut app, "/art/Wait.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(10.0, 10.0), false)).unwrap(); assert!(long_operation_busy(&app)); - let t0 = std::time::Instant::now(); - while long_operation_busy(&app) && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert!(!long_operation_busy(&app)); let (release, held) = std::sync::mpsc::channel::<()>(); let services = Services { write_shared: Some(std::sync::Arc::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() }; @@ -24,7 +20,7 @@ fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() { "Saving test.vectorcraft".into(), None, move |_| { - let _ = held.recv_timeout(std::time::Duration::from_secs(10)); + let _ = held.recv(); Ok(json!({})) }, |_, r| r, @@ -32,14 +28,28 @@ fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() { .unwrap(); assert!(long_operation_busy(&app)); let _ = release.send(()); - let t0 = std::time::Instant::now(); - while long_operation_busy(&app) && t0.elapsed().as_secs() < 30 { - crate::background::poll(&mut app); - std::thread::yield_now(); - } + crate::background::wait_all(&mut app); assert!(!long_operation_busy(&app)); } +/// Wait until every file being opened has been read, keeping each result for [`poll`]. +fn wait_read(app: &mut VectorcraftApp) { + for p in &mut app.opening.pending { + let (tx, done) = std::sync::mpsc::channel(); + // A reader that stopped without a result leaves the new channel closed too. + if let Ok(r) = p.done.recv() { + let _ = tx.send(r); + } + p.done = done; + } +} + +/// Wait until every file being opened has been read, then open the files that may open now. +fn open_ready(app: &mut VectorcraftApp) { + wait_read(app); + poll(app); +} + /// #1694: a file that finishes opening while a dialog is up waits for it to close, so the /// dialog's document stays the active one. #[test] @@ -49,19 +59,12 @@ fn a_file_ready_while_a_dialog_is_open_waits_for_it_to_close() { let (first, before) = (app.session.doc().unwrap().uid, app.session.documents().len()); app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({"path": "/art/First.vectorcraft"}))); start(&mut app, "/art/Second.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert_eq!((app.session.documents().len(), app.session.doc().unwrap().uid), (before, first), "still the dialog's document"); assert_eq!(app.opening.pending.len(), 1); app.ui.dialog = None; - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + poll(&mut app); + assert!(app.opening.pending.is_empty()); assert_eq!(app.session.documents().len(), before + 1); assert_eq!(app.session.doc().unwrap().path.as_deref(), Some("/art/Second.vectorcraft")); } @@ -80,18 +83,10 @@ fn a_file_ready_during_a_drag_waits_for_it_to_end() { app.session.pointer(&PointerEvent::new(kind, x, 20.0), view).unwrap(); } start(&mut app, "/art/Second.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert!(app.session.documents().len() == 1 && app.session.in_interaction(), "the file waits for the drag"); app.session.pointer(&PointerEvent::new(PointerKind::Up, 60.0, 20.0), view).unwrap(); - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + poll(&mut app); assert_eq!(app.session.documents().len(), 2); let moved = app.session.documents()[0].doc.node(vectorcraft_doc::NodeId(square)).and_then(|n| n.geometric_bounds()); assert_eq!(moved.map(|b| (b.x0, b.y0)), Some((50.0, 10.0)), "the drag was not canceled"); @@ -112,18 +107,10 @@ fn a_file_ready_during_a_place_cursor_drag_waits_for_it_to_end() { crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, x, 20.0), view); } start(&mut app, "/art/Second.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert!(app.session.documents().len() == 1 && app.session.tool_busy(), "the file waits for the drag"); crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Up, 60.0, 20.0), view); - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + poll(&mut app); assert_eq!(app.session.documents().len(), 2); let first = &app.session.documents()[0].doc; let names: Vec<_> = first.layers.iter().flat_map(|l| l.children().into_iter().flatten()).filter_map(|n| n.name.clone()).collect(); @@ -158,22 +145,14 @@ fn a_file_ready_during_a_preview_waits_for_it_to_end() { } assert_eq!(app.session.tool_busy(), case != "slider", "{case}"); start(&mut app, "/art/Second.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 400 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert!(app.session.documents().len() == 1 && app.session.in_interaction(), "the file waits for the preview: {case}"); if case == "line" { click(&mut app, 50.0); } else { app.session.cancel_interaction().unwrap(); } - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + poll(&mut app); assert_eq!(app.session.documents().len(), 2, "{case}"); } } @@ -194,24 +173,17 @@ fn a_file_ready_between_a_tools_clicks_opens() { crate::canvas::dispatch(app, &PointerEvent::new(kind, x, 20.0), view); } }; - let opened = |app: &mut VectorcraftApp| { - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(app); - std::thread::yield_now(); - } - }; click(&mut app, 20.0); assert!(app.session.tool_busy() && !app.session.in_interaction(), "the first point waits for the second"); start(&mut app, "/art/Second.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(400.0, 300.0), false)).unwrap(); - opened(&mut app); + open_ready(&mut app); assert_eq!(app.session.documents().len(), 2, "the file opens after one click"); assert!(!app.session.tool_busy(), "the tool starts afresh"); click(&mut app, 20.0); click(&mut app, 80.0); assert!(app.session.tool_busy() && !app.session.in_interaction(), "the second point waits for the line's place"); start(&mut app, "/art/Third.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - opened(&mut app); + open_ready(&mut app); assert_eq!(app.session.documents().len(), 3, "the file opens after two clicks"); assert!(!app.session.tool_busy() && !app.session.in_interaction(), "the tool starts afresh"); let second = &app.session.documents()[1].doc; @@ -228,11 +200,7 @@ fn a_file_read_off_the_ui_thread_opens_as_one_read_at_once() { let r = start(&mut app, "/art/Poster.vectorcraft", bytes).unwrap(); assert_eq!(r["background"], true); assert_eq!(app.ui.status, "Opening Poster.vectorcraft…"); - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert_eq!(app.session.documents().len(), before + 1); assert!(!app.ui.status.starts_with("Opening"), "{}", app.ui.status); let st = app.session.doc().unwrap(); @@ -240,11 +208,7 @@ fn a_file_read_off_the_ui_thread_opens_as_one_read_at_once() { assert_eq!(app.ui.recent_files.first().map(String::as_str), Some("/art/Poster.vectorcraft")); // A file that can't be read: reported, nothing opened, not a recent file. start(&mut app, "/art/Broken.vectorcraft", b"{\"format\":\"vectorcraft\"".to_vec()).unwrap(); - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert_eq!(app.session.documents().len(), before + 1); assert!(app.ui.status.starts_with("Couldn't open Broken.vectorcraft"), "{}", app.ui.status); assert_ne!(app.ui.recent_files.first().map(String::as_str), Some("/art/Broken.vectorcraft")); @@ -298,11 +262,7 @@ fn a_file_read_off_the_ui_thread_has_its_links_and_type_as_one_read_at_once() { assert!(question.as_ref().is_some_and(|(_, f)| f["missing"][0]["name"] == "gone.png"), "{update}: {question:?}"); app.ui.dialog = None; start(&mut app, &path, bytes.clone()).unwrap(); - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); let st = app.session.doc().unwrap(); assert!(*st.doc == *at_once, "{update}: the same document"); assert!(st.history.undo.is_empty() && !st.is_dirty(), "{update}"); @@ -341,11 +301,7 @@ fn a_file_asked_for_again_while_it_is_read_opens_once() { start(&mut app, "/art/Poster.vectorcraft", bytes).unwrap(); assert_eq!(crate::io::open_file(&mut app, "/art/Poster.vectorcraft", true).unwrap(), Value::Null); assert_eq!(app.opening.pending.len(), 1); - let t0 = std::time::Instant::now(); - while !app.opening.pending.is_empty() && t0.elapsed().as_secs() < 30 { - poll(&mut app); - std::thread::yield_now(); - } + open_ready(&mut app); assert_eq!(app.session.documents().len(), 1); } @@ -374,12 +330,8 @@ fn a_queued_reopen_that_asks_holds_back_files_ready_to_open() { app.session.execute("file.close", &json!({"index": 1})).unwrap(); app.session.execute("file.close", &json!({"index": 0})).unwrap(); start(&mut app, "/art/Other.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - // Time for the other file to be read; it waits for the dialog meanwhile. - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 500 { - poll(&mut app); - std::thread::yield_now(); - } + // The other file is read; it waits for the dialog meanwhile. + open_ready(&mut app); assert_eq!(app.opening.pending.len(), 1); app.ui.dialog = None; poll(&mut app); @@ -402,12 +354,8 @@ fn a_file_that_opens_and_asks_holds_back_the_next_one_ready() { app.ui.dialog = Some(crate::state::Dialog::new(crate::dialogs::save_options::KIND, json!({}))); start(&mut app, "/art/Asks.vectorcraft", asks).unwrap(); start(&mut app, "/art/Plain.vectorcraft", vectorcraft_format::save(&vectorcraft_doc::Document::new(120.0, 80.0), false)).unwrap(); - // Time for both files to be read; they wait for the dialog meanwhile. - let t0 = std::time::Instant::now(); - while t0.elapsed().as_millis() < 500 { - poll(&mut app); - std::thread::yield_now(); - } + // Both files are read; they wait for the dialog meanwhile. + open_ready(&mut app); assert_eq!(app.opening.pending.len(), 2); app.ui.dialog = None; poll(&mut app); From 84f528f5bb37cc2fc97dbfa3298e5c40e5698b9d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:04:37 -0800 Subject: [PATCH 085/482] Character: Kerning reads (10+5) with a manual value too Kerning read one pair of parentheses around its text only while it showed an automatic value as (12), so typing (10+5) over a manual value committed nothing. spin_kerning now reads that pair in both states; the field still shows parentheses only for an automatic value, and (10+5)*2 is still refused. --- crates/ui-egui/src/widgets/look_tests.rs | 28 ++++++++++++++++++ crates/ui-egui/src/widgets/numeric.rs | 36 ++++++++++++++++++++---- 2 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 17a2288d16..1f9275008f 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -468,3 +468,31 @@ fn a_held_spinner_arrow_repeats() { frame(&ctx, 1.8, vec![], &mut add); assert_eq!(value.get(), 9.0, "letting go doesn't step once more"); } + +/// The Kerning field reads `(10+5)` as 15 whether it shows a manual value (`12`) or an automatic +/// one (`(12)`), and refuses `(10+5)*2` either way. +#[test] +fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { + let typed = |automatic: bool, text: &str| { + let ctx = themed(Default::default()); + let picked = std::cell::Cell::new(None); + let mut add = |ui: &mut Ui| { + ui.horizontal(|ui| { + if let Some(p) = spin_kerning(ui, "kern", Some(12.0), Some(automatic), Some(false), "Optical", automatic, 100.0, &[]) { + picked.set(Some(p)); + } + }); + }; + arm_field_focus(&ctx, "kern"); + frame(&ctx, 0.0, vec![], &mut add); + frame(&ctx, 0.1, vec![], &mut add); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&ctx, 0.2, vec![egui::Event::Text(text.into()), enter(true), enter(false)], &mut add); + frame(&ctx, 0.3, vec![], &mut add); + picked.get() + }; + for automatic in [false, true] { + assert_eq!(typed(automatic, "(10+5)"), Some(SpinPick::Value(15.0)), "automatic: {automatic}"); + assert_eq!(typed(automatic, "(10+5)*2"), None, "automatic: {automatic}"); + } +} diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 56ace75b85..847b3b0ea4 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -433,9 +433,8 @@ pub fn mixed_field_named( bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false, false) } -/// [`mixed_field`] whose ↑/↓, wheel and scrub stop at `bounds`; ↑/↓ and the wheel take `step`'s steps -/// when it is given (see [`SliderValue::step`]). Armed with id salt `id` ([`arm_field_focus`]), it -/// takes the keyboard focus with its value selected. +/// [`bounded_field_reading`] that reads one pair of parentheses around its text only while it shows +/// its value in parentheses. #[allow(clippy::too_many_arguments)] fn bounded_field( ui: &mut Ui, @@ -450,11 +449,34 @@ fn bounded_field( step: Option f64>, parentheses: bool, live: bool, +) -> Option { + bounded_field_reading(ui, id, label, name, value, suffix, decimals, width, bounds, step, parentheses, parentheses, live) +} + +/// [`mixed_field`] whose ↑/↓, wheel and scrub stop at `bounds`; ↑/↓ and the wheel take `step`'s steps +/// when it is given (see [`SliderValue::step`]). Armed with id salt `id` ([`arm_field_focus`]), it +/// takes the keyboard focus with its value selected. With `parentheses` it shows its value as +/// `(12)`; with `read_parentheses` it reads typed text as [`field_number`] does with its Kerning flag. +#[allow(clippy::too_many_arguments)] +fn bounded_field_reading( + ui: &mut Ui, + id: impl std::hash::Hash, + label: Option, + name: Option<&str>, + value: Option, + suffix: &str, + decimals: usize, + width: f32, + bounds: &RangeInclusive, + step: Option f64>, + parentheses: bool, + read_parentheses: bool, + live: bool, ) -> Option { let armed = take_armed_focus(ui, &id); let id = id_with(ui.scope_id(), id); let show = |value: f64| field_text(value, suffix, decimals); - let read = |buf: &str| field_number(buf, suffix, parentheses); + let read = |buf: &str| field_number(buf, suffix, read_parentheses); let shown = value.map(|v| if parentheses { format!("({})", show(v)) } else { show(v) }).unwrap_or_default(); take_dialog_focus(ui, id, &shown); if armed { @@ -677,7 +699,9 @@ pub fn spin_plain_named( .and_then(SpinPick::value) } -/// Kerning's numeric field and automatic method choices. +/// Kerning's numeric field and automatic method choices. With `parentheses` the field shows its +/// value as `(12)`; typed text such as `(10+5)` reads with one pair of parentheses around it either +/// way. #[allow(clippy::too_many_arguments)] pub fn spin_kerning( ui: &mut Ui, @@ -704,7 +728,7 @@ pub fn spin_kerning( presets, &[], &|v| format!("{v}"), - &mut |ui, fw, label| bounded_field(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses, false), + &mut |ui, fw, label| bounded_field_reading(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses, true, false), ) } From 041736753219759a73e797c02e423ed694832d24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 04:39:49 -0800 Subject: [PATCH 086/482] Accessibility: screen readers can set a dialog slider's number Dialog sliders and the Blob Brush tip preview offered screen readers only the increment and decrement actions. They now also offer the set-value action: the last request in a frame sets the number within the slider's range, rounded to the places its field shows, and a value that is not a finite number leaves it as it is. --- crates/ui-egui/src/dialogs/tests.rs | 42 +++++++++++++++++++++++++++++ crates/ui-egui/src/widgets/color.rs | 39 ++++++++++++++++++++++----- 2 files changed, 74 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index ef3bf88483..9b6365ac87 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2015,6 +2015,48 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { assert_eq!(angle(&app), -44.0, "the drag gives the preview the focus"); } +/// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the +/// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to +/// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite +/// number leaves the Angle as it is. +#[test] +fn screen_readers_set_the_blob_brush_angle() { + use egui::accesskit::{Action, ActionData, ActionRequest, TreeId}; + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let angle = |app: &VectorcraftApp| app.ui.dialog.as_ref().expect("Blob Brush Tool Options is open").f64("angle", f64::NAN); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (node, ..) = slider_node(&out, "Angle"); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let advertised = nodes.iter().find(|(id, _)| *id == node).is_some_and(|(_, n)| n.supports_action(Action::SetValue)); + assert!(advertised, "the Angle slider offers the set-value action"); + let set = |value: f64| { + egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::SetValue, + target_node: node, + target_tree: TreeId::ROOT, + data: Some(ActionData::NumericValue(value)), + }) + }; + f.run(&mut app, vec![set(30.0)]); + assert_eq!(angle(&app), 30.0); + f.run(&mut app, vec![set(12.4)]); + assert_eq!(angle(&app), 12.0, "the field shows whole degrees"); + let shown = crate::widgets::SliderValue::field(12.5, -180.0..=180.0, "°", 0).value; + f.run(&mut app, vec![set(12.5)]); + assert_eq!(angle(&app), shown, "as the field shows 12.5"); + f.run(&mut app, vec![set(500.0)]); + assert_eq!(angle(&app), 180.0, "past the end"); + f.run(&mut app, vec![set(-12.0), set(-90.0)]); + assert_eq!(angle(&app), -90.0, "the last request"); + f.run(&mut app, vec![set(f64::NAN)]); + assert_eq!(angle(&app), -90.0, "not a number"); + f.run(&mut app, vec![set(30.0), set(f64::INFINITY)]); + assert_eq!(angle(&app), -90.0, "the last request is not a finite number"); +} + #[test] fn polar_grid_shared_canvas_click_defaults_units_counts_and_history() { use vectorcraft_doc::NodeId; diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index bd40e174d8..747de05cb1 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -42,6 +42,9 @@ pub struct SliderValue { /// steps from `value` (±1 for an arrow, ±10 with Shift or Page Up/Down). `None` steps to whole /// numbers. pub step: Option f64>, + /// The places the field shows, which a screen reader's set-value action rounds to; `None` + /// keeps the number it sets. + pub decimals: Option, } /// Two values are the same when they show the same number, range and text, whatever their keys' steps @@ -55,20 +58,20 @@ impl PartialEq for SliderValue { impl SliderValue { /// `value` on a rail over `range`, without a text. pub fn number(value: f64, range: std::ops::RangeInclusive) -> Self { - Self { value, range, text: None, step: None } + Self { value, range, text: None, step: None, decimals: None } } /// `value` on a rail over `range` as [`plain_field`] shows it with `suffix` and at most /// `decimals` places: the number it shows (`value` rounded) and its text. pub fn field(value: f64, range: std::ops::RangeInclusive, suffix: &str, decimals: usize) -> Self { let number = field_text(value, "", decimals); - Self { value: number.parse().unwrap_or(value), range, text: Some(format!("{number}{suffix}")), step: None } + Self { value: number.parse().unwrap_or(value), range, text: Some(format!("{number}{suffix}")), step: None, decimals: Some(decimals) } } /// `value` on a rail over `range`, with `text`, for a field that writes its own text (a length /// in the document's unit, an egui `DragValue`). pub fn text(value: f64, range: std::ops::RangeInclusive, text: String) -> Self { - Self { value, range, text: Some(text), step: None } + Self { value, range, text: Some(text), step: None, decimals: None } } /// This value, stepped by the keys with `step` instead of to whole numbers (see @@ -119,8 +122,10 @@ pub fn color_slider_valued( /// While it has the focus, → and ↑ raise the number `shown` holds to the next whole number and ← /// and ↓ lower it to the next whole number, Shift with an arrow, Page Up and Page Down add or take /// ten, and Home and End set the start and the end of `shown`'s range. Screen readers' increment -/// and decrement actions step the number as → and ← do. A number past the range steps from the -/// range's nearer end, and no step goes past either end. With `shown` `None` (a blank field), or +/// and decrement actions step the number as → and ← do, and their set-value action sets it within +/// the range, rounded to [`SliderValue::decimals`] (a value that is not a finite number leaves it +/// as it is). A number past the range steps from the range's nearer end, and no step goes past +/// either end. With `shown` `None` (a blank field), or /// in a disabled `ui`, the keys and actions leave the rail as it is. Returns the new value from 0 /// to 1 that a click or a drag gives, its phase, and the number in `shown`'s units that a key or /// an action gives. @@ -167,6 +172,7 @@ fn slider_keys(ui: &Ui, resp: &Response, shown: Option) -> Option) -> Option Option { - use egui::accesskit::Action; + use egui::accesskit::{Action, ActionData}; use egui::{Event, Key}; let (lo, hi) = (*s.range.start(), *s.range.end()); if !lo.is_finite() || !hi.is_finite() || hi <= lo { @@ -235,11 +241,30 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Some(value), + _ => None, + }) + .last() + .filter(|value| value.is_finite()); + if let Some(value) = set { + // The number the field would show, as `SliderValue::field` reads it. + let shown = s.decimals.map_or(value, |d| field_text(value, "", d).parse().unwrap_or(value)); + v = shown.clamp(lo, hi); + end = true; + exact = true; + } }); - (v != from || (end && v != s.value)).then_some(round_to(v, STEP_DECIMALS).clamp(lo, hi)) + (v != from || (end && v != s.value)).then_some(if exact { v } else { round_to(v, STEP_DECIMALS).clamp(lo, hi) }) } /// The rail of [`color_slider_valued`] with the id `id`: its response, the new value from 0 to 1 From d1e69239a75fc740abfdb574396a8065939d6091 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:00:46 -0800 Subject: [PATCH 087/482] Accessibility: a set value can reach a field's number past the rail The range screen readers get for a dialog slider takes in a field's number past the rail's end, and the set-value action now accepts that range too. --- crates/ui-egui/src/dialogs/tests.rs | 27 +++++++++++++++++++++++++-- crates/ui-egui/src/widgets/color.rs | 10 ++++++---- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 9b6365ac87..37a027e730 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2018,9 +2018,10 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { /// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the /// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to /// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite -/// number leaves the Angle as it is. +/// number leaves the Angle as it is. On a field past its rail's end, a set value can go as far as +/// the field's number. #[test] -fn screen_readers_set_the_blob_brush_angle() { +fn screen_readers_set_a_dialog_slider_number() { use egui::accesskit::{Action, ActionData, ActionRequest, TreeId}; let mut app = app(); app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); @@ -2055,6 +2056,28 @@ fn screen_readers_set_the_blob_brush_angle() { assert_eq!(angle(&app), -90.0, "not a number"); f.run(&mut app, vec![set(30.0), set(f64::INFINITY)]); assert_eq!(angle(&app), -90.0, "the last request is not a finite number"); + // A field past its rail's end extends the range screen readers get, and a set value can go + // that far: Transform Each's Horizontal Scale at 300% on a rail that ends at 200%. + app.ui.dialog = None; + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + app.ui.dialog.as_mut().expect("Transform Each is open").fields.insert("scaleH".into(), json!(300)); + let scale = |app: &VectorcraftApp| app.ui.dialog.as_ref().expect("Transform Each is open").f64("scaleH", f64::NAN); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (node, ..) = slider_node(&out, "Horizontal:"); + let set = |value: f64| { + egui::Event::AccessKitActionRequest(ActionRequest { + action: Action::SetValue, + target_node: node, + target_tree: TreeId::ROOT, + data: Some(ActionData::NumericValue(value)), + }) + }; + f.run(&mut app, vec![set(250.0)]); + assert_eq!(scale(&app), 250.0, "within the range screen readers get"); + f.run(&mut app, vec![set(400.0)]); + assert_eq!(scale(&app), 250.0, "past 250%, the range's end now"); } #[test] diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 747de05cb1..b982d1707f 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -123,8 +123,9 @@ pub fn color_slider_valued( /// and ↓ lower it to the next whole number, Shift with an arrow, Page Up and Page Down add or take /// ten, and Home and End set the start and the end of `shown`'s range. Screen readers' increment /// and decrement actions step the number as → and ← do, and their set-value action sets it within -/// the range, rounded to [`SliderValue::decimals`] (a value that is not a finite number leaves it -/// as it is). A number past the range steps from the range's nearer end, and no step goes past +/// the range they get (the range, extended to a number past its end), rounded to +/// [`SliderValue::decimals`] (a value that is not a finite number leaves it as it is). A number +/// past the range steps from the range's nearer end, and no step goes past /// either end. With `shown` `None` (a blank field), or /// in a disabled `ui`, the keys and actions leave the rail as it is. Returns the new value from 0 /// to 1 that a click or a drag gives, its phase, and the number in `shown`'s units that a key or @@ -247,7 +248,7 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Option Date: Wed, 4 Nov 2026 05:35:28 -0800 Subject: [PATCH 088/482] Accessibility: a set value in another unit keeps a number past the rail A dialog slider whose field shows another unit, such as Transform Each's Move in millimeters, converted the number back to points and held it to the rail's range, so a set value past the rail that the field holds came back as the rail's end. --- crates/ui-egui/src/dialogs/form.rs | 5 +++-- crates/ui-egui/src/dialogs/tests.rs | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index faad934c2a..333c9de1b2 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -813,8 +813,9 @@ pub(super) fn slider_rail_valued( let units = shown.as_ref().map(|s| s.range.clone()); let (dragged, _, keyed) = crate::widgets::color_slider_stepped(ui, ("dlg-slider", key), name, shown, ((v - min) / (max - min)) as f32, SLIDER_WIDTH, track); - let keyed = - keyed.zip(units).map(|(k, u)| if u == range { k } else { (min + (k - u.start()) / (u.end() - u.start()) * (max - min)).clamp(min, max) }); + // Not clamped to the rail: a screen reader's set value can reach a number past it that the + // field holds. + let keyed = keyed.zip(units).map(|(k, u)| if u == range { k } else { min + (k - u.start()) / (u.end() - u.start()) * (max - min) }); if let Some(n) = dragged.map(|x| (min + x as f64 * (max - min)).round()).or(keyed).filter(|n| *n != held) { d.fields.insert(key.into(), json!(n)); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 37a027e730..b52328dd1f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2078,6 +2078,23 @@ fn screen_readers_set_a_dialog_slider_number() { assert_eq!(scale(&app), 250.0, "within the range screen readers get"); f.run(&mut app, vec![set(400.0)]); assert_eq!(scale(&app), 250.0, "past 250%, the range's end now"); + // The same for a Move slider in millimeters, whose rail ends at 1000 pt: with the field at + // 1200 pt, 400 mm sets about 1134 pt. + app.ui.dialog = None; + app.run("document.setUnits", json!({"units": "millimeters"})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + app.ui.dialog.as_mut().expect("Transform Each is open").fields.insert("moveH".into(), json!(1200)); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let mut horizontal = nodes.iter().filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label() == Some("Horizontal:")); + let (node, _) = horizontal.nth(1).expect("the Move slider named Horizontal:"); + let request = + ActionRequest { action: Action::SetValue, target_node: *node, target_tree: TreeId::ROOT, data: Some(ActionData::NumericValue(400.0)) }; + f.run(&mut app, vec![egui::Event::AccessKitActionRequest(request)]); + let moved = app.ui.dialog.as_ref().expect("Transform Each is open").f64("moveH", f64::NAN); + assert!((moved - 400.0 * 72.0 / 25.4).abs() < 1e-6, "{moved} pt"); } #[test] From c743662add0573283ea443f1c8682924ef4357fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 05:46:56 -0800 Subject: [PATCH 089/482] Accessibility: a set-value request without a number leaves a dialog slider as it is --- crates/ui-egui/src/dialogs/tests.rs | 3 +++ crates/ui-egui/src/widgets/color.rs | 12 ++++-------- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index b52328dd1f..782b3de29e 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2056,6 +2056,9 @@ fn screen_readers_set_a_dialog_slider_number() { assert_eq!(angle(&app), -90.0, "not a number"); f.run(&mut app, vec![set(30.0), set(f64::INFINITY)]); assert_eq!(angle(&app), -90.0, "the last request is not a finite number"); + let empty = ActionRequest { action: Action::SetValue, target_node: node, target_tree: TreeId::ROOT, data: None }; + f.run(&mut app, vec![set(30.0), egui::Event::AccessKitActionRequest(empty)]); + assert_eq!(angle(&app), -90.0, "the last request has no number"); // A field past its rail's end extends the range screen readers get, and a set value can go // that far: Transform Each's Horizontal Scale at 300% on a rail that ends at 200%. app.ui.dialog = None; diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index b982d1707f..cb44bfe043 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -249,14 +249,10 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, s: &SliderValue) -> Option Some(value), - _ => None, - }) - .last() - .filter(|value| value.is_finite()); + let set = i.accesskit_action_requests(id, Action::SetValue).last().and_then(|request| match request.data { + Some(ActionData::NumericValue(value)) if value.is_finite() => Some(value), + _ => None, + }); if let Some(value) = set { // The number the field would show, as `SliderValue::field` reads it. let shown = s.decimals.map_or(value, |d| field_text(value, "", d).parse().unwrap_or(value)); From 69ef2a4e50afc3a9d83e9325f1e0a251bbd03279 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:06:43 -0800 Subject: [PATCH 090/482] Accessibility: a whole-number dialog slider rounds a set value --- crates/ui-egui/src/dialogs/form.rs | 3 ++- crates/ui-egui/src/dialogs/tests.rs | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index 333c9de1b2..8bfcef3d33 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -790,7 +790,8 @@ pub(super) fn slider_rail_named( range: std::ops::RangeInclusive, track: &dyn Fn(f32) -> egui::Color32, ) { - let shown = crate::widgets::SliderValue::number(d.f64(key, 0.0), range.clone()); + // Whole numbers, as a drag sets them. + let shown = crate::widgets::SliderValue { decimals: Some(0), ..crate::widgets::SliderValue::number(d.f64(key, 0.0), range.clone()) }; slider_rail_valued(ui, d, key, name, range, Some(shown), track); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 782b3de29e..56e59c7532 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2098,6 +2098,17 @@ fn screen_readers_set_a_dialog_slider_number() { f.run(&mut app, vec![egui::Event::AccessKitActionRequest(request)]); let moved = app.ui.dialog.as_ref().expect("Transform Each is open").f64("moveH", f64::NAN); assert!((moved - 400.0 * 72.0 / 25.4).abs() < 1e-6, "{moved} pt"); + // A slider without a field's places, Roughen's Detail, sets whole numbers as a drag does. + app.ui.dialog = None; + app.run("effect.dialog", json!({"effect": "distort.roughen"})).unwrap(); + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (node, ..) = slider_node(&out, "Detail:"); + let request = + ActionRequest { action: Action::SetValue, target_node: node, target_tree: TreeId::ROOT, data: Some(ActionData::NumericValue(12.4)) }; + f.run(&mut app, vec![egui::Event::AccessKitActionRequest(request)]); + assert_eq!(app.ui.dialog.as_ref().expect("Roughen is open").f64("detail", f64::NAN), 12.0); } #[test] From 985ef69cb76306ba3159d994110e26e1ebc91a57 Mon Sep 17 00:00:00 2001 From: FractalEncrypt <59615752+FractalEncrypt@users.noreply.github.com> Date: Wed, 4 Nov 2026 08:39:51 -0500 Subject: [PATCH 091/482] New Document: units belong to the chosen preset, not the whole tab Choosing units in Preset Details restyled every preset card in the Recent and Saved tabs, so switching between inches and millimetres rewrote all the user's templates at once. The pane's options apply to the selected preset (helpx, "Create and save custom document presets"), so only the chosen card follows the chosen units now; the others keep the units their document or preset was made in, and clicking one brings its units back. The built-in category tabs still show the chosen units (#2078). Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- ROADMAP.md | 1 + crates/ui-egui/src/dialogs/new_document.rs | 56 ++++++++++---- crates/ui-egui/src/panels/tests_units.rs | 86 +++++++++++++++++++++- docs/roadmap.md | 4 +- docs/target-app-parity.md | 3 +- docs/ui-parity.md | 3 +- 6 files changed, 136 insertions(+), 17 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6cf80d3628..16bd8b1dab 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -131,6 +131,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap ## Progress log +- 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`). - 2026-11-01: Find Nearest Swatch joins the Color Effects add-on (Object › Plug-ins › Color Effects): for each colour of the selection, the closest swatches of the document, a built-in library or a library or colour book the user loaded, with their CIEDE2000 difference; Apply gives each colour its nearest swatch as one undo step, linking global and spot swatches and adding a library's to the document first, so a process colour becomes the closest spot colour (`addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, #4923). diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 5d53ebe73e..1a4c393892 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -41,7 +41,8 @@ const PARAMS: [&str; 12] = [ "rasterEffectsPpi", "previewMode", ]; -/// The preset the fields were last filled from (its fields as `apply` set them). +/// The preset the fields were last filled from, as `apply` set them; a Recent or Saved card keeps +/// its own units here, which the units chosen in Preset Details don't change. const APPLIED: &str = "__applied"; /// Save Preset's name field is showing. const SAVING: &str = "__saving"; @@ -257,21 +258,50 @@ fn presets(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::vec2(12.0, 12.0); let (w, h, preset, units) = (d.f64("width", 0.0), d.f64("height", 0.0), d.str("preset"), unit(d)); + // The fields were last filled from this preset's card; Recent keeps one entry per size + // and units, so the units tell two entries of one size apart. + let chosen = d + .fields + .get(APPLIED) + .filter(|a| a.get("preset").and_then(Value::as_str) == Some(preset.as_str())) + .and_then(Value::as_object) + .cloned(); for s in &list { - // The built-in presets' cards show the chosen orientation (square sizes have none) - // and the units chosen in Preset Details; choosing one keeps both. Recent and Saved - // show each entry as it was made, so a portrait and a landscape A3 are two cards - // (#2860). - let mut s = DocSettings { units, ..s.clone() }; - if cat > 1 && ((w > h && s.height > s.width) || (h > w && s.width > s.height)) { - std::mem::swap(&mut s.width, &mut s.height); + // The built-in presets' cards show the chosen orientation (square sizes have none); + // Recent and Saved show each entry as it was made, so a portrait and a landscape A3 + // are two cards (#2860). + let mut card = s.clone(); + if cat > 1 && ((w > h && card.height > card.width) || (h > w && card.width > card.height)) { + std::mem::swap(&mut card.width, &mut card.height); } - let selected = d.fields.contains_key(APPLIED) && s.name == preset && s.width == w && s.height == h; - let card = preset_card(ui, &s, selected); - if card.clicked() || card.double_clicked() { - apply(d, &s); + // The built-in presets all share the units chosen in Preset Details. + if cat > 1 { + card.units = units; } - create |= card.double_clicked(); + let selected = chosen.as_ref().is_some_and(|a| { + a.get("preset").and_then(Value::as_str) == Some(card.name.as_str()) + && a.get("width").and_then(Value::as_f64) == Some(card.width) + && a.get("height").and_then(Value::as_f64) == Some(card.height) + && (cat > 1 || a.get("units").and_then(Value::as_str) == Some(s.units.label())) + }); + // The chosen card shows the units chosen in Preset Details, which the new document + // will have (#2078); the others keep their own, so choosing one document's units + // doesn't restyle the whole tab. + if selected { + card.units = units; + } + let resp = preset_card(ui, &card, selected); + if resp.clicked() || resp.double_clicked() { + apply(d, &card); + // The card is still the entry it was, whatever units it shows: its own units say + // which entry it is, so a chosen card stays chosen after a units change. + if cat < 2 + && let Some(Value::Object(a)) = d.fields.get_mut(APPLIED) + { + a.insert("units".into(), json!(s.units.label())); + } + } + create |= resp.double_clicked(); } }); }); diff --git a/crates/ui-egui/src/panels/tests_units.rs b/crates/ui-egui/src/panels/tests_units.rs index da5be17f4d..687174e839 100644 --- a/crates/ui-egui/src/panels/tests_units.rs +++ b/crates/ui-egui/src/panels/tests_units.rs @@ -5,7 +5,7 @@ use serde_json::json; use vectorcraft_doc::Unit; -use super::tests_appearance::{app_with_rect, frame_events, run}; +use super::tests_appearance::{app_with_rect, click, frame_events, run, text_rect}; use super::*; /// Every text drawn in the second headless frame of `f` (windows size themselves in the first). @@ -171,3 +171,87 @@ fn new_document_cards_follow_the_chosen_units() { assert!(shows(&t, "288 × 432 px") && !shows(&t, "101.6 × 152.4 mm"), "Postcard in px: {t:?}"); assert_eq!(app.ui.dialog.as_ref().unwrap().fields["preset"], json!("Postcard")); } + +/// Choosing units in Preset Details changes the chosen document, not every recent one: each card +/// keeps the units its document was made in, so switching between inches and millimetres leaves the +/// other templates as they were; choosing another card brings its units back. +#[test] +fn recent_cards_keep_their_own_units() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + // 8.5 × 11 in, then 210 × 297 mm, which Recent lists first and the dialog opens on. + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "210 mm", "height": "297 mm", "units": "Millimeters"})); + app.run("file.newDialog", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["units"], json!("Millimeters")); + app.ui.dialog.as_mut().unwrap().fields.insert("units".into(), json!("Points")); + let t = dialog_texts(&mut app); + assert!(shows(&t, "595.276 × 841.89 pt"), "the chosen entry in points: {t:?}"); + assert!(shows(&t, "8.5 × 11 in"), "the other entry keeps its inches: {t:?}"); + assert!(!shows(&t, "612 × 792 pt"), "the inches entry isn't turned into points: {t:?}"); + // Clicking the inches card makes it the chosen one, in its own units. + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let inches = text_rect(&frame_events(&ctx, &mut app, vec![], &mut draw), "8.5 × 11 in").center(); + click(&ctx, &mut app, inches, &mut draw); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.fields["units"], json!("Inches")); + assert_eq!((d.fields["width"].clone(), d.fields["height"].clone()), (json!(612.0), json!(792.0))); +} + +/// A saved preset keeps the units it was saved in too, whichever units the dialog is showing. +#[test] +fn saved_cards_keep_their_own_units() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + run(&mut app, "file.newPresets.save", json!({"name": "A4 mm", "width": "210 mm", "height": "297 mm", "units": "Millimeters"})); + app.run("file.newDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("category".into(), json!("Saved")); + d.fields.insert("units".into(), json!("Points")); + let t = dialog_texts(&mut app); + assert!(shows(&t, "210 × 297 mm") && !shows(&t, "595.276 × 841.89 pt"), "the saved preset keeps millimetres: {t:?}"); +} + +/// Clicking the card that is already chosen leaves it chosen, in the units the dialog is showing: +/// the entry's own units still say which card it is. +#[test] +fn clicking_the_chosen_recent_card_keeps_it_chosen() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + app.run("file.newDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("units".into(), json!("Points")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let card = text_rect(&frame_events(&ctx, &mut app, vec![], &mut draw), "612 × 792 pt").center(); + click(&ctx, &mut app, card, &mut draw); + let t = dialog_texts(&mut app); + assert!(shows(&t, "612 × 792 pt") && !shows(&t, "8.5 × 11 in"), "the card stays chosen in points: {t:?}"); +} + +/// Recent keeps one entry per size and units, so two entries can be one size in two units: the +/// chosen card is the entry the fields were filled from, not every card of that size. +#[test] +fn recent_entries_of_one_size_in_two_units_stay_apart() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + // Both are 612 × 792 pt; Recent lists the points one first, which the dialog opens on. + run(&mut app, "file.new", json!({"width": "8.5 in", "height": "11 in", "units": "Inches"})); + run(&mut app, "file.new", json!({"width": "612 pt", "height": "792 pt", "units": "Points"})); + app.run("file.newDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("units".into(), json!("Inches")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut draw = |app: &mut VectorcraftApp, ui: &mut Ui| crate::dialogs::show(app, ui.ctx()); + frame_events(&ctx, &mut app, vec![], &mut draw); // the window sizes itself here + let texts = frame_events(&ctx, &mut app, vec![], &mut draw); + let mut cards: Vec = texts.iter().filter(|(t, _)| t == "8.5 × 11 in").map(|(_, r)| *r).collect(); + cards.sort_by(|a, b| a.center().x.total_cmp(&b.center().x)); + assert_eq!(cards.len(), 2, "both cards read in inches: {texts:?}"); + // The right-hand card is the inches entry: choosing it leaves the points entry in points. + click(&ctx, &mut app, cards[1].center(), &mut draw); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["units"], json!("Inches")); + let t = dialog_texts(&mut app); + assert!(shows(&t, "612 × 792 pt"), "the points entry keeps its points: {t:?}"); +} diff --git a/docs/roadmap.md b/docs/roadmap.md index c75e857b0c..cf8cf6a5de 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-03 · **Change:** minor (OpenType panel offers font-defined Stylistic Sets; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (New Document's units belong to the chosen preset; Recent and Saved cards keep their own units; 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-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. | | 2026-11-03 | minor | M1: Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot; estimates unchanged. | | 2026-11-03 | minor | New gradients use CMYK default stops in CMYK documents, including Gradient tool creation. Scores and estimates unchanged. | | 2026-10-30 | minor | M4: G9: `.ai`/EPS editing data: a blend takes the transparency (opacity, blend mode, knockout) in its state block after its record, so its steps knock each other out as the page draws them; a user's file comes in 0.6% from its page instead of 1.3%. Scores and estimates unchanged. | @@ -158,6 +159,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-04 | minor | New Document: the units chosen in Preset Details belong to the chosen preset; Recent and Saved cards keep their own units; scores and estimates unchanged. | | 2026-11-03 | minor | M7: the OpenType panel offers the selected font's available Stylistic Sets with custom or numbered names; estimates unchanged. | | 2026-11-03 | minor | M1: Enclosing Lasso adds freehand whole-object selection under Object › Plug-ins; estimates unchanged. | | 2026-11-02 | minor | Font-family fields in Character, Properties and Control step selected text with the wheel (#5253), with one undo step per notch; scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 849d7fa00c..02329b46d1 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-04 · **Change:** minor (Document Tools add-on: Batch Trace Folder, #4921; 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-04 · **Change:** minor (New Document's units belong to the chosen preset; Recent and Saved cards keep their own units; 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-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. | | 2026-11-04 | minor | Document Tools add-on (a VectorCraft addition): Batch Trace Folder under Object › Plug-ins (`addon.document.batchTraceFolder`, #4921); evidence added; scores unchanged. | | 2026-11-04 | minor | Object › Expand turns selected symbol instances into their art as Break Link places it, one level deep, with the Expand dialog's Fill and Stroke reaching that art. Scores and estimates unchanged. | | 2026-11-03 | minor | The OpenType panel offers the selected font's stylistic sets by custom or numbered name, and allows several to be active. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 62d62e5d92..26f56b16f1 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 (Document Tools add-on: Batch Trace Folder under Object › Plug-ins, #4921; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (New Document's units belong to the chosen preset; Recent and Saved cards keep their own units; 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) ## Feature submission evidence @@ -423,6 +423,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 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 | | 2026-11-04 | minor | Area type: Align Top / Center / Bottom / Justify Vertically buttons in the Properties panel (Paragraph section) and the Control panel set its vertical alignment in the frame, as Area Type Options does; turned off for frames with rows or columns and threaded frames (#3759); scores and estimates unchanged | From dc9b2f087f3c88c0fad093ce8b0e9c36453e0214 Mon Sep 17 00:00:00 2001 From: FractalEncrypt <59615752+FractalEncrypt@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:07:46 -0500 Subject: [PATCH 092/482] Contributors: credit FractalEncrypt by their GitHub profile name Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index f4e508fdf5..7a90cd6524 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -201,3 +201,6 @@ sync_github_name = false [people.FrancoJacquet] real_name = "Franco Jacquet" + +[people.FractalEncrypt] +sync_github_name = true From 292b385a667dbef8f6ad5eab89ddb3daaf8a788e Mon Sep 17 00:00:00 2001 From: bflatastic Date: Wed, 4 Nov 2026 21:46:27 +0700 Subject: [PATCH 093/482] Tests: the font menu and idle-socket tests don't fail on a busy machine MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit type_font_menu_lists_every_available_family compared two reads of Type › Font while a test running alongside could add a font in between, so the menu was rebuilt with one more family. It now judges a run in which the font generation held still. idle_expiry_closes_without_writing_a_line took a connection reset as a failure; on Windows the server's close of an idle connection can reach the client as one. --- apps/vectorcraft/src/control_server/tests.rs | 7 +++++- crates/ui-egui/src/tests/fonts.rs | 24 +++++++++++++++----- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/apps/vectorcraft/src/control_server/tests.rs b/apps/vectorcraft/src/control_server/tests.rs index aad5d7d083..d991fd6028 100644 --- a/apps/vectorcraft/src/control_server/tests.rs +++ b/apps/vectorcraft/src/control_server/tests.rs @@ -58,7 +58,12 @@ fn idle_control_socket_releases_its_worker() { fn idle_expiry_closes_without_writing_a_line() { let (mut client, done, worker) = socket_fixture(short_timeouts(), |_, _| panic!("no request expected")); let mut got = Vec::new(); - client.read_to_end(&mut got).unwrap(); + match client.read_to_end(&mut got) { + // On Windows the server's close can reach the client as a reset. + Err(e) if e.kind() == std::io::ErrorKind::ConnectionReset => {} + Ok(_) => {} + Err(e) => panic!("reading the idle connection: {e}"), + } assert_eq!(String::from_utf8_lossy(&got), "", "the app wrote to an idle connection"); expect_socket_deadline(client, done, worker); } diff --git a/crates/ui-egui/src/tests/fonts.rs b/crates/ui-egui/src/tests/fonts.rs index 182de9f0d4..f8f019171e 100644 --- a/crates/ui-egui/src/tests/fonts.rs +++ b/crates/ui-egui/src/tests/fonts.rs @@ -13,14 +13,26 @@ fn type_font_menu_lists_every_available_family() { let fonts = |app: &VectorcraftApp| -> Vec { menus::menu_entries(app).into_iter().filter(|e| e.path == ["Type", "Font"]).map(|e| e.label).collect() }; - let labels = fonts(&app); - assert_eq!(labels, *FontDb::global().menu_family_list()); let installed = FontDb::with_font_dirs(system_font_dirs()); installed.load_system_fonts(); - let missing: Vec = installed.menu_family_list().iter().filter(|f| !labels.contains(f)).cloned().collect(); - assert!(missing.is_empty(), "installed but not in Type › Font: {missing:?}"); - // The menu is built every frame, from a list built once. - assert_eq!(fonts(&app), labels); + // A test running alongside can add a font (and the installed fonts' scan can end), and the menu + // is then built again: judge a run in which the fonts held still. + for _ in 0..20 { + let generation = FontDb::global().generation(); + let labels = fonts(&app); + let listed = FontDb::global().menu_family_list(); + // The menu is built every frame, from a list built once. + let again = fonts(&app); + if FontDb::global().generation() != generation { + continue; + } + assert_eq!(labels, *listed); + let missing: Vec = installed.menu_family_list().iter().filter(|f| !labels.contains(f)).cloned().collect(); + assert!(missing.is_empty(), "installed but not in Type › Font: {missing:?}"); + assert_eq!(again, labels); + return; + } + panic!("the fonts kept changing"); } #[test] From ebbbf29f1ef0de36de0c86af525e5883748ad5e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:19:22 -0800 Subject: [PATCH 094/482] Gradient: Perceptual spot ink mixes stay continuous from red to blue Mixed in display RGB, red and blue darken past blue's lightness and come back. The weight search for a Perceptual DeviceN shading then found a red-side weight for stops near the blue stop, and the inks jumped there. When the display RGB mix's lightness turns back between two stops, the inks are mixed at each stop's mix position instead. --- crates/color/src/gradient.rs | 21 +++++++++++++++++---- crates/color/src/gradient/tests.rs | 19 +++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 652db3340b..794f92aeea 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -86,6 +86,9 @@ const TINT_STEPS: u32 = 16; const MIN_INK_LIGHTNESS_SPAN: f64 = 1.0 / 255.0; /// Most stops on a gradient's curve that [`Gradient::ink_tints`] finds tints for. const MAX_INK_TINTS: usize = 4096; +/// How many even steps [`Gradient::ink_mixes`] checks the lightness of two stops' display RGB mix +/// at, to tell whether it moves steadily from one stop's lightness to the other's. +const INK_MIX_STEPS: u32 = 64; /// The mix positions (0..1, after `v0`, before `v1`) between which display RGB mixed linearly /// stays within [`PERCEPTUAL_TOLERANCE`] of the perceptual mix of `a` and `b`: the span halved @@ -401,8 +404,10 @@ impl Gradient { /// The weight is the one at which the two stops' colors mixed in display RGB have the OKLab /// lightness of the color on the curve there, found to [`TINT_STEPS`] halvings, or the mix /// position itself when the two colors' lightness differs by less than - /// [`MIN_INK_LIGHTNESS_SPAN`]. `None` for a Classic gradient, and when the curve has more than - /// [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). + /// [`MIN_INK_LIGHTNESS_SPAN`], or when the display RGB mix's lightness turns back somewhere + /// on the way from one color's lightness to the other's (checked at [`INK_MIX_STEPS`] even + /// steps), as from red to blue. `None` for a Classic gradient, and when the curve has more + /// than [`MAX_INK_TINTS`] stops ([`Self::fits_ink_tints`]). pub fn ink_mixes(&self) -> Option> { use crate::libraries::srgb_to_oklab; if self.method.is_classic() || !self.fits_ink_tints() { @@ -414,8 +419,16 @@ impl Gradient { out.push((s.offset, i, 0.0, s.opacity)); let Some(n) = self.stops.get(i + 1) else { continue }; let (l0, l1) = (lightness(&s.color), lightness(&n.color)); + let mixed_lightness = |w: f32| lightness(&GradientMethod::Classic.mix(&s.color, &n.color, w)); + // The mix position itself when the lightness doesn't tell the mixes apart. + let by_position = (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN + || !(0..=INK_MIX_STEPS) + .map(|k| mixed_lightness(k as f32 / INK_MIX_STEPS as f32)) + .collect::>() + .windows(2) + .all(|w| (w[1] - w[0]) * (l1 - l0) >= 0.0); for v in perceptual_mixes(s, n) { - let weight = if (l1 - l0).abs() < MIN_INK_LIGHTNESS_SPAN { + let weight = if by_position { v } else { let want = lightness(&self.method.mix(&s.color, &n.color, v)); @@ -423,7 +436,7 @@ impl Gradient { for _ in 0..TINT_STEPS { let mid = (lo + hi) / 2.0; // The mix at `mid` has not yet gone from stop `i`'s lightness to the wanted one. - if (lightness(&GradientMethod::Classic.mix(&s.color, &n.color, mid)) - want) * (l1 - l0) < 0.0 { + if (mixed_lightness(mid) - want) * (l1 - l0) < 0.0 { lo = mid; } else { hi = mid; diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs index 1e75feb335..1005b84300 100644 --- a/crates/color/src/gradient/tests.rs +++ b/crates/color/src/gradient/tests.rs @@ -585,3 +585,22 @@ fn ink_mixes_follow_the_perceptual_curve() { g.stops = (0..n).map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { magenta } else { Color::WHITE })).collect(); assert_eq!(g.ink_mixes(), None); } + +/// From red to blue the display RGB mix darkens past blue's lightness and comes back, so a +/// weight found by lightness near the blue stop would be a red-side one and the inks would jump +/// there. The weights are the mix positions instead, and reach the blue stop's inks steadily. +#[test] +fn ink_mixes_use_the_mix_position_when_the_lightness_turns_back() { + let (red, blue) = (Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)); + let mut g = Gradient::new(GradientKind::Linear, vec![GradientStop::new(0.0, red), GradientStop::new(1.0, blue)]); + g.method = GradientMethod::Perceptual; + let mixes = g.ink_mixes().expect("a Perceptual gradient's curve"); + assert_eq!(mixes[mixes.len() - 1], (1.0, 1, 0.0, 1.0), "the blue stop"); + let between: Vec<_> = mixes.iter().filter(|m| m.1 == 0 && m.0 > 0.0).collect(); + assert!(!between.is_empty(), "stops on the curve between red and blue: {mixes:?}"); + // With the midpoint at ½, a stop's offset on the curve is its mix position. + for (t, _, w, _) in &between { + assert!((w - t).abs() < 1e-6, "at {t}: weight {w}"); + } + assert!(mixes.windows(2).filter(|p| p[1].1 == 0).all(|p| p[0].2 <= p[1].2), "the weights rise: {mixes:?}"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 02329b46d1..fe801adcce 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1387,7 +1387,7 @@ applies to fills). Tests: `color::gradient::tests` (perceptual midpoint, expansi `pdf::tests::dithered_perceptual_gradients_export_as_images_with_noise_on_the_fill` and the Gradient panel's `the_method_menu_makes_the_gradient_perceptual`. Scores and hours unchanged. -PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there (VectorCraft's own rule). Dithered fills, freeform gradients, Perceptual gradients that mix a spot color with RGB or Lab stops, and Perceptual gradients whose curve has more than 4,096 stops once expanded (VectorCraft's own limit) are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve` and `ink_mixes_follow_the_perceptual_curve`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. +PDF export writes a Perceptual linear or radial gradient whose stops are tints of one spot color (and paper white) as a Separation shading in that ink instead of an image, so the ink keeps its plate ([swatches](https://helpx.adobe.com/illustrator/using/using-creating-swatches.html); [separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html)). Its tints follow the curve's stops, each the tint with the OKLab lightness of the color there (VectorCraft's own rule). A Perceptual gradient that mixes spot colors with each other or with CMYK or gray stops is written as a DeviceN shading of its inks: at each stop on the curve, the inks of the two stops on either side are mixed at the weight where the two colors mixed in display RGB have the OKLab lightness of the color there, or at the stop's mix position between the two colors when that mix's lightness turns back on the way from one color to the other, as from red to blue (VectorCraft's own rule). Dithered fills, freeform gradients, Perceptual gradients that mix a spot color with RGB or Lab stops, and Perceptual gradients whose curve has more than 4,096 stops once expanded (VectorCraft's own limit) are still images, and the export warns that their spot colors are written in process colors. Tests: `color::gradient::tests::ink_tints_follow_the_perceptual_curve`, `ink_mixes_follow_the_perceptual_curve` and `ink_mixes_use_the_mix_position_when_the_lightness_turns_back`, `engine::tests::linked_stops::perceptual_spot_gradients_export_as_separation_shadings`, `perceptual_spot_gradients_mixed_with_other_inks_export_as_device_n_shadings` and `spot_gradients_drawn_as_images_warn`. In these Separation and DeviceN shadings, a white stop linked to a swatch that is not a spot color (a global White swatch, for example) is paper white, 0% of the ink, as an unlinked white stop is, so a gradient of one spot ink and such a stop stays a Separation shading; a stop linked to a white spot color stays a stop of that ink (VectorCraft's own rule). Test: `engine::tests::linked_stops::white_stops_linked_to_process_swatches_are_paper_in_spot_gradients`. From a883874a7341231f1b61f1bd8a56640fb3e57bb7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:20:29 -0800 Subject: [PATCH 095/482] Type: Touch Type moves an upright character in vertical type down and across its column An upright glyph in vertical type has its frame's up axis along its column, parallel to the line, so Touch Type split no drag or arrow-key nudge into kerning and baseline shift and sent no movement. Such a glyph now takes the line's cross axis, right of its column, as the way baseline shift moves it. --- crates/tools/src/touchtype.rs | 10 ++++++++-- crates/tools/src/touchtype/tests.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/touchtype.rs b/crates/tools/src/touchtype.rs index c1184d72a6..172487c197 100644 --- a/crates/tools/src/touchtype.rs +++ b/crates/tools/src/touchtype.rs @@ -58,7 +58,8 @@ struct CharBox { pivot: Point, /// A unit vector along its line in reading order. along: Vec2, - /// A unit vector up from its line, without its rotation: the way baseline shift moves it. + /// A unit vector up from its line, without its rotation: the way baseline shift moves it. For + /// a glyph standing upright in vertical type, the line's cross axis (right of its column). up: Vec2, /// The glyph's own x axis and its up axis (with its rotation), unit vectors. ex: Vec2, @@ -174,6 +175,11 @@ fn char_box(t: &TextObject, lay: &TextLayout, gi: usize) -> Option { } let quad = [m * Point::new(x0, y0), m * Point::new(x1, y0), m * Point::new(x1, y1), m * Point::new(x0, y1)]; let d = Vec2::new(g.angle.cos(), g.angle.sin()); + // Up from the glyph's frame without its rotation. For a glyph standing upright in vertical + // type, that up runs along the column, so the glyph takes the line's cross axis instead: the + // way baseline shift moves the column's sideways glyphs. + let up = unit(linear(m * g.unturned, Vec2::new(0.0, -1.0))); + let up = if d.cross(up).abs() > 1e-6 { up } else { Vec2::new(d.y, -d.x) }; let style = edit::slice_runs(&t.runs, g.byte, g.byte + g.len).first().map(|r| r.style.clone())?; Some(CharBox { start: g.byte, @@ -181,7 +187,7 @@ fn char_box(t: &TextObject, lay: &TextLayout, gi: usize) -> Option { pen, pivot: m * g.pivot, along: if g.rtl { -d } else { d }, - up: unit(linear(m * g.unturned, Vec2::new(0.0, -1.0))), + up, ex, ey, kerned: lay.glyphs.iter().any(|h| h.line == g.line && h.len > 0 && h.byte + h.len == g.byte && h.rtl == g.rtl), diff --git a/crates/tools/src/touchtype/tests.rs b/crates/tools/src/touchtype/tests.rs index 99388178ec..3b551950d1 100644 --- a/crates/tools/src/touchtype/tests.rs +++ b/crates/tools/src/touchtype/tests.rs @@ -176,6 +176,35 @@ fn a_character_rotated_near_a_quarter_turn_moves_across_its_line() { } } +/// In vertical type, a character standing upright (§) still splits a drag into kerning down its +/// column and baseline shift across it: down 10 pt and right 4 pt is `dx` 10 and `dy` 4. Every +/// arrow key nudges it. +#[test] +fn an_upright_character_in_vertical_type_moves_down_and_across_its_column() { + let (mut d, id, s) = doc_with_type(); + if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) { + **t = TextObject::point(Point::new(100.0, 200.0), "l§", CharStyle { size: 40.0, ..Default::default() }); + t.vertical = true; + } + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = TouchTypeTool { target: Some((id, 1)), ..Default::default() }; + let q = quad(&t, &cx); + let at = q[0].midpoint(q[2]); + let acts = drag(&mut t, &cx, at, at + Vec2::new(4.0, 10.0)); + let p1 = preview(&acts[1]); + assert!(close(p1["dx"].as_f64().unwrap_or(0.0), 10.0) && close(p1["dy"].as_f64().unwrap_or(0.0), 4.0), "{p1}"); + for key in [ToolKey::Up, ToolKey::Down, ToolKey::Left, ToolKey::Right] { + let acts = t.key(&cx, key, Mods::default()); + let moved = match acts.first() { + Some(Action::Exec(c, v)) if c == "text.touchType" => v, + other => panic!("{key:?}: {other:?}"), + }; + let parts = [&moved["dx"], &moved["dy"]].map(|v| v.as_f64().unwrap_or(0.0).abs()); + assert!(close(parts[0] + parts[1], 1.0) && (close(parts[0], 0.0) || close(parts[1], 0.0)), "{key:?}: {moved}"); + } +} + /// In type scaled unevenly, a drag's parts are measured in document points: right 10 pt and up 4 /// pt of a quarter-turned character is `dx` 10 and `dy` 4. #[test] From d639508a9a867603a2618db946ce5e345078a153 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:15:59 -0800 Subject: [PATCH 096/482] Type: baseline shift moves an upright glyph across the column in vertical type Baseline shift on an upright glyph in vertical type moved it up the column instead of across it, at any Character Rotation, because the shift was applied before the glyph was turned upright. The shift is now taken off before the turn and put back after it, so an upright glyph moves across the column by the shift as a letter lying on its side does, and still turns about its shifted pen position. --- crates/text/src/layout.rs | 8 +++++-- crates/text/src/tests/vertical.rs | 35 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs index 38688b8ce5..b814506e6d 100644 --- a/crates/text/src/layout.rs +++ b/crates/text/src/layout.rs @@ -327,10 +327,14 @@ impl Ctx<'_> { } else if self.vertical && stands_upright(g) { let next = self.out.glyphs.len(); let after_base = self.out.glyphs.last().is_some_and(|p| p.byte == g.byte && p.line == line && p.len > 0); + // Baseline shift moves it across the column at any Character Rotation: the shift is + // taken off before the turn and put back after it. + let shift = pre * Point::new(0.0, -g.bshift) - pre * Point::ZERO; + let (shift, unshift) = (Affine::translate(shift), Affine::translate(-shift)); if let Some((_, _, turn, after)) = cluster.filter(|c| c.0 == g.byte && c.1 == next && after_base && g.len > 0) { // A later glyph of an upright glyph's cluster: set after it as the shaper placed // it, and turned with it. - m = turn * Affine::translate((after - origin.x, 0.0)) * m; + m = shift * turn * Affine::translate((after - origin.x, 0.0)) * unshift * m; self.upright_cluster = Some((g.byte, next + 1, turn, after)); } else { // Turned about the centre of its cell, which the column's centre line runs through: @@ -342,7 +346,7 @@ impl Ctx<'_> { // turning point instead would move it across the column too). let turn = Affine::translate((-g.lead, 0.0)) * Affine::rotate_about(-std::f64::consts::FRAC_PI_2, Point::new(origin.x + cell * 0.5, origin.y - upright_centre(g, cell, em))); - m = turn * m; + m = shift * turn * unshift * m; // Its own advance across, from where the cell centres it: where the shaper set the // next glyph of its cluster. let across = g.face.advance(g.gid) * g.sx; diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index 9c9d616815..c0a2b5e13f 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -343,6 +343,41 @@ fn tracking_spaces_upright_marks_without_moving_them_off_the_centre_line() { assert!((step - 24.0).abs() < 1e-6, "one em plus 200/1000 em of tracking: {step}"); } +/// Baseline shift moves an upright glyph across the column, as it moves a letter lying on its +/// side, at any Character Rotation, and leaves its neighbors where they are. The glyph turns about +/// its shifted pen position (`xf * pivot`), and `xf * unturned` places the shifted glyph without +/// its rotation. +#[test] +fn baseline_shift_moves_an_upright_glyph_across_the_column() { + let at = |byte: usize, rotation: f64, shift: f64| { + let mut t = vertical("§l§"); + edit::style_range(&mut t.runs, byte, byte + "§l§"[byte..].chars().next().map_or(1, char::len_utf8), |s| { + s.rotation = rotation; + s.baseline_shift = shift; + }); + layout(FontDb::global(), &t) + }; + let centre = |l: &TextLayout, byte: usize| l.glyphs.iter().find(|g| g.byte == byte).map(|g| g.outline.bounding_box().center()).unwrap(); + // The letter lying on its side moves across the column by the shift. + let across = centre(&at(2, 0.0, 10.0), 2) - centre(&at(2, 0.0, 0.0), 2); + assert!((across.x.abs() - 10.0).abs() < 1e-6 && across.y.abs() < 1e-6, "{across:?}"); + for rotation in [0.0, 30.0, 90.0, -90.0] { + let (plain, shifted) = (at(3, rotation, 0.0), at(3, rotation, 10.0)); + let moved = centre(&shifted, 3) - centre(&plain, 3); + assert!((moved - across).hypot() < 1e-6, "{rotation}°: {moved:?}, across {across:?}"); + for byte in [0, 2] { + assert!((centre(&shifted, byte) - centre(&plain, byte)).hypot() < 1e-6, "{rotation}°: byte {byte} moved"); + } + let (p, s) = (plain.glyphs.iter().find(|g| g.byte == 3).unwrap(), shifted.glyphs.iter().find(|g| g.byte == 3).unwrap()); + let turn_at = s.xf * s.pivot - p.xf * p.pivot; + assert!((turn_at - across).hypot() < 1e-6, "{rotation}°: turns about a point moved by {turn_at:?}"); + let unrotated = at(3, 0.0, 10.0); + let u = unrotated.glyphs.iter().find(|g| g.byte == 3).unwrap(); + let (a, b) = ((s.xf * s.unturned).as_coeffs(), u.xf.as_coeffs()); + assert!(a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-6), "{rotation}°: {a:?} vs {b:?}"); + } +} + /// Character panel menu › Tate-chu-yoko: a marked run stands across one em of the column, including /// a number longer than three digits and Latin letters. Unmarked text keeps the automatic rule /// (two or three digits only). Horizontal type stores the mark and does not move the letters. From eb03e8943fbdc88f0b10c02108a2e7f676df125f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:28:00 -0800 Subject: [PATCH 097/482] Gradient: PDF shading notes name linear and radial gradients and DeviceN The PDF writer writes a spot gradient as a Separation or DeviceN shading only when it is linear or radial; freeform gradients and dithered fills are written as images in process colors. - `paint.editGradient`'s method help and the Method paragraph in docs/mcp.md limit the Perceptual exception to linear and radial gradients. - The Linked gradient stops paragraph in docs/mcp.md no longer says the writer has no DeviceN: a gradient mixing spot inks with other spot, CMYK or gray inks exports as a DeviceN shading, and only a mix with RGB or Lab colors is written in process colors, with a warning. --- crates/engine/src/cmd/gradient.rs | 2 +- docs/mcp.md | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index fde35136c4..b217ade5d0 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white, CMYK or gray, it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg, aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient", has_doc, edit_gradient ), diff --git a/docs/mcp.md b/docs/mcp.md index 915d0ef8a1..8f72dc23ac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -924,9 +924,10 @@ SVG and PDF exports write such a fill as an image at the Document Raster Effects Method (the Gradient panel's menu): `classic` (the default) mixes the colours between stops in display RGB, `perceptual` mixes a linear or radial gradient's colours in OKLab so the steps look even. SVG exports write a Perceptual gradient as an image at the Document Raster Effects resolution (a dithered Perceptual fill with its noise). -PDF exports write it the same way, except for a gradient with spot color stops whose other stops are all paper white, -CMYK or gray, that is not a dithered fill and whose curve does not have too many stops. PDF writes tints of one spot -ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading. +PDF exports write it the same way, except for a linear or radial gradient with spot color stops whose other stops +are all paper white, CMYK or gray, that is not a dithered fill and whose curve does not have too many stops. PDF +writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray +inks as a DeviceN shading. `paint.setFill`/`paint.setStroke` take it in `gradient` too: ```json @@ -2777,9 +2778,11 @@ Applying a gradient swatch (`paint.setFill {swatch}`) records it as the gradient highlights it; new stops drop the link). A gradient stop can link to a global or spot swatch like a solid colour: give it `swatch` (and `tint` %, default 100 or a tint swatch's own) instead of `color` in `paint.editGradient {stops}` or a `gradient` paint's stops. Editing or deleting the swatch then recolours or unlinks the stop, in art and -in gradient swatches. A spot stop separates on its plate; a gradient whose stops are all tints of one spot ink (or -paper white, 0 %) exports to PDF as a Separation shading (the writer has no DeviceN, so a gradient mixing a spot -ink with other colours is written in process colours, with a warning). +in gradient swatches. A spot stop separates on its plate. A linear or radial gradient whose stops are all tints of one spot ink (or +paper white, 0 %) exports to PDF as a Separation shading, and one that mixes spot inks with other spot, CMYK or gray +inks exports as a DeviceN shading. A gradient that mixes a spot ink with RGB or Lab colours is written in process +colours, with a warning. Freeform gradients and dithered fills export to PDF as images in process colours, and Method +above covers Perceptual gradients. ```json {"name":"run_command","arguments":{"command":"paint.editGradient","params":{"stops":[{"offset":0,"swatch":"Ink"},{"offset":1,"swatch":"Ink","tint":20}]}}} From 204b57e0460523818ae2b5e4ae5d86c515739f9e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:31:32 -0800 Subject: [PATCH 098/482] Docs: American spelling in the PDF shading notes --- docs/mcp.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 8f72dc23ac..bd73b26582 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2780,8 +2780,8 @@ give it `swatch` (and `tint` %, default 100 or a tint swatch's own) instead of ` {stops}` or a `gradient` paint's stops. Editing or deleting the swatch then recolours or unlinks the stop, in art and in gradient swatches. A spot stop separates on its plate. A linear or radial gradient whose stops are all tints of one spot ink (or paper white, 0 %) exports to PDF as a Separation shading, and one that mixes spot inks with other spot, CMYK or gray -inks exports as a DeviceN shading. A gradient that mixes a spot ink with RGB or Lab colours is written in process -colours, with a warning. Freeform gradients and dithered fills export to PDF as images in process colours, and Method +inks exports as a DeviceN shading. A gradient that mixes a spot ink with RGB or Lab colors is written in process +colors, with a warning. Freeform gradients and dithered fills export to PDF as images in process colors, and Method above covers Perceptual gradients. ```json From ef5a4d967a4893a7a1586127c900e9b3d8d5ec79 Mon Sep 17 00:00:00 2001 From: Don Omondi <282319807+mockydevs@users.noreply.github.com> Date: Wed, 4 Nov 2026 09:46:07 -0500 Subject: [PATCH 099/482] Fix #5502: Export As PNG exports the active artboard, not always the first File > Export > Export As PNG... opened PNG Options with no artboard chosen, and a single-image export without one writes the first artboard, whichever was in use. With no artboard choice given, it now takes the active artboard, or each artboard the Artboard tool has selected (one file each). A choice the caller gives is kept. --- crates/ui-egui/src/dialogs/tests_export.rs | 31 ++++++++++++++++++++++ crates/ui-egui/src/menus/run.rs | 13 +++++++++ docs/ui-parity.md | 3 ++- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index f658c31b00..891fb586be 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -106,6 +106,37 @@ fn export_as_png_picks_the_file_then_shows_png_options() { assert_eq!(&written.borrow()[0].1[16..20], 120u32.to_be_bytes(), "60 pt at 144 ppi"); } +/// File › Export › Export As PNG… exports the artboard in use, not the first (#5502), and each +/// artboard the Artboard tool has selected, one file each. +#[test] +fn export_as_png_exports_the_active_artboard() { + let (mut app, written) = app(2); + // The ellipse is on the first artboard; the second is empty. + let opaque = |bytes: &[u8]| image::load_from_memory(bytes).unwrap().to_rgba8().pixels().any(|p| p.0[3] > 0); + app.view_mut().unwrap().artboard = 1; + app.run("file.export.png", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["artboard"], json!(1)); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(!opaque(&written.borrow()[0].1), "the second artboard, which is empty"); + app.view_mut().unwrap().artboard = 0; + app.run("file.export.png", json!({})).unwrap(); + frame(&mut app); + confirm(&mut app).unwrap(); + assert!(opaque(&written.borrow()[1].1), "the first artboard, with the ellipse"); + // A choice given is kept. + app.run("file.export.png", json!({"useArtboards": false})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.get("artboard").is_none_or(serde_json::Value::is_null)); + app.ui.dialog = None; + // Artboards the Artboard tool selected: one file each. + app.select_tool("artboard"); + app.session.set_tool_option("selected", &json!([0, 1])); + app.run("file.export.png", json!({})).unwrap(); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(names(&written)[2..], ["/out/Untitled-1-Artboard-1.png", "/out/Untitled-1-Artboard-2.png"]); +} + #[test] fn export_as_with_a_range_then_png_options_writes_one_file_per_artboard() { let (mut app, written) = app(3); diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 80fe0a1845..2d134f76f8 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -170,6 +170,19 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option 0 { + match crate::panels::artboards::picked(app, n).as_slice() { + [i] => params["artboard"] = json!(i), + several => { + params["artboards"] = json!(several); + params["useArtboards"] = json!(true); + } + } + } crate::dialogs::open_raster_options(app, f, params); Ok(Value::Null) }), diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 26f56b16f1..bbfcdc0698 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 (New Document's units belong to the chosen preset; Recent and Saved cards keep their own units; 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-04 · **Change:** minor (File › Export › Export As PNG exports the active artboard, or each one the Artboard tool selected, not always the first, #5502; 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) ## 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 | File › Export › Export As PNG… exports the active artboard, or each artboard the Artboard tool has selected (one file each), instead of always the first (#5502); a choice the caller gives is kept; scores and estimates unchanged | | 2026-11-04 | minor | Document Tools add-on (a VectorCraft addition): Object › Plug-ins › Document Tools › Batch Trace Folder asks for a folder of images and a destination folder and traces each image into it (#4921); scores and estimates unchanged | | 2026-11-03 | minor | The Action Options row cites the public Actions panel page and describes its controls. Scores and estimates remain unchanged. | | 2026-11-03 | minor | Enclosing Lasso provides whole-object enclosure selection as an add-on with no default shortcut or Basic toolbar slot. Scores and estimates remain unchanged. | From 9dc172a26dab5be5e9ca081826feb295a917af29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:46:58 -0800 Subject: [PATCH 100/482] Symbols: the quick box of a 9-slice instance holds art its guides move An object in 9-slice art that crosses a guide and draws symbol art is placed by the map of the cell its center is in, so it can draw outside the instance's transformed art box. Bounds measured without placing the art (the renderer's culling, and placements past the object limit) used that box alone, so the displaced art could be culled and not drawn. The fallback now takes in the art box placed by each of the nine cells' maps (NineSliceMap::placement_bounds), grown by the art's reach as before. --- crates/doc/src/node/ops.rs | 7 ++++++- crates/doc/src/symbol_nine_slice.rs | 20 ++++++++++++++++++++ crates/doc/src/symbols.rs | 23 ++++++++++++++++++++++- crates/render/src/tests.rs | 21 +++++++++++++++++++++ 4 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 07899196c2..5ab9e2c6c5 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -369,7 +369,12 @@ impl Node { let placed = xf.transform_rect_bbox(art.geometric); match s.placed_visual(symbol, *xf) { Some(v) => v.union(placed), - None => placed.inflate(art.reach, art.reach), + // Art placed through 9-slice guides can draw outside `placed`. + None => s + .document() + .symbol_slice_map_of(symbol, art.geometric, *xf) + .map_or(placed, |m| m.placement_bounds(art.geometric).union(placed)) + .inflate(art.reach, art.reach), } } None => xf.transform_rect_bbox(SYMBOL_SQUARE), diff --git a/crates/doc/src/symbol_nine_slice.rs b/crates/doc/src/symbol_nine_slice.rs index 8d7c108ab5..acc682872c 100644 --- a/crates/doc/src/symbol_nine_slice.rs +++ b/crates/doc/src/symbol_nine_slice.rs @@ -343,6 +343,20 @@ impl NineSliceMap { self.cell_xf(self.x.cell(q.x), self.y.cell(q.y)) } + /// A box that holds everything [`Self::place`] draws of art whose geometric box in symbol space + /// is `art`, before strokes and effects: `art` placed by each of the nine cells' maps. An object + /// that crosses a guide and draws symbol art is placed by the map of the cell its center is in, + /// so it can draw outside the box the corner cells place `art` in. + pub fn placement_bounds(&self, art: Rect) -> Rect { + let mut b = self.cell_xf(0, 0).transform_rect_bbox(art); + for j in 0..3 { + for i in 0..3 { + b = b.union(self.cell_xf(i, j).transform_rect_bbox(art)); + } + } + b + } + /// The guides in symbol space: the two x values and the two y values. fn cuts(&self) -> ([f64; 2], [f64; 2]) { let inv = self.natural.inverse(); @@ -704,6 +718,12 @@ impl Document { NineSliceMap::new(guides, art, self.symbol_natural_xf(name), xf) } + /// [`Self::symbol_slice_map`] with the guides cutting `art`, the symbol's art box already + /// measured. + pub(crate) fn symbol_slice_map_of(&self, name: &str, art: Rect, xf: Affine) -> Option { + NineSliceMap::new(self.symbol_nine_slice(name)?, art, self.symbol_natural_xf(name), xf) + } + /// Art `art` of symbol `name` (stained as the caller draws it) placed by an instance's /// transform `xf`, with strokes at their own weight: through the symbol's 9-slice guides when /// it has them ([`NineSliceMap::place`]), otherwise by `xf`. `None` when placing it through diff --git a/crates/doc/src/symbols.rs b/crates/doc/src/symbols.rs index 7e371c670e..3a91f8d62f 100644 --- a/crates/doc/src/symbols.rs +++ b/crates/doc/src/symbols.rs @@ -102,7 +102,9 @@ impl<'a> SymbolBoxes<'a> { /// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its /// art box alone. An instance that scales or turns stroked art then measures a little larger - /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. + /// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The + /// visual box of an instance placed through 9-slice guides holds the art box placed by each + /// cell's map ([`crate::NineSliceMap::placement_bounds`]). pub fn quick(self) -> Self { self.quick.set(true); self @@ -447,6 +449,25 @@ mod tests { assert_eq!(scaled.reach_bounds_with(&s), Some(Rect::new(0.0, 0.0, 60.0, 30.0).inflate(reach, reach))); } + #[test] + fn quick_boxes_hold_art_that_9_slice_guides_move_past_the_instance() { + // A 100 × 100 frame with guides a quarter in, holding an instance of a bar from x 10 to 70. + // Scaled 2 times across, the bar crosses the left guide and is placed by the middle + // column's map, x → 3x − 50: it draws from x −20 to 160, past the frame's left edge at 0. + let mut d = Document::new(200.0, 200.0); + let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0); + symbol(&mut d, "Bar", vec![bar]); + let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0); + let inner = instance(&mut d, "Bar", Affine::IDENTITY); + symbol(&mut d, "Panel", vec![frame, inner]); + d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default())); + let panel = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0)); + let exact = panel.visual_bounds_with(&d.symbol_boxes()).unwrap(); + assert_eq!(exact, Rect::new(-20.0, 0.0, 200.0, 100.0)); + let quick = panel.visual_bounds_with(&d.symbol_boxes().quick()).unwrap(); + assert_eq!(quick.union(exact), quick, "{quick:?} holds {exact:?}"); + } + #[test] fn missing_symbols_and_symbols_inside_themselves_measure_as_the_square() { let mut d = Document::new(200.0, 200.0); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index e171eecf6e..f8060eea71 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -378,6 +378,27 @@ fn a_scaled_instance_is_culled_by_the_effects_in_its_art_as_placed() { assert_eq!(img.pixel(5, 50), [255, 0, 0, 255]); } +#[test] +fn an_instance_is_culled_by_the_art_its_9_slice_guides_move() { + // A 100 × 100 frame with guides a quarter in, holding an instance of a red bar from x 10 to + // 70. Scaled 2 times across, the bar crosses the left guide and is placed by the middle + // column's map, x → 3x − 50: moved 110 pt right, it draws from x 90 to 270 while the frame + // starts at x 110, out of view. + let mut d = Document::new(100.0, 100.0); + let bar = rect_node(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Bar".into(), art: Arc::new(bar) }); + let frame = rect_node(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::None, Paint::None, 0.0); + let inner = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Bar".into(), xf: Affine::IDENTITY }); + let art = Node::group(d.alloc_id(), vec![Arc::new(frame), Arc::new(inner)]); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Panel".into(), art: Arc::new(art) }); + d.set_symbol_nine_slice("Panel", Some(vectorcraft_doc::SymbolNineSlice::default())); + let (id, l) = (d.alloc_id(), d.layers[0].id); + let xf = Affine::translate((110.0, 0.0)) * Affine::scale_non_uniform(2.0, 1.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::SymbolInstance { symbol: "Panel".into(), xf })).unwrap(); + let img = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions::default()); + assert_eq!(img.pixel(95, 50), [255, 0, 0, 255]); +} + #[test] fn an_instance_with_a_geometry_effect_is_culled_by_its_reshaped_art() { // The art, (0, 0) to (20, 20), drawn from (-100, 10) is out of view, and the Transform effect From 9992fa0bf62ecabcf7451849fef2d10ceb8c90c1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:39:39 -0800 Subject: [PATCH 101/482] Symbols: saving leaves out a nested editing layer and keeps layers named in file data Leaving opacity-mask or symbol editing now removes the editing layer wherever it is, so a save or export after Layers moved it into another layer no longer writes it. An editing id that names anything other than a layer is left alone. symbol_edit is no longer read from files: a value in file data is dropped on load, so the layer it names is kept and saving does not write the value again. --- crates/doc/src/document_ext.rs | 14 ++++---- crates/doc/src/lib.rs | 5 +-- crates/doc/src/skip.rs | 5 +++ crates/doc/src/tests.rs | 61 ++++++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/document_ext.rs b/crates/doc/src/document_ext.rs index c9a6c5f56a..efd7f80b22 100644 --- a/crates/doc/src/document_ext.rs +++ b/crates/doc/src/document_ext.rs @@ -99,13 +99,15 @@ impl Document { } /// Leave opacity-mask editing and symbol editing: drop the temporary editing layer, a working - /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). + /// copy of art the mask or the symbol already holds (the engine syncs it after every edit). The + /// layer is removed wherever it is, also as a sublayer of another layer; an id that names + /// anything other than a layer is left alone. pub fn drop_edit_modes(&mut self) { - if let Some(me) = self.mask_edit.take() { - self.layers.retain(|l| l.id != me.layer); - } - if let Some(se) = self.symbol_edit.take() { - self.layers.retain(|l| l.id != se.layer); + let layers = [self.mask_edit.take().map(|me| me.layer), self.symbol_edit.take().map(|se| se.layer)]; + for id in layers.into_iter().flatten() { + if self.node(id).is_some_and(Node::is_layer) { + let _ = self.remove(id); + } } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 84a66220f1..133bc41205 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -228,8 +228,9 @@ pub struct Document { #[serde(default, skip_serializing)] pub mask_edit: Option, /// Symbol editing mode, while active. Never saved (see [`Document::without_edit_modes`]): the - /// symbol already holds the art of its editing layer. - #[serde(default, skip_serializing)] + /// symbol already holds the art of its editing layer. Never read either: a value in file data + /// is dropped, so the layer it names is kept and saving does not write the value again. + #[serde(default, skip_serializing, deserialize_with = "skip::read_as_none")] pub symbol_edit: Option, next_id: u64, /// Foreign data preserved on round-trip. diff --git a/crates/doc/src/skip.rs b/crates/doc/src/skip.rs index 15f294c009..b26a1a7ac5 100644 --- a/crates/doc/src/skip.rs +++ b/crates/doc/src/skip.rs @@ -13,3 +13,8 @@ pub fn is_empty_vec(v: &[T]) -> bool { pub fn is_empty_map(v: &serde_json::Map) -> bool { v.is_empty() } +/// Read a field's value and drop it, giving `None`: for state that is never taken from a file. +pub fn read_as_none<'de, D: serde::Deserializer<'de>, T>(d: D) -> Result, D::Error> { + ::deserialize(d)?; + Ok(None) +} diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index 37e2d39bca..4b75b01497 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -451,3 +451,64 @@ fn pica_form_rejects_exponent_notation() { assert_eq!(Unit::Points.parse(s), None, "{s}"); } } + +/// Symbol editing of symbol "S" on `layer`. +fn symbol_edit_on(layer: NodeId) -> SymbolEdit { + SymbolEdit { + symbol: "S".into(), + layer, + instance: None, + xf: Affine::IDENTITY, + group: false, + changed: false, + back_isolation: None, + back_layer: None, + } +} + +/// The opacity-mask and symbol editing layers are left out of the saved document wherever they +/// are, also when `layer.move` made them sublayers of another layer. +#[test] +fn edit_mode_layers_are_dropped_as_sublayers_too() { + let mut d = Document::new(612.0, 792.0); + let host = d.layers[0].id; + let mask = d.add_layer(Some("Mask")); + let symbol = d.add_layer(Some("Symbol")); + d.move_node(mask, Some(host), 0).unwrap(); + d.move_node(symbol, Some(host), usize::MAX).unwrap(); + let object = d.alloc_id(); + d.mask_edit = Some(MaskEdit { object, layer: mask }); + d.symbol_edit = Some(symbol_edit_on(symbol)); + let saved = d.without_edit_modes(); + assert!(saved.node(mask).is_none(), "the mask editing layer is left out"); + assert!(saved.node(symbol).is_none(), "the symbol editing layer is left out"); + assert!(saved.node(host).is_some_and(|l| l.children().is_some_and(|c| c.is_empty()))); + assert!(saved.mask_edit.is_none() && saved.symbol_edit.is_none()); +} + +/// Symbol editing is never read from a file, so a layer that file data names as the editing layer +/// loads and stays in the document, and saving does not write the value again. +#[test] +fn symbol_edit_is_not_read_from_a_file() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut v = serde_json::to_value(&d).unwrap(); + v["symbol_edit"] = serde_json::to_value(symbol_edit_on(layer)).unwrap(); + d = serde_json::from_value(v).unwrap(); + assert_eq!(d.symbol_edit, None); + assert!(d.extra.is_empty(), "not kept as an unknown key"); + d.drop_edit_modes(); + assert!(d.node(layer).is_some(), "the layer is kept"); + assert!(serde_json::to_value(&d).unwrap().get("symbol_edit").is_none(), "not saved again"); +} + +/// An opacity-mask editing id in file data that names art inside a layer, not a layer, leaves the +/// art in place. +#[test] +fn mask_edit_naming_art_leaves_it() { + let (mut d, a, b) = doc_with_rects(); + d.mask_edit = Some(MaskEdit { object: b, layer: a }); + d.drop_edit_modes(); + assert!(d.node(a).is_some() && d.node(b).is_some()); + assert_eq!(d.mask_edit, None); +} From 32456839ebb3dfd3d6f08ca06d4a8880655528e9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:53:00 -0800 Subject: [PATCH 102/482] Native format: a saved mask-editing id drops only a top-level layer Files saved mid-edit by older versions carry the opacity-mask editing layer at the top level. An id there that names a sublayer is ignored on load, so that sublayer and its art are kept. --- crates/format/src/lib.rs | 6 +++++- crates/format/tests/it/native_v3.rs | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 6ed3e68407..65c10ba802 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -537,7 +537,11 @@ fn load_file_within(bytes: &[u8], max_nodes: usize, max_values: usize) -> Result } doc.images.insert(k, blob); } - // Saved mid-edit by an older version: drop the opacity-mask editing layer. + // Saved mid-edit by an older version: drop the opacity-mask editing layer. Those versions + // removed it only as a top-level layer, so an id naming anything else is ignored. + if doc.mask_edit.is_some_and(|me| !doc.layers.iter().any(|l| l.id == me.layer)) { + doc.mask_edit = None; + } doc.drop_edit_modes(); // Saved before per-fill/stroke overprint: the Overprint Black list becomes overprint flags. doc.migrate_overprint_black(); diff --git a/crates/format/tests/it/native_v3.rs b/crates/format/tests/it/native_v3.rs index 5475f39fb0..6a96fae79d 100644 --- a/crates/format/tests/it/native_v3.rs +++ b/crates/format/tests/it/native_v3.rs @@ -157,6 +157,24 @@ fn keys_from_newer_versions_round_trip() { check_native_roundtrip(&d).unwrap(); } +/// An opacity-mask editing state in a file drops the editing layer it names only when that is a +/// top-level layer, as files saved mid-edit have it: a sublayer it names loads and stays. +#[test] +fn saved_mask_editing_drops_only_a_top_level_layer() { + let mut d = Document::new(612.0, 792.0); + let host = d.layers[0].id; + let sub = d.add_layer(Some("Sub")); + d.move_node(sub, Some(host), 0).unwrap(); + let top = d.add_layer(Some("Mask")); + for (layer, kept) in [(sub, true), (top, false)] { + let mut v = json_of(&save(&d, false)); + v["document"]["mask_edit"] = json!({"object": host, "layer": layer}); + let back = load(&serde_json::to_vec(&v).unwrap()).unwrap(); + assert_eq!(back.node(layer).is_some(), kept, "layer {layer:?}"); + assert!(back.mask_edit.is_none() && back.node(host).is_some()); + } +} + /// The paragraph composer is saved only when it isn't the default (Every-line) and reads back. #[test] fn text_composer_round_trips() { From a574139814266ef6a1742997d83d806ecea45698 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 4 Nov 2026 06:56:28 -0800 Subject: [PATCH 103/482] i18n: a count in a translated message matches only a number A plural status message such as "Saved {path} with {n} note: {first}" matched a path that holds " with " by taking the first split, so for "/out/art with notes.pdf" the count became "notes.pdf with 1". The count did not parse, the translation took the plural form and split the path. The {n} of a @msgplural template now matches only a number, and the matcher tries the next split when it does not. {n} in a @msg template still matches any text, since those name brushes, symbols and presets. --- crates/ui-egui/src/i18n/catalog.rs | 27 +++++++++++++++++---------- crates/ui-egui/src/i18n/tests.rs | 16 ++++++++++++++++ 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/i18n/catalog.rs b/crates/ui-egui/src/i18n/catalog.rs index 1be460212a..8999157286 100644 --- a/crates/ui-egui/src/i18n/catalog.rs +++ b/crates/ui-egui/src/i18n/catalog.rs @@ -35,6 +35,8 @@ struct Template { /// Bytes of literal text: a template with more of it is the more specific match. literal: usize, forms: Vec, + /// A `@msgplural` form: its `{n}` matches only a count. + counted: bool, } /// The placeholder values of a matched message template: placeholder name and value. @@ -46,7 +48,7 @@ const MAX_MESSAGE_LEN: usize = 2000; impl Template { /// `None` for a template that can't be matched reliably: no literal text, or two placeholders /// in a row (where one ends and the next begins is unknowable). - fn parse(source: &str, forms: Vec) -> Option