From cc5d3b5537f723cb7885bd8f617d0ec38bf80e44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:20:49 -0800 Subject: [PATCH 001/104] Color Wheel: the box and the wheel mark the contrast lines and offer the closest passing color With Show Contrast on, the wheel's square and the box's field draw where the color picked there meets AA (solid) and AAA (dashed) for the chosen category, each as a white line over a black one. The field is sampled on a 33 by 33 grid and each crossing is placed by bisection, so a line can run across the field or up it; a passing band narrower than the samples is found by looking for the highest ratio around a failing sample higher than its neighbors. When the color fails AA, or meets AA and fails AAA, a chip at the end of the contrast row shows the closest color that passes that level, and a click applies it. The chip keeps its space while hidden, so the row does not move as a drag crosses a line. Screen readers read it as a button. color.contrast takes `for` (normalText, largeText or graphics) and answers `for` and `fix: {aa, aaa}` (no aaa for graphics): for each level, the closest color that meets it when drawn the same way (blend modes, opacity, translucent groups and layers, the stain of a picked symbol object), in the model of the measured color, or null when the color already meets it or no lightness of its hue does. The search keeps the OKLCH hue, raises or lowers the lightness, whichever takes the smaller step, lowers the chroma where sRGB cannot show it, and tests at most 167 colors. Part of #978 --- crates/color/src/wcag.rs | 154 ++++++++ crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/colorcmds.rs | 234 +++++++++--- crates/engine/src/tests/colorcontrast.rs | 84 +++++ 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/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 336 ++++++++++++++++-- .../tests_color_wheel_contrast_lines.rs | 167 +++++++++ docs/control-protocol.md | 11 +- docs/mcp.md | 14 +- docs/target-app-parity.md | 2 +- 38 files changed, 946 insertions(+), 87 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index ef42eec957..d63e07c952 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -2,6 +2,7 @@ //! the relative luminance of display sRGB with the 0.04045 threshold, the ratio //! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3 //! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA). +//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum. /// What the content in front is, which sets the ratio it needs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -87,6 +88,99 @@ pub fn ratio_text(ratio: f64) -> String { format!("{:.2}:1", (r * 100.0).floor() / 100.0) } +/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that +/// passes. +const LIGHTNESS_SAMPLES: usize = 16; +/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9. +const LIGHTNESS_STEPS: usize = 32; +/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples, +/// which leave it within 1e-7 of the step. +const PEAK_STEPS: usize = 32; +/// The halvings [`closest_passing`] makes of the chroma when sRGB cannot show it. +const CHROMA_STEPS: usize = 24; + +/// The display sRGB of OKLCH lightness `l`, chroma `c` and the hue whose sine and cosine are `sc`, +/// with the chroma lowered until the color fits in sRGB. +fn oklch_in_gamut(l: f64, c: f64, (sin, cos): (f64, f64)) -> [f32; 3] { + let at = |c: f64| crate::libraries::oklab_to_srgb(l, c * cos, c * sin); + let fits = |rgb: &[f64; 3]| rgb.iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(v)); + let mut rgb = at(c); + if !fits(&rgb) { + let (mut lo, mut hi) = (0.0, c); + for _ in 0..CHROMA_STEPS { + let mid = (lo + hi) / 2.0; + if fits(&at(mid)) { lo = mid } else { hi = mid } + } + rgb = at(lo); + } + rgb.map(|v| v.clamp(0.0, 1.0) as f32) +} + +/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a +/// single peak between them. `f` is called 34 times. +pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { + let g = (5f64.sqrt() - 1.0) / 2.0; + let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo)); + let (mut fa, mut fb) = (f(a), f(b)); + for _ in 0..PEAK_STEPS { + if fa < fb { + (lo, a, fa) = (a, b, fb); + b = lo + g * (hi - lo); + fb = f(b); + } else { + (hi, b, fb) = (b, a, fa); + a = hi - g * (hi - lo); + fa = f(a); + } + } + if fa > fb { a } else { b } +} + +/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue +/// () with the lightness raised or lowered, whichever +/// takes the smaller step, and the chroma lowered where sRGB cannot show it. Each side is tested at +/// 16 even steps up to white or black, and the step before the first that passes is narrowed down. +/// When no step passes, the highest ratio between the neighbors of the highest step is looked for, +/// so a color that passes only in a narrow band between white and black (as under a Difference +/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is +/// bounded: at most 167 colors are tested. +pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> { + let passes = |c: [f32; 3]| ratio(c) >= minimum; + let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); + if passes(srgb) { + return Some(srgb); + } + let [l, a, b] = crate::libraries::srgb_to_oklab(srgb); + let (c, sc) = (a.hypot(b), b.atan2(a).sin_cos()); + let mut best: Option<(f64, [f32; 3])> = None; + for end in [1.0, 0.0] { + let at = |t: f64| oklch_in_gamut(l + (end - l) * t, c, sc); + let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64; + let ratios: Vec = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect(); + // `lo` fails and `hi` passes, the step before the first sample that passes. + let found = match ratios.iter().position(|r| *r >= minimum) { + Some(i) => Some((step(i), step(i + 1))), + None => { + // Every sample fails: look for a higher ratio around the highest one. + let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0; + let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES))); + let peak = peak_between(lo, hi, &|t| ratio(at(t))); + passes(at(peak)).then_some((lo, peak)) + } + }; + let Some((mut lo, mut hi)) = found else { continue }; + for _ in 0..LIGHTNESS_STEPS { + let mid = (lo + hi) / 2.0; + if passes(at(mid)) { hi = mid } else { lo = mid } + } + let step = (end - l).abs() * hi; + if best.is_none_or(|(d, _)| step < d) { + best = Some((step, at(hi))); + } + } + best.map(|(_, c)| c) +} + #[cfg(test)] mod tests { use super::*; @@ -137,6 +231,66 @@ mod tests { assert_eq!(Category::parse("NormalText"), None); } + fn hue(srgb: [f32; 3]) -> f64 { + let [_, a, b] = crate::libraries::srgb_to_oklab(srgb); + b.atan2(a).to_degrees() + } + + #[test] + fn the_closest_passing_color_keeps_the_hue_and_just_passes() { + let (fg, bg) = (hex("fdc96e"), hex("355f78")); + let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap(); + let r = contrast_ratio(fix, bg); + assert!((4.5..4.501).contains(&r), "{r}"); + assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg)); + // A color lighter than the background gets lighter. + assert!(relative_luminance(fix) > relative_luminance(fg)); + } + + #[test] + fn the_closest_passing_gray_on_white_is_a_darker_gray() { + let white = [1.0; 3]; + let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap(); + let r = contrast_ratio(fix, white); + assert!((4.5..4.501).contains(&r), "{r}"); + assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}"); + } + + #[test] + fn a_color_that_passes_only_between_white_and_black_is_found() { + // White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and + // mid gray draws black, 5.3:1. + let gray = [0.5; 3]; + let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) }; + let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap(); + let r = contrast_ratio(difference(fix), gray); + assert!((4.5..4.51).contains(&r), "{fix:?}: {r}"); + assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}"); + } + + #[test] + fn a_narrow_band_between_the_samples_is_found() { + // Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference + // for 3:1 (black reaches 3.04:1), and no even step from white lands there. + let gray = hex("5a5a5a"); + let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) }; + let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray); + let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap(); + let r = ratio(fix); + assert!((3.0..3.01).contains(&r), "{fix:?}: {r}"); + } + + #[test] + fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() { + let white = [1.0; 3]; + assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3])); + assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None); + // Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches. + let mid = hex("777777"); + assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None); + assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3])); + } + #[test] fn half_opaque_black_over_white_is_mid_gray() { assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e2bc50cdc5..2859e8751e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -821,6 +821,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +pub use colorcmds::{Backdrop, contrast_measure}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index b1817784b6..b3f0a4e2fb 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the background; the modes inside an object, group or layer that isolates its blending do not apply; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the background; the modes inside an object, group or layer that isolates its blending do not apply; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it; null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), @@ -1000,7 +1000,160 @@ const BELOW_SIDE: f64 = 1.0; /// The pixels per point [`color_below`] renders at. const BELOW_SCALE: f64 = 4.0; +/// What `color.contrast` measures a color against: the background, and how the color is drawn over +/// it (its blend modes, its opacity and the translucent groups and layers around it). The Color +/// Wheel panel's contrast lines measure many colors against one. +#[derive(Clone, Debug, PartialEq)] +pub struct Backdrop { + /// The background in display sRGB. + against: [f32; 3], + /// The background in working RGB, rounded to 8 bits, as the answer writes it. + written: [u8; 3], + /// The blend modes the color is drawn with, innermost first. + modes: Vec, + /// The given opacity, which takes the place of the drawn ones. + opacity: Option, + /// Each translucent group or layer around the object, from the outermost in, with the color + /// outside it. + levels: Vec<(f32, [f32; 3])>, + /// The opacity the color is drawn with inside its object. + drawn: f32, + /// The color and amount a fill stains the picked object of a dynamic symbol instance with. + stain: Option<(Color, f32)>, +} + +impl Backdrop { + /// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a + /// fill stains mixes its solid color towards the stain. + pub fn drawn_color(&self, c: &Color) -> Color { + match self.stain { + Some((stain, amount)) => c.lerp(&stain, amount), + None => *c, + } + } + + /// Display sRGB `shown`, drawn as the measured color is drawn, over the background. + pub fn front(&self, shown: [f32; 3]) -> [f32; 3] { + // Each blend mode, innermost first, replaces the color with its blend with the background + // where it covers it. + let blended = self.modes.iter().fold(shown, |c, m| vectorcraft_color::blend::blend_rgb(*m, self.against, c)); + match self.opacity { + Some(o) => wcag::over(blended, o, self.against), + None => { + // A translucent group or layer draws the art inside it, the art behind the object + // included, over what is outside it: the color is drawn opaque through each such + // level from the outermost in, over the color read with that level hidden, then at + // the object's own opacity over the background. + let x = self.levels.iter().fold(blended, |x, (a, outside)| wcag::over(x, *a, *outside)); + wcag::over(x, self.drawn, self.against) + } + } + } + + /// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against + /// the background. + pub fn ratio(&self, shown: [f32; 3]) -> f64 { + wcag::contrast_ratio(self.front(shown), self.against) + } + + /// The background as `#rrggbb` in working RGB, the form a color param takes. + pub fn against_hex(&self) -> String { + let [r, g, b] = self.written; + format!("#{r:02x}{g:02x}{b:02x}") + } +} + +/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black, +/// 100 % K alone shows as black. +fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] { + match *c { + Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3], + _ => cms.display_rgb(c), + } +} + +/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it: +/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a +/// Gray color as gray. +fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color { + let [r, g, b] = cms.srgb_to_rgb(srgb); + let rgb = Color::rgb(r, g, b); + match like { + Color::Rgb { .. } => rgb, + Color::Cmyk { .. } => { + let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent); + Color::cmyk(c, m, y, k) + } + Color::Lab { .. } => { + let l = cms.lab(&rgb); + Color::lab(l.l, l.a, l.b) + } + Color::Gray { .. } => keep_model(*like, rgb), + } +} + +/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum` +/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain +/// included). None when `color` already meets it, or when no lightness of its hue does. +fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64, rich_black: bool) -> Option { + let cms = vectorcraft_color::cms::active(); + let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c)); + let ratio = |srgb: [f32; 3]| backdrop.ratio(drawn(&in_model_of(&cms, srgb, color))); + if backdrop.ratio(drawn(color)) >= minimum { + return None; + } + let fix = wcag::closest_passing(shown_rgb(&cms, rich_black, color), minimum, &ratio)?; + Some(in_model_of(&cms, fix, color)) +} + fn contrast(s: &mut Session, p: &Value) -> Result { + contrast_measure(s, p).map(|(answer, _)| answer) +} + +/// `color.contrast`'s answer for params `p`, and what it measured the color against. +pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { + const C: &str = "color.contrast"; + let category = match p.get("for") { + None | Some(Value::Null) => Category::NormalText, + Some(v) => { + let key = "for"; + let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect(); + v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))? + } + }; + let (color, backdrop) = contrast_backdrop(s, p)?; + let rich_black = s.prefs.black_on_screen == "rich"; + let ratio = backdrop.ratio(shown_rgb(&vectorcraft_color::cms::active(), rich_black, &backdrop.drawn_color(&color))); + let levels = |c: Category| { + let (aa, aaa) = c.passes(ratio); + match aaa { + Some(aaa) => json!({ "aa": aa, "aaa": aaa }), + None => json!({ "aa": aa }), + } + }; + let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum, rich_black) { + Some(c) => serde_json::to_value(c).unwrap_or(Value::Null), + None => Value::Null, + }; + let fixes = match category.minimums() { + (aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }), + (aa, None) => json!({ "aa": fix(aa) }), + }; + let answer = json!({ + "ratio": ratio, + "against": backdrop.against_hex(), + "normalText": levels(Category::NormalText), + "largeText": levels(Category::LargeText), + "graphics": levels(Category::Graphics), + "for": category.id(), + "fix": fixes, + }); + Ok((answer, backdrop)) +} + +/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and +/// what it measures it against. +fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { const C: &str = "color.contrast"; check_numbers(p, &["opacity"], C)?; let opacity = match p.get("opacity").and_then(Value::as_f64) { @@ -1012,16 +1165,14 @@ fn contrast(s: &mut Session, p: &Value) -> Result { None => None, }; let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below")); + let given = p.get("color").is_some_and(|v| !v.is_null()); let (color, drawn, mode, around) = match p.get("color") { None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?, Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, 1.0, vec![], vec![]), }; let rich_black = s.prefs.black_on_screen == "rich"; let cms = vectorcraft_color::cms::active(); - let shown = |c: &Color| match *c { - Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3], - _ => cms.display_rgb(c), - }; + let shown = |c: &Color| shown_rgb(&cms, rich_black, c); let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); // The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as. let (against, written) = match p.get("against").filter(|_| !below) { @@ -1037,43 +1188,19 @@ fn contrast(s: &mut Session, p: &Value) -> Result { (shown, to_8bit(cms.srgb_to_rgb(shown))) } }; - // Each blend mode, innermost first, replaces the color with its blend with the background - // where it covers it. - let blended = mode.iter().fold(shown(&color), |c, m| vectorcraft_color::blend::blend_rgb(*m, against, c)); - let front = match opacity { - Some(o) => wcag::over(blended, o, against), - None => { - // A translucent group or layer draws the art inside it, the art behind the object - // included, over what is outside it: the color is drawn opaque through each such level - // from the outermost in, over the color read with that level hidden, then at the - // object's own opacity over the background. - let mut x = blended; - for (a, level) in around.iter().rev().filter(|(a, _)| *a < 1.0) { - let outside = match level.filter(|_| below) { - Some(id) => color_below(s, rich_black, Some(id)).map_err(|e| bad(C, e))?, - None => against, - }; - x = wcag::over(x, *a, outside); - } - wcag::over(x, drawn, against) + // Each translucent group or layer, from the outermost in, with the color read with it hidden. + let mut levels = vec![]; + if opacity.is_none() { + for (a, level) in around.iter().rev().filter(|(a, _)| *a < 1.0) { + let outside = match level.filter(|_| below) { + Some(id) => color_below(s, rich_black, Some(id)).map_err(|e| bad(C, e))?, + None => against, + }; + levels.push((*a, outside)); } - }; - let ratio = wcag::contrast_ratio(front, against); - let levels = |c: Category| { - let (aa, aaa) = c.passes(ratio); - match aaa { - Some(aaa) => json!({ "aa": aa, "aaa": aaa }), - None => json!({ "aa": aa }), - } - }; - let [r, g, b] = written; - Ok(json!({ - "ratio": ratio, - "against": format!("#{r:02x}{g:02x}{b:02x}"), - "normalText": levels(Category::NormalText), - "largeText": levels(Category::LargeText), - "graphics": levels(Category::Graphics), - })) + } + let stain = if given { None } else { stain_of(s) }; + Ok((color, Backdrop { against, written, modes: mode, opacity, levels, drawn, stain })) } /// The opacity of each object around the proxy's object that draws it, innermost first, with the @@ -1134,7 +1261,7 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re } let no_color = || "the active fill or stroke has no color: give `color`".to_string(); match if stroke { stroke_paint } else { fill } { - Paint::Solid { color, .. } => Ok((stained(s, color), layer, mode, around)), + Paint::Solid { color, .. } => Ok((color, layer, mode, around)), Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => { let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0)); let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0); @@ -1186,19 +1313,18 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s Ok((opacity, drawn_modes(levels.collect()), around)) } -/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains -/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill); -/// `color` itself otherwise. -fn stained(s: &Session, color: Color) -> Color { - let stain = s.active().and_then(|st| { - let sp = st.selection.symbol_part.as_ref()?; - st.selected_symbol_part()?; - vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?) - }); - match stain { - Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)), - None => color, +/// The color and amount a fill stains the picked object of a dynamic symbol instance with +/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when +/// such an object is picked and its proxy shows a solid color. +fn stain_of(s: &Session) -> Option<(Color, f32)> { + let (fill, stroke) = s.proxy_paints(); + if !matches!(if s.fill_active { fill } else { stroke }, Paint::Solid { .. }) { + return None; } + let st = s.active()?; + let sp = st.selection.symbol_part.as_ref()?; + st.selected_symbol_part()?; + vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0))) } /// The blend modes that apply to a color drawn through `levels` (each a blend mode and whether that diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 398dc24b88..20a8b9bcda 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -379,6 +379,14 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() { let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap(); let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}"); + // The fix is the color to store: the stain mixes it half way to black again, and the result + // just meets AA against white. + let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap(); + assert_eq!(r["normalText"]["aa"], false, "{r}"); + let fix = fix_color(&r["fix"]["aa"]); + let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated(); + let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]); + assert!((4.5..4.51).contains(&got), "{fix:?} draws {drawn:?}: {got}"); } #[test] @@ -441,3 +449,79 @@ fn a_fill_of_none_has_no_color_to_measure() { assert!(e.contains("has no color"), "{e}"); assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok()); } + +fn fix_color(v: &Value) -> vectorcraft_color::Color { + crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}")) +} + +fn oklch_hue(c: &vectorcraft_color::Color) -> f64 { + let [_, a, b] = vectorcraft_color::libraries::to_oklab(c); + b.atan2(a).to_degrees() +} + +#[test] +fn a_failing_color_answers_the_closest_passing_color_of_its_hue() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap(); + assert_eq!(r["for"], "normalText"); + let aa = fix_color(&r["fix"]["aa"]); + let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap(); + assert!((4.5..4.51).contains(&ratio(&back)), "{back}"); + let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap()); + assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa)); + assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}"); + // White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1. + assert!(r["fix"]["aaa"].is_null(), "{r}"); + let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap(); + let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap(); + assert!((4.5..4.51).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}"); +} + +#[test] +fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert_eq!(r["fix"], json!({"aa": null, "aaa": null})); + let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap(); + assert_eq!(g["for"], "graphics"); + let fix = g["fix"].as_object().unwrap(); + assert_eq!(fix.keys().collect::>(), ["aa"], "{g}"); + let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap(); + assert!((3.0..3.01).contains(&ratio(&back)), "{back}"); + let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap(); + assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}"); + assert!(!large["fix"]["aaa"].is_null(), "{large}"); +} + +#[test] +fn a_cmyk_color_answers_a_cmyk_fix() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap(); + assert_eq!(r["normalText"]["aa"], false, "{r}"); + let fix = fix_color(&r["fix"]["aa"]); + assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}"); + let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap(); + assert!(ratio(&back) >= 4.5, "{back}"); +} + +#[test] +fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() { + let mut s = Session::new(); + // #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which + // meets large text AA (3:1) but not AAA (4.5:1). + let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"}); + let r = s.execute("color.contrast", &p).unwrap(); + assert_eq!(r["largeText"]["aa"], false, "{r}"); + assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}"); + let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap(); + assert!((3.0..3.01).contains(&ratio(&back)), "{back}"); +} + +#[test] +fn for_takes_only_the_three_categories() { + let mut s = Session::new(); + for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] { + let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string(); + assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}"); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 359972b26c..b78684086f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1477,6 +1477,7 @@ font-technology Variable Променливи Fail Не покрива WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11). The background is read at the center of the selection. Фонът се отчита в центъра на селекцията. + The closest color that passes {level}: click to apply it. Най-близкият цвят, който покрива {level}: щракнете, за да го приложите. Graphics Processor Графичен процесор Graphics: {adapter} Графика: {adapter} Gravity Гравитация diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d9bfe3c2..52513dddfb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1968,6 +1968,7 @@ digits Malayalam Malajalam Fail Ne prolazi WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11). The background is read at the center of the selection. Pozadina se očitava u sredini odabira. + The closest color that passes {level}: click to apply it. Najbliža boja koja zadovoljava {level}: kliknite da je primijenite. Local Libraries Lokalne biblioteke Add Content Dodaj sadržaj Click to apply to the selected type Kliknite da primijenite na odabrani tekst diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 47559f16c1..7a64590644 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1992,6 +1992,7 @@ digits Malayalam Malaiàlam Fail No supera WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11). The background is read at the center of the selection. El fons es llegeix al centre de la selecció. + The closest color that passes {level}: click to apply it. El color més proper que compleix {level}: feu clic per aplicar-lo. Graphics Processor Processador gràfic Graphics: {adapter} Gràfics: {adapter} Gravity Gravetat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 517c4732e4..e6c2295c24 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2041,6 +2041,7 @@ digits Malayalam Malajálamské Fail Nevyhovuje WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11). The background is read at the center of the selection. Pozadí se čte uprostřed výběru. + The closest color that passes {level}: click to apply it. Nejbližší barva, která splňuje {level}: kliknutím ji použijete. Local Libraries Místní knihovny Add Content Přidat obsah Click to apply to the selected type Kliknutím použijete na vybraný text diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3ab1d7eb08..c38325c433 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4520,6 +4520,7 @@ digits Malayalam Malayalam Fail Ikke bestået WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11). The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen. + The closest color that passes {level}: click to apply it. Den nærmeste farve, der består {level}: klik for at anvende den. Local Libraries Lokale biblioteker Add Content Tilføj indhold Click to apply to the selected type Klik for at anvende på den markerede tekst diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d9f7612aa8..8e3c8847e4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1527,6 +1527,7 @@ file-filter Templates Vorlagen Fail Nicht bestanden WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11). The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen. + The closest color that passes {level}: click to apply it. Die nächste Farbe, die {level} besteht: Klicken Sie, um sie anzuwenden. Graphics Processor Grafikprozessor Graphics: {adapter} Grafik: {adapter} Gravity Schwerkraft diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f476aa9b33..9b7b485a6f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1459,6 +1459,7 @@ font-technology Variable Μεταβλητές Fail Αποτυχία WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11). The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής. + The closest color that passes {level}: click to apply it. Το πλησιέστερο χρώμα που περνά το {level}: κάντε κλικ για να το εφαρμόσετε. Graphics Processor Επεξεργαστής γραφικών Graphics: {adapter} Γραφικά: {adapter} Gravity Βαρύτητα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c0ced0baaa..78858b8cd4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1542,6 +1542,7 @@ font-technology Variable Variables Fail No cumple WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11). The background is read at the center of the selection. El fondo se lee en el centro de la selección. + The closest color that passes {level}: click to apply it. El color más cercano que cumple {level}: haga clic para aplicarlo. Graphics Processor Procesador gráfico Graphics: {adapter} Gráficos: {adapter} Gravity Gravedad diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 018f984732..0f0a867295 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2002,6 +2002,7 @@ digits Malayalam Malajalam Fail Ei läpäise WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11). The background is read at the center of the selection. Tausta luetaan valinnan keskeltä. + The closest color that passes {level}: click to apply it. Lähin väri, joka läpäisee tason {level}: käytä sitä napsauttamalla. Local Libraries Paikalliset kirjastot Add Content Lisää sisältöä Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index eaac8d95b1..9cf5367489 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1532,6 +1532,7 @@ font-technology Variable Variables Fail Échec WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11). The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection. + The closest color that passes {level}: click to apply it. La couleur la plus proche qui satisfait {level} : cliquez pour l’appliquer. Graphics Processor Processeur graphique Graphics: {adapter} Carte graphique : {adapter} Gravity Gravité diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ee71f52157..54f5a79610 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1616,6 +1616,7 @@ Fail નાપાસ WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11). The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે. + The closest color that passes {level}: click to apply it. {level} પાસ કરતો સૌથી નજીકનો રંગ: તેને લાગુ કરવા ક્લિક કરો. Graphics Processor ગ્રાફિક્સ પ્રોસેસર Graphics: {adapter} ગ્રાફિક્સ: {adapter} Gravity ગ્રેવિટી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6b62bda40f..cffebdc9b7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2208,6 +2208,7 @@ antiAlias Sharp शार्प Fail फ़ेल WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)। The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है। + The closest color that passes {level}: click to apply it. {level} पास करने वाला सबसे नज़दीकी रंग: लागू करने के लिए क्लिक करें। Graphics Processor ग्राफिक्स प्रोसेसर Graphics: {adapter} ग्राफिक्स: {adapter} Gravity ग्रेविटी diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1d24dba789..87b38dc4aa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1925,6 +1925,7 @@ file-filter Templates Sablonok Fail Nem felel meg WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11). The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program. + The closest color that passes {level}: click to apply it. A legközelebbi szín, amely megfelel a(z) {level} szintnek: kattintson az alkalmazásához. Graphics Processor Grafikus processzor Graphics: {adapter} Grafika: {adapter} Gravity Gravitáció diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index af89105e27..b8e9a88359 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1804,6 +1804,7 @@ digits Malayalam Malayalam Fail Gagal WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11). The background is read at the center of the selection. Latar dibaca di tengah seleksi. + The closest color that passes {level}: click to apply it. Warna terdekat yang lolos {level}: klik untuk menerapkannya. Local Libraries Pustaka lokal Add Content Tambahkan konten Click to apply to the selected type Klik untuk menerapkan ke teks terpilih diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a902541e0b..52e3aeccb7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1561,6 +1561,7 @@ file-filter Templates Modelli Fail Non superato WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11). The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione. + The closest color that passes {level}: click to apply it. Il colore più vicino che soddisfa {level}: fai clic per applicarlo. Graphics Processor Processore grafico Graphics: {adapter} Scheda grafica: {adapter} Gravity Gravità diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f647393ade..0187ebacc2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3987,6 +3987,7 @@ file-filter Templates テンプレート Fail 不合格 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。 The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。 + The closest color that passes {level}: click to apply it. {level} を満たす最も近いカラー:クリックで適用します。 Greek & Cyrillic ギリシャ文字とキリル文字 Hex by Column 六角形 (列) Hex by Row 六角形 (行) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8041133095..516a00d1ec 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3869,6 +3869,7 @@ digits Malayalam მალაიალამური Fail არ აკმაყოფილებს WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11). The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში. + The closest color that passes {level}: click to apply it. უახლოესი ფერი, რომელიც აკმაყოფილებს {level}-ს: დააწკაპუნეთ მის გამოსაყენებლად. Local Libraries ლოკალური ბიბლიოთეკები Add Content შიგთავსის დამატება Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9e890e2580..9402411a0d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3975,6 +3975,7 @@ file-filter Templates 템플릿 Fail 실패 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11). The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다. + The closest color that passes {level}: click to apply it. {level}을(를) 충족하는 가장 가까운 색상: 클릭하여 적용합니다. Greek & Cyrillic 그리스어 및 키릴 문자 Hex by Column 열 기준 육각형 Hex by Row 행 기준 육각형 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b63a05e26f..06559f4d4f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2414,6 +2414,7 @@ digits Malayalam Malayalam Fail Niet geslaagd WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11). The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten. + The closest color that passes {level}: click to apply it. De dichtstbijzijnde kleur die aan {level} voldoet: klik om deze toe te passen. Local Libraries Lokale bibliotheken Add Content Inhoud toevoegen Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index aeaa4a7bac..e703f9f206 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1959,6 +1959,7 @@ digits Malayalam Malajalam Fail Nie spełnia WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11). The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia. + The closest color that passes {level}: click to apply it. Najbliższy kolor spełniający {level}: kliknij, aby go zastosować. Local Libraries Biblioteki lokalne Add Content Dodaj zawartość Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 91820ab433..2a30fdb4d0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3684,6 +3684,7 @@ font-technology Variable Variáveis Fail Reprovado WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11). The background is read at the center of the selection. O fundo é lido no centro da seleção. + The closest color that passes {level}: click to apply it. A cor mais próxima que atende a {level}: clique para aplicá-la. Highlight Rows Destacar linhas Highlight Variable Destacar variável Sort Variables Ordenar variáveis diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 76a70a4fb6..7dd8cb1654 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1552,6 +1552,7 @@ file-filter Templates Шаблоны Fail Не соответствует WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11). The background is read at the center of the selection. Фон определяется в центре выделения. + The closest color that passes {level}: click to apply it. Ближайший цвет, соответствующий {level}: щёлкните, чтобы применить его. Graphics Processor Графический процессор Graphics: {adapter} Графика: {adapter} Gravity Гравитация diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 37292b64ee..6e47263e1c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1495,6 +1495,7 @@ font-technology Variable Variabla Fail Underkänd WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11). The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen. + The closest color that passes {level}: click to apply it. Den närmaste färgen som klarar {level}: klicka för att använda den. Graphics Processor Grafikprocessor Graphics: {adapter} Grafik: {adapter} Gravity Gravitation diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fd72402419..75c89b5a0d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1453,6 +1453,7 @@ font-technology Variable Değişken Fail Kaldı WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11). The background is read at the center of the selection. Arka plan seçimin ortasında okunur. + The closest color that passes {level}: click to apply it. {level} düzeyini karşılayan en yakın renk: uygulamak için tıklayın. Graphics Processor Grafik İşlemcisi Graphics: {adapter} Grafik: {adapter} Gravity Yerçekimi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eedbd4ca26..e46c5e9175 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1555,6 +1555,7 @@ file-filter Templates Шаблони Fail Не відповідає WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11). The background is read at the center of the selection. Фон визначається в центрі виділення. + The closest color that passes {level}: click to apply it. Найближчий колір, що відповідає {level}: клацніть, щоб застосувати його. Graphics Processor Графічний процесор Graphics: {adapter} Графіка: {adapter} Gravity Гравітація diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4816d2ebaa..03793d07d4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1785,6 +1785,7 @@ file-filter Templates Mẫu Fail Không đạt WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11). The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn. + The closest color that passes {level}: click to apply it. Màu gần nhất đạt {level}: bấm để áp dụng. Graphics Processor Bộ xử lý đồ họa Graphics: {adapter} Đồ họa: {adapter} Gravity Trọng lực diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3049598865..a9ebbfc8b3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1490,6 +1490,7 @@ file-filter Templates 模板 Fail 未通过 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。 The background is read at the center of the selection. 背景在所选对象的中心读取。 + The closest color that passes {level}: click to apply it. 符合 {level} 的最接近颜色:单击即可应用。 Gravity 重力 Grays 灰度级数 Grays and Neutrals 灰色和中性色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 17e10e55f3..7b28293be5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1525,6 +1525,7 @@ file-filter Templates 範本 Fail 未通過 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。 The background is read at the center of the selection. 背景在選取範圍的中心讀取。 + The closest color that passes {level}: click to apply it. 符合 {level} 的最接近顏色:按一下即可套用。 Graphics Processor 圖形處理器 Graphics: {adapter} 圖形:{adapter} Gravity 重力 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 31dc6307c6..214ecdb392 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -786,6 +786,8 @@ mod tests_color_wheel_box; #[cfg(test)] mod tests_color_wheel_contrast; #[cfg(test)] +mod tests_color_wheel_contrast_lines; +#[cfg(test)] mod tests_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 5bc807f4bb..38cfaf1bc0 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -16,14 +16,20 @@ //! () of the color against the color drawn //! behind the selection, or against a color pinned with Contrast Background › Current Color, and //! whether it meets AA and AAA for the category picked under Contrast For (`color.contrast`). +//! The wheel's square and the box's field then draw lines where the color picked there would meet +//! AA and AAA (AAA dashed), and when the color fails, a chip in the row offers the closest color +//! that passes, the one `color.contrast` answers as `fix`. -use egui::{Ui, UiBuilder, vec2}; +use std::collections::HashMap; + +use egui::{Color32, Rect, Stroke, Ui, UiBuilder, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; use vectorcraft_color::wcag::{self, Category}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; +use vectorcraft_engine::cmd::{Backdrop, contrast_measure}; use super::color::{Target, apply, wheel_target}; use super::{color_json, pstate, set_pstate}; @@ -273,15 +279,19 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { /// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with /// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, -/// and its phase. -fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { +/// and its phase, and the field's rect. +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> (Option<([f32; 3], Live)>, Rect) { let (z, x, y) = box_pos(ch, hsb); let mut pick = None; + let mut field_rect = Rect::NOTHING; ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = STRIP_GAP; let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); - if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { + let picked = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at); + // The field is the first thing in the row. + field_rect = Rect::from_min_size(ui.min_rect().min, field); + if let (Some((x, y)), phase) = picked { pick = Some((box_pick(ch, z, x, y, hsb), phase)); } // The hue strip shows the whole spectrum; the others change only their own component. @@ -294,7 +304,7 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> _ => {} } }); - pick + (pick, field_rect) } /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. @@ -313,9 +323,217 @@ type BehindKey = (u64, u64, Vec, Option>, String, Under); /// What the contrast row's answer depends on: the background, the active proxy's paint (with nothing /// selected it is the default for new art, which no revision counts), the document, its revision, /// the selection and its picked symbol object, the proxy, the appearance item, the selected -/// gradient stop and freeform point, the on-screen Appearance of Black and the color settings. +/// gradient stop and freeform point, the on-screen Appearance of Black, the color settings and the +/// Contrast For category, which the closest passing colors are for. pub(super) type RatioKey = - (String, String, Option<(u64, u64)>, Vec, Option>, bool, Option, Option, Option, String, Under); + (String, String, Option<(u64, u64)>, Vec, Option>, bool, Option, Option, Option, String, Under, Category); + +/// Panel state: what the contrast row's answer was measured against, with its [`RatioKey`]. +const BACKDROP: &str = "color-wheel-backdrop"; +/// Panel state: the contrast lines of the square or the field, with the [`LinesKey`] they were +/// found for. +pub(super) const LINES: &str = "color-wheel-lines"; +/// What the contrast lines depend on: what the color is measured against, the category, the field +/// (the view, the channel and the component the field holds fixed) with the model a pick there +/// stores, and the color settings. +pub(super) type LinesKey = (Backdrop, Category, String, Under); +/// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates. +pub(super) type Lines = Vec>>; + +/// The columns and rows at which [`contrast_lines`] samples a field. +const LINE_SAMPLES: usize = 32; +/// The halvings that place a line on the edge between two samples. +const LINE_STEPS: usize = 10; + +/// A point of a field: x across, y down, 0 to 1 each. +type FieldPoint = (f32, f32); + +/// The passing bands found between the samples of one column or row: where each peaks along it, and +/// its two crossings. +type Bands = Vec<(f32, FieldPoint, FieldPoint)>; + +/// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in +/// field coordinates. The field is sampled on a 33 × 33 grid, and each cell whose corners fall on +/// both sides gets a segment between the crossings on its edges, placed by bisection (marching +/// squares; a cell with two opposite corners passing is split by its center). Around a failing +/// sample higher than its neighbors in a column or a row, the highest ratio is looked for, so a +/// passing band narrower than the samples gets its two edges too, joined from column to column or +/// from row to row. Segments that share an end are joined into one polyline. +pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64]) -> Lines { + let n = LINE_SAMPLES; + let at = |i: usize| i as f32 / n as f32; + // `grid[i][j]` is column i (x) and row j (y). + let grid: Vec> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect(); + let r = |i: usize, j: usize| grid.get(i).and_then(|c| c.get(j)).copied().unwrap_or(f64::NAN); + minimums + .iter() + .map(|&min| { + let pass = |p: FieldPoint| ratio_at(p.0, p.1) >= min; + // The crossing between `p`, on the side `above` says, and `q`. + let cross = |p: FieldPoint, q: FieldPoint, above: bool| { + let lerp = |t: f32| (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t); + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..LINE_STEPS { + let mid = (lo + hi) / 2.0; + if pass(lerp(mid)) == above { lo = mid } else { hi = mid } + } + lerp((lo + hi) / 2.0) + }; + let mut edges: HashMap<(usize, usize, bool), Option> = HashMap::new(); + // The crossing on the edge from sample (i, j) across (`across`) or down. + let mut edge = |i: usize, j: usize, across: bool| { + *edges.entry((i, j, across)).or_insert_with(|| { + let (i2, j2) = if across { (i + 1, j) } else { (i, j + 1) }; + let (a, b) = (r(i, j) >= min, r(i2, j2) >= min); + (a != b).then(|| cross((at(i), at(j)), (at(i2), at(j2)), a)) + }) + }; + let mut segments: Vec<[FieldPoint; 2]> = vec![]; + for i in 0..n { + for j in 0..n { + let (top, right, bottom, left) = (edge(i, j, true), edge(i + 1, j, false), edge(i, j + 1, true), edge(i, j, false)); + match (top, right, bottom, left) { + (Some(t), Some(rt), Some(b), Some(l)) => { + // Opposite corners pass: the center says which pair of them it joins. + let half = 0.5 / n as f32; + if pass((at(i) + half, at(j) + half)) == (r(i, j) >= min) { + segments.extend([[t, rt], [b, l]]); + } else { + segments.extend([[t, l], [rt, b]]); + } + } + _ => { + let found: Vec = [top, right, bottom, left].into_iter().flatten().collect(); + if let &[p, q] = found.as_slice() { + segments.push([p, q]); + } + } + } + } + } + // Bands narrower than the samples, along each column and then each row. + for across in [false, true] { + let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) }; + let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) }; + let bands: Vec = (0..=n) + .map(|k| { + let mut found = vec![]; + for s in 0..=n { + let (before, after) = (s.saturating_sub(1), (s + 1).min(n)); + let v = value(k, s); + if v >= min || v < value(k, before) || (after != s && v <= value(k, after)) { + continue; + } + let peak = wcag::peak_between(f64::from(at(before)), f64::from(at(after)), &|t| { + let p = point(k, t as f32); + ratio_at(p.0, p.1) + }) as f32; + if pass(point(k, peak)) { + found.push(( + peak, + cross(point(k, at(before)), point(k, peak), false), + cross(point(k, peak), point(k, at(after)), true), + )); + } + } + found + }) + .collect(); + for pair in bands.windows(2) { + let [this, next] = pair else { continue }; + for (peak, a, b) in this { + if let Some((_, c, d)) = next.iter().find(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32) { + segments.extend([[*a, *c], [*b, *d]]); + } + } + } + } + chain(segments) + }) + .collect() +} + +/// `segments` joined end to end into polylines where they share an end. +fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec> { + let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits()); + let mut ends: HashMap<(u32, u32), Vec> = HashMap::new(); + for (s, seg) in segments.iter().enumerate() { + for p in seg { + ends.entry(key(*p)).or_default().push(s); + } + } + let mut used = vec![false; segments.len()]; + let mut lines = vec![]; + for (start, [a, b]) in segments.iter().enumerate() { + if used.get(start).copied().unwrap_or(true) { + continue; + } + if let Some(u) = used.get_mut(start) { + *u = true; + } + let mut line = std::collections::VecDeque::from([*a, *b]); + for back in [true, false] { + loop { + let end = if back { line.back() } else { line.front() }; + let Some(end) = end.copied() else { break }; + let next = ends.get(&key(end)).and_then(|ss| ss.iter().copied().find(|s| !used.get(*s).copied().unwrap_or(true))); + let Some((s, [p, q])) = next.and_then(|s| segments.get(s).map(|seg| (s, *seg))) else { break }; + if let Some(u) = used.get_mut(s) { + *u = true; + } + let other = if key(p) == key(end) { q } else { p }; + if back { line.push_back(other) } else { line.push_front(other) } + } + } + lines.push(line.into_iter().collect()); + } + lines +} + +/// The contrast lines of the wheel's square or the box's field on HSB `hsb`, kept per [`LinesKey`]: +/// where a pick there, stored as the wheel stores it in place of `tgt`'s color, meets each minimum +/// of the chosen category against `backdrop`. +fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, hsb: [f32; 3], cmyk_doc: bool) -> Lines { + let set = &app.ui.color_wheel; + let (category, view, ch) = (set.contrast_for, set.view, set.channel); + let was = replaced(app, tgt, false); + // The component the field holds fixed: the box's strip value, or the wheel's hue. + let fixed = if view == View::Box { box_pos(ch, hsb).0 } else { hsb[0] }; + let field = format!("{view:?} {ch:?} {fixed} {:?} {cmyk_doc}", was.map(|c| c.model())); + let key: LinesKey = (backdrop.clone(), category, field, under()); + if let Some((k, lines)) = pstate::>(ui.ctx(), LINES) + && k == key + { + return lines; + } + let cms = cms::active(); + let at = |x: f32, y: f32| if view == View::Box { box_pick(ch, fixed, x, y, hsb) } else { [hsb[0], x, 1.0 - y] }; + let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc)))); + let (aa, aaa) = category.minimums(); + let minimums: Vec = std::iter::once(aa).chain(aaa).collect(); + let lines = contrast_lines(&ratio_at, &minimums); + set_pstate(ui.ctx(), LINES, Some((key, lines.clone()))); + lines +} + +/// Draw `lines` (from [`contrast_lines`]) over the field in `rect`: AA solid and AAA dashed, each +/// a light line over a dark one, as the field's marker is drawn. +fn draw_contrast_lines(ui: &Ui, rect: Rect, lines: &Lines) { + let painter = ui.painter().with_clip_rect(rect); + let at = |(x, y): &(f32, f32)| egui::pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height()); + for (level, polylines) in lines.iter().enumerate() { + for line in polylines { + let points: Vec = line.iter().map(at).collect(); + for stroke in [Stroke::new(3.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] { + if level == 0 { + painter.add(egui::Shape::line(points.clone(), stroke)); + } else { + painter.extend(egui::Shape::dashed_line(&points, stroke, 4.0, 3.0)); + } + } + } + } +} /// The active color settings and profiles generation, which change how a color displays without /// a document revision (Edit › Color Settings, a document's assigned profiles). @@ -357,17 +575,24 @@ fn background(app: &mut VectorcraftApp, ui: &Ui) -> Option { Color::from_hex(&hex?) } -/// The contrast row: the background's chip, the ratio cut off at two decimals and the AA and AAA -/// results for the chosen category; a dash when there is no background or no color to measure. -/// Without a pinned background the row asks `color.contrast` for the color behind the selection -/// (`against: "below"`), also during an interaction, so translucent groups and layers count as the -/// command counts them; the chip then shows the background in the answer, else the pinned color or -/// the one kept by [`background`]. -fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { +/// The contrast row's measurement: the background it was measured against, `color.contrast`'s +/// answer for the chosen category, and what the lines measure picks against. +struct Measured { + against: Option, + answer: Option, + backdrop: Option, +} + +/// Measure the active color for the contrast row and the lines. Without a pinned background it +/// asks `color.contrast` for the color behind the selection (`against: "below"`), also during an +/// interaction, so translucent groups and layers count as the command counts them. The answer is +/// kept per [`RatioKey`]. +fn measure(app: &mut VectorcraftApp, ui: &Ui) -> Measured { let category = app.ui.color_wheel.contrast_for; let pinned = app.ui.color_wheel.contrast_background.is_some(); let against = background(app, ui); let sampled = !pinned; + let mut backdrop = None; let answer = against.as_ref().and_then(|bg| { let st = app.session.active(); let key: RatioKey = ( @@ -382,27 +607,51 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { app.session.selected_freeform_point(), app.session.prefs.black_on_screen.clone(), under(), + category, ); - match pstate::)>>(ui.ctx(), RATIO) { - Some((k, r)) if k == key => r, + let kept = pstate::)>>(ui.ctx(), RATIO); + let kept_backdrop = pstate::)>>(ui.ctx(), BACKDROP); + match (kept, kept_backdrop) { + (Some((k, r)), Some((kb, b))) if k == key && kb == key => { + backdrop = b; + r + } _ => { let against = if sampled { json!("below") } else { color_json(bg) }; - let r = app.session.execute("color.contrast", &json!({ "against": against })).ok(); - set_pstate(ui.ctx(), RATIO, Some((key, r.clone()))); + let m = contrast_measure(&app.session, &json!({ "against": against, "for": category.id() })).ok(); + let (r, b) = m.map_or((None, None), |(r, b)| (Some(r), Some(b))); + set_pstate(ui.ctx(), RATIO, Some((key.clone(), r.clone()))); + set_pstate(ui.ctx(), BACKDROP, Some((key, b.clone()))); + backdrop = b; r } } }); + Measured { against, answer, backdrop } +} + +/// The contrast row: the background's chip, the ratio cut off at two decimals, the AA and AAA +/// results for the chosen category, and a chip of the closest color that passes the first level the +/// color fails; a dash when there is no background or no color to measure. Without a pinned +/// background the first chip shows the background in the answer, else the pinned color or the one +/// kept by [`background`]. The fix chip keeps its space while hidden. Returns the fix color when its +/// chip is clicked. +fn contrast_row(app: &VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option { + let category = app.ui.color_wheel.contrast_for; + let pinned = app.ui.color_wheel.contrast_background.is_some(); + let sampled = !pinned; + let (against, answer) = (m.against, m.answer.as_ref()); + let mut clicked = None; let resp = ui .horizontal(|ui| { let (rect, _) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::hover()); // The chip shows the background the ratio was measured against. - let measured = answer.as_ref().filter(|_| sampled).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); + let measured = answer.filter(|_| sampled).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); match measured.or(against) { Some(c) => widgets::swatch_tile(ui, rect, &Paint::solid(c), false, false), None => widgets::swatch_tile(ui, rect, &Paint::None, false, false), } - let Some(ratio) = answer.as_ref().and_then(|r| r["ratio"].as_f64()) else { + let Some(ratio) = answer.and_then(|r| r["ratio"].as_f64()) else { ui.label("—"); return; }; @@ -413,6 +662,7 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(aaa) = aaa { ui.label(format!("AAA {}", result(aaa))); } + clicked = fix_chip(ui, answer, aa, aaa); }) .response; let mut tip = tl!( @@ -424,6 +674,35 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { tip.push_str(tl!("The background is read at the center of the selection.")); } resp.on_hover_text(tip); + clicked +} + +/// The fix chip at the end of the contrast row: the closest color that passes AA when the color +/// fails AA (`aa`), else AAA when it fails AAA (`aaa`), from `color.contrast`'s `fix`. Its space is +/// kept while there is none, so the row does not move as a drag crosses a line. Returns the color +/// when the chip is clicked or activated. +fn fix_chip(ui: &mut Ui, answer: Option<&Value>, aa: bool, aaa: Option) -> Option { + let level = if !aa { + Some(("aa", "AA")) + } else if aaa == Some(false) { + Some(("aaa", "AAA")) + } else { + None + }; + let fix = level.and_then(|(key, name)| { + let v = answer?.get("fix")?.get(key)?; + serde_json::from_value::(v.clone()).ok().map(|c| (c, name)) + }); + let Some((color, name)) = fix else { + ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::hover()); + return None; + }; + let (rect, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::click()); + widgets::swatch_tile(ui, rect, &Paint::solid(color), false, false); + let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &label)); + let resp = resp.on_hover_text(&label); + resp.clicked().then_some(color) } /// What the HSB picked last belongs to: the document, the selected objects or text characters, @@ -528,7 +807,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); + let measured = app.ui.color_wheel.contrast.then(|| measure(app, ui)); let mut pick: Option<([f32; 3], Live)> = None; + let mut field_rect = Rect::NOTHING; ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(44.0); @@ -536,11 +817,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); let size = ui.available_width().min(MAX_WHEEL); if app.ui.color_wheel.view == View::Box { - pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); + (pick, field_rect) = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); return; } let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked); let square = widgets::ring_square(ring.rect); + field_rect = square; let mut field_ui = ui.new_child(UiBuilder::new().id_salt("color-wheel-square").max_rect(square)); let axes = [FieldAxis { name: tl!("Saturation"), units: 100.0, suffix: "%" }, FieldAxis { name: tl!("Brightness"), units: 100.0, suffix: "%" }]; @@ -562,12 +844,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); - if app.ui.color_wheel.contrast { - contrast_row(app, ui); + let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + if let Some(m) = &measured { + if let Some(backdrop) = &m.backdrop { + let lines = lines_for(app, ui, backdrop, &tgt, hsb, cmyk_doc); + draw_contrast_lines(ui, field_rect, &lines); + } + if let Some(c) = contrast_row(app, ui, m) { + apply(app, &tgt, c, Live::Released, false); + } } let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); - let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs new file mode 100644 index 0000000000..1418dc5fd2 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -0,0 +1,167 @@ +//! The Color Wheel panel's contrast lines on the box's field and the wheel's square, and the chip of +//! the closest passing color in the contrast row, drawn headless. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb}; +use vectorcraft_engine::Session; + +use super::color_wheel::{LINES, Lines, LinesKey, box_pick, show}; +use super::pstate; +use crate::VectorcraftApp; +use crate::dialogs::color_picker::Channel; + +/// An app with a selected rectangle filled with #FDC96E, the contrast row shown against a pinned +/// #355F78 (4.4963:1, just under AA for normal text), and `view` with `channel`. +fn app(view: &str, channel: &str) -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#fdc96e"})).unwrap(); + app.run("ui.colorWheel", json!({"contrast": true, "contrastBackground": "#355f78", "view": view, "channel": channel})).unwrap(); + app +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + // The height the panel took, for the test that checks nothing moves. + let h = ui.min_rect().height(); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("panel-height"), h)); + }, + app, + ); + h.run_steps(2); + h +} + +fn lines(h: &Harness<'static, VectorcraftApp>) -> Lines { + pstate::>(&h.ctx, LINES).expect("the field's contrast lines were found").1 +} + +/// Whether the color picked at field point (x, y) meets AA for normal text against #355F78, as +/// `color.contrast` answers it; `hsb_at` maps the point to the HSB the field picks there. +fn passes_aa(h: &mut Harness<'static, VectorcraftApp>, hsb_at: &dyn Fn(f32, f32) -> [f32; 3], (x, y): (f32, f32)) -> bool { + let [r, g, b] = hsb_to_rgb(hsb_at(x, y)); + let r = h.state_mut().session.execute("color.contrast", &json!({"color": [r, g, b], "against": "#355f78"})).unwrap(); + r["normalText"]["aa"].as_bool().unwrap() +} + +/// The middle point of the longest AA line, and the points a little above and below it. +fn either_side(lines: &Lines) -> [(f32, f32); 2] { + let aa = lines.first().expect("an AA level"); + let line = aa.iter().max_by_key(|l| l.len()).expect("an AA line"); + let (x, y) = line[line.len() / 2]; + [(x, (y - 0.04).max(0.0)), (x, (y + 0.04).min(1.0))] +} + +#[test] +fn the_box_marks_where_its_colors_meet_aa() { + let mut h = harness(app("box", "hue")); + let lines = lines(&h); + assert_eq!(lines.len(), 2, "AA and AAA for normal text"); + let hsb = vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap())); + let z = super::color_wheel::box_pos(Channel::Hue, hsb).0; + let at = move |x: f32, y: f32| box_pick(Channel::Hue, z, x, y, hsb); + let [above, below] = either_side(&lines); + let (a, b) = (passes_aa(&mut h, &at, above), passes_aa(&mut h, &at, below)); + assert_ne!(a, b, "the points either side of the line fall on either side of AA"); + // Against a dark background the lighter colors, at the top, pass. + assert!(a && !b); +} + +#[test] +fn the_wheels_square_marks_where_its_colors_meet_aa() { + let mut h = harness(app("wheel", "hue")); + let lines = lines(&h); + let hsb = vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap())); + let at = move |x: f32, y: f32| [hsb[0], x, 1.0 - y]; + let [above, below] = either_side(&lines); + assert!(passes_aa(&mut h, &at, above) && !passes_aa(&mut h, &at, below)); +} + +/// White with Difference over a pinned #757575: in the gray box (saturation 0) only grays within a +/// few hundredths of #757575 draw dark enough for AA, a band narrower than the samples. +#[test] +fn a_band_narrower_than_the_samples_gets_its_lines() { + let mut app = app("box", "saturation"); + app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap(); + app.run("transparency.set", json!({"blend": "difference"})).unwrap(); + app.run("ui.colorWheel", json!({"contrastBackground": "#757575"})).unwrap(); + let mut h = harness(app); + let lines = lines(&h); + let aa = lines.first().expect("an AA level"); + assert!(aa.len() >= 2, "a line on each side of the band: {aa:?}"); + h.state_mut().run("paint.setFill", json!({"color": "#757575"})).unwrap(); + let r = h.state_mut().session.execute("color.contrast", &json!({"against": "#757575"})).unwrap(); + assert!(r["normalText"]["aa"] == true, "#757575 draws black and passes: {r}"); +} + +/// Multiply over a pinned #FF0000 keeps only the red of a pick, so in the blue box (red across) +/// the contrast changes across and not up: the AA line runs top to bottom. +#[test] +fn a_line_that_runs_up_the_field_is_found() { + let mut app = app("box", "blue"); + app.run("transparency.set", json!({"blend": "multiply"})).unwrap(); + app.run("ui.colorWheel", json!({"contrastBackground": "#ff0000"})).unwrap(); + let h = harness(app); + let lines = lines(&h); + let line = lines.first().and_then(|aa| aa.iter().max_by_key(|l| l.len())).expect("an AA line"); + let (xs, ys): (Vec, Vec) = line.iter().copied().unzip(); + let spread = |v: &[f32]| v.iter().copied().fold(f32::NEG_INFINITY, f32::max) - v.iter().copied().fold(f32::INFINITY, f32::min); + assert!(spread(&ys) > 0.9 && spread(&xs) < 0.05, "{line:?}"); +} + +#[test] +fn graphics_have_one_line() { + let mut app = app("box", "saturation"); + app.run("ui.colorWheel", json!({"contrastFor": "graphics"})).unwrap(); + let h = harness(app); + assert_eq!(lines(&h).len(), 1, "graphics have AA only"); +} + +const CHIP: &str = "The closest color that passes AA: click to apply it."; + +#[test] +fn the_chip_applies_the_fix_color_answers() { + let mut h = harness(app("wheel", "hue")); + let want = h.state_mut().session.execute("color.contrast", &json!({"against": "#355f78"})).unwrap(); + let fix: Color = serde_json::from_value(want["fix"]["aa"].clone()).unwrap(); + h.get_by_label(CHIP).click(); + h.run_steps(2); + match h.state().session.proxy_paints().0 { + Paint::Solid { color, .. } => assert_eq!(color, fix), + other => panic!("the fill is {other:?}"), + } + assert!(h.query_by_label(CHIP).is_none(), "the color now passes AA: no chip"); + assert!(h.query_by_label("AA Pass").is_some()); +} + +#[test] +fn the_chip_offers_aaa_once_aa_passes_and_nothing_once_both_pass() { + let mut app = app("wheel", "hue"); + app.run("ui.colorWheel", json!({"contrastFor": "largeText"})).unwrap(); + let h = harness(app); + assert!(h.query_by_label(CHIP).is_none(), "4.49:1 meets large text AA"); + assert!(h.query_by_label("The closest color that passes AAA: click to apply it.").is_some()); + let mut app = self::app("wheel", "hue"); + app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap(); + app.run("ui.colorWheel", json!({"contrastFor": "largeText"})).unwrap(); + let h = harness(app); + assert!(h.query_by_label_contains("The closest color that passes").is_none()); +} + +#[test] +fn the_panel_keeps_its_height_when_the_chip_goes() { + let height = |fill: &str| { + let mut app = app("box", "hue"); + app.run("paint.setFill", json!({"color": fill})).unwrap(); + let h = harness(app); + h.ctx.data(|d| d.get_temp::(egui::Id::unique("panel-height"))).expect("a height") + }; + // #FDC96E fails AA and shows the chip; #FFFFFF passes both levels and hides it. + assert_eq!(height("#fdc96e"), height("#ffffff")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index efe976d74e..ac5900da54 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -234,11 +234,12 @@ its variation grid; the panel draws the same grid. `ui.colorGuideOptions` opens as `ui.color_guide` (`variation`, `steps`, `amount`). Save Colors as Swatches runs `swatch.new {colors: [...]}` (one swatch per colour, one undo step). -Color Wheel contrast: `color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio of the active -proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given color, -with the AA and AAA results for normal text, large text and graphics (docs/mcp.md). The Color Wheel panel's Show -Contrast row shows the same answer for the category picked under Contrast For; `ui.colorWheel {contrast?, contrastFor?, -contrastBackground?}` sets the row, its category and a pinned background, and `ui.inspect` reports them as +Color Wheel contrast: `color.contrast {color?, against?, opacity?, for?}` answers the WCAG 2 contrast ratio of the +active proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given +color, with the AA and AAA results for normal text, large text and graphics, and as `fix` the closest color of the same +hue that meets each level of the category `for` names (docs/mcp.md). The Color Wheel panel's Show Contrast row shows +the same answer for the category picked under Contrast For, with a chip of the fix color; `ui.colorWheel {contrast?, +contrastFor?, contrastBackground?}` sets the row, its category and a pinned background, and `ui.inspect` reports them as `ui.color_wheel`. Color Guide Limit to Library: `ui.colorGuideLimit {library}` (a swatch library id or name, `"document"` for the diff --git a/docs/mcp.md b/docs/mcp.md index 0a5f508969..051bd114b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -658,7 +658,10 @@ the list return an error and change nothing. `{"contrast": true}` shows Show Con box, `contrastFor` (`normalText`, `largeText` or `graphics`) picks the category its AA and AAA results are for, and `contrastBackground` (a color, or `null` for the color behind the selection) pins the background it measures against, as `color.contrast` below answers it. The command returns `{view, channel, contrast, contrastFor, -contrastBackground}`, and the settings are kept with the preferences. +contrastBackground}`, and the settings are kept with the preferences. With the row shown, the wheel's square and the +box's field draw lines where the color picked there meets AA (solid) and AAA (dashed) for the category, and when the +color fails a level, a chip at the end of the row shows `color.contrast`'s `fix` for the first level it fails; a click +applies it. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop @@ -1065,7 +1068,7 @@ panel's Limit to Library does (`ui.colorGuideLimit`); Recolor Artwork's `limitTo that is not a string, such as `5`, names no library and gets the same error as an unknown name; `null` or `""` sets no limit. -`color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio +`color.contrast {color?, against?, opacity?, for?}` answers the WCAG 2 contrast ratio ([definition](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio)) of a color against a background, from 1 to 21, and whether it meets AA and AAA for normal text (4.5:1 and 7:1), large text (3:1 and 4.5:1) and graphics (3:1, AA only): `{ratio, against, normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}`. The results compare the unrounded @@ -1087,7 +1090,12 @@ selected objects that draw one color with different blend modes, or at different `"below"`, also in different translucent groups or layers), where hidden objects do not count; and a proxy of None, a pattern or a hidden row without `color`. `against` in the answer is the background as a working RGB `#rrggbb`, the form `against` takes; the sampled background is rounded to 8 bits, so giving it back answers the same ratio. Headless MCP -answers it too. +answers it too. The answer also has `for` (the category `for` names: `normalText`, the default, `largeText` or +`graphics`) and `fix: {aa, aaa}` (no `aaa` for graphics): for each level of that category, the closest color that +meets it when drawn the same way, in the model of the measured color, as the Color Wheel stores a pick. The search +keeps the color's [OKLCH](https://bottosson.github.io/posts/oklab/) hue, raises or lowers its lightness, whichever +takes the smaller step, and lowers its chroma where sRGB cannot show it. A level is `null` when the color already meets +it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no color meets 7:1 there). Color Themes (local only: no online service) keeps five-colour themes in the preferences. `colorTheme.save {colors: [...]}` saves up to five colours as they are, `colorTheme.save {color, rule}` saves the five-colour theme a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d808656065..7049dd2e2a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1651,7 +1651,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Scores and estimates are unchanged. - The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics. `color.contrast` answers the same for agents. + The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics. `color.contrast` answers the same for agents. With the row shown, the wheel's square and the box's field draw the AA and AAA lines, and a chip in the row offers the closest color of the same hue that passes, which `color.contrast` answers as `fix`. - **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From 546d274e6eff61daba8934eadf884557fb3284e7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 07:18:04 +0000 Subject: [PATCH 002/104] .ai import: type takes the installed copy that sets its PDF part's widths When several installed faces answer to a text document font record's PostScript name and the record keeps no version (no key 5), type was set in whichever copy loaded first. Two copies can share the PostScript name, family and style and differ only in their widths (two releases of one font): the type then set at other widths than the file's own page, and envelopes of it could fail their drawn-art check. #6983 left this case out, as only the page's widths tell such copies apart. - `Opened::page_widths` (crates/pdf/src/page_widths.rs) reads the widths the pages give the characters of each font they set type in, from the font dictionaries alone and without importing any page: a simple font's `Widths` from `FirstChar`, a composite font's descendant's `W` under an `Identity-H`/`Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1 9.6.2, 9.7.4.3, 9.10.3, Annex D.2), by `BaseFont` without its subset tag. Zero widths (codes a subset doesn't use) are left out; subsets that give a character two widths give none. - Its cost is bounded by the file: each resource dictionary is walked once, however many pages and forms share it, within 65,536 entries for the whole file, 256 fonts and 4,096 forms; a width array that fonts share by reference is read once, and none past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one over 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. `cid_ranges` reads a `W` list's values as it takes them instead of collecting the whole list. A font's widths are shared, not copied. - `postscript_face` (crates/eps/src/import/text.rs) takes, among the faces of the record's name, the first that sets those characters (the first 512 in code-point order) each within 1/1000 em. With no widths, one face, a version in the record, or no face that sets them all, the pick is the one before. The face found first is checked before any other is loaded, and the records of one name and version share their widths and their answer, so each font resolves once whatever the number of records. - The widths reach the text document through `Structure::page_widths` and `Texts::with_page_widths`; the engine reads them once per open and passes them to `ai_layers_alone`, `AiLayers::with_page_widths` and `ai_alone_with` when it reads a `.ai`'s editing copy beside a PDF part (not for a placeholder page). - `without_subset_tag` replaces two copies of the subset-tag strip in the PDF import, and `replacement` (a `ToUnicode` value that names no character) is shared with it. - A fuzz target feeds hostile font dictionaries, `ToUnicode` maps and forms that draw themselves to the reader. Measured on 224 users' files (used locally, never committed): 3 font records in 3 files change copy, each now within 0.5/1000 em of its page; those 3 renders, and no others, change, all closer to the file's own page; envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way. Refs #6983 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/fileio/load.rs | 24 +- .../engine/src/cmd/fileio/tests_aiimport.rs | 107 ++++ crates/engine/tests/import_fuzz.rs | 55 +- crates/eps/src/ai_editing/writer/texts.rs | 4 +- crates/eps/src/import/ai/legacy_text.rs | 2 +- crates/eps/src/import/ai/read.rs | 4 + crates/eps/src/import/ai/read/document.rs | 1 + crates/eps/src/import/ate.rs | 68 +- crates/eps/src/import/native/build.rs | 25 +- crates/eps/src/import/native/layers.rs | 69 +- crates/eps/src/import/tests_native.rs | 117 +++- crates/eps/src/import/text.rs | 69 +- crates/pdf/src/import.rs | 1 + crates/pdf/src/import/builder.rs | 6 +- crates/pdf/src/import/cid.rs | 2 +- crates/pdf/src/import_scan.rs | 28 +- crates/pdf/src/import_text.rs | 6 +- crates/pdf/src/lib.rs | 2 + crates/pdf/src/page_widths.rs | 598 ++++++++++++++++++ crates/pdf/src/pages.rs | 7 + docs/file-format-parity.md | 5 +- docs/target-app-parity.md | 3 +- 22 files changed, 1111 insertions(+), 92 deletions(-) create mode 100644 crates/pdf/src/page_widths.rs diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index ff0e14c40d..1e8cfdbe7d 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -255,12 +255,15 @@ fn from_editing_data_alone(opened: &vectorcraft_pdf::Opened, opts: &LoadOptions) return None; } let private = opened.illustrator_data()?; - Some(editing_copy_alone(&private, opts)) + // A placeholder page's fonts aren't the art's. + Some(editing_copy_alone(&private, opts, Default::default())) } -/// [`from_editing_data_alone`] of `private`, the editor's copy already read. -fn editing_copy_alone(private: &[u8], opts: &LoadOptions) -> Result<(Document, Vec)> { - vectorcraft_eps::ai_alone_with(private, opts.legacy_names) +/// [`from_editing_data_alone`] of `private`, the editor's copy already read, with `widths`, the +/// widths the file's PDF part gives the characters of its fonts, which tell installed copies of a +/// font apart ([`vectorcraft_eps::AiLayers::with_page_widths`]). +fn editing_copy_alone(private: &[u8], opts: &LoadOptions, widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec)> { + vectorcraft_eps::ai_alone_with(private, opts.legacy_names, widths) .map_err(|why| err(format!("this file was saved without PDF compatibility, and its editing data can't be read ({why})"))) } @@ -444,6 +447,10 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result Err(e) => Err(err(e)), }; let mut read = restore_or_import(editing, || { + // The widths the PDF part gives the characters of its fonts, which tell installed + // copies of a font apart: read once, when the editing copy is. + let page_widths = std::cell::OnceCell::new(); + let widths = || page_widths.get_or_init(|| opened.as_ref().map(vectorcraft_pdf::Opened::page_widths).unwrap_or_default()).clone(); // 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. @@ -451,7 +458,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result 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, opts.legacy_names) { + match vectorcraft_eps::ai_layers_alone(&private, &pages.sizes, pages.user_unit, opts.legacy_names, widths()) { Ok((mut doc, warnings)) => { doc.setup.bleed = pages.bleed; editing_data = true; @@ -473,9 +480,9 @@ 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 copy_alone = || match &private { - Some(private) => Some(editing_copy_alone(private, opts)), + Some(private) => Some(editing_copy_alone(private, opts, widths())), None if layers.is_some() => { - opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts)) + opened.as_ref().ok().and_then(|o| editing_copy(o, opts)).map(|p| editing_copy_alone(&p, opts, widths())) } None => None, }; @@ -487,7 +494,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result 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)); + let layers = + layers.or_else(|| private.as_deref().map(|p| vectorcraft_eps::AiLayers::decode(p).with_page_widths(widths()))); through_editing_data(layers, opts, r.document, r.warnings, r.user_unit) } }; diff --git a/crates/engine/src/cmd/fileio/tests_aiimport.rs b/crates/engine/src/cmd/fileio/tests_aiimport.rs index 9d263c8c97..0274232b91 100644 --- a/crates/engine/src/cmd/fileio/tests_aiimport.rs +++ b/crates/engine/src/cmd/fileio/tests_aiimport.rs @@ -2072,3 +2072,110 @@ fn an_illustrator_ai_file_opens_with_its_layers_closed() { assert_eq!(r["restored"], json!(true), "{r}"); assert_eq!(open_rows(&s).1, ["Art", "Hidden"]); } + +/// A `.ai` whose layer `Art` holds one line of type, `Hamburg`, that its text document sets in the +/// font of PostScript name `name` (a font record without a version), and whose PDF part sets it in +/// a subset of that font that gives each character the width `width` gives it, in thousandths of an +/// em. With `square`, the layer and the page have a gray square too. The editing copy's artboard is +/// 200 × 100 pt, and the page `page_width` × 100. +fn type_in_copy_ai(name: &str, square: bool, page_width: f64, width: impl Fn(char) -> f64) -> Vec { + let story = "Hamburg"; + let n = story.chars().count() + 1; + let document = format!( + "/0 << /1 << /0 [ << /0 << /0 << /0 ({name}) >> >> >> ] >> /8 << /0 [ << /0 << /0 [ 0 0 ] /2 << /2 [ 1 0 0 1 0 0 ] >> >> >> ] >> >>\n\ + /1 << /1 [ << /0 << /0 ({story}\r) /5 << /0 [ << /0 << /0 << /0 () /5 << /0 0 >> /6 0 >> >> /1 {n} >> ] >> \ + /6 << /0 [ << /0 << /0 << /0 () /5 0 /6 << /0 0 /1 10.0 >> >> >> /1 {n} >> ] >> >> \ + /1 << /0 [ << /0 0 >> ] /2 [ << /99 /PC /6 [ << /99 /F /0 << /0 [ 8105.5 8176.5 ] >> /6 [ << /99 /R /6 [ << /99 /R /6 [ << /99 /L /6 [ \ + << /99 /S /0 << /0 [ 0.0 0.0 ] >> /15 << /0 {n} >> >> ] >> ] >> ] >> ] >> ] >> ] >> >> ] /2 << /1 12.0 >> >>\n" + ); + let lines: Vec = ascii85(document.as_bytes()).as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect(); + let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n"; + let (art, drawn) = + if square { (format!("0.5 g\n{}f\n{text}", ai::rect(120.0, 20.0, 160.0, 60.0)), "0.5 g 120 20 40 40 re f ") } else { (text.to_string(), "") }; + 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") + ); + let data = ai::editing_data(200.0, 100.0, &body); + let widths: Vec = (32u8..=126).map(char::from).map(|c| if story.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let page = PdfPage { + resources: format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ), + entries: format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(1)), + // A page that is only type, with its art box, isn't a placeholder. + art: Some([0.0, 0.0, page_width, 100.0]), + ..PdfPage::new(page_width, 100.0, &format!("{drawn}BT /F1 10 Tf 14 65 Td ({story}) Tj ET")) + }; + pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len())], None) +} + +/// Type from the text document of a `.ai` whose font record keeps no version, where two installed +/// copies of the font share its PostScript name, family and style and differ in their widths, is +/// set in the copy that sets its characters at the widths the file's PDF part gives them: whether +/// its layers open alone, with the PDF part imported, or from the editing copy alone because the PDF +/// part is only type (read after the layers alone, on a page of another size, were not used). +#[test] +fn type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewtest Ink", "PagewtestInk-Regular")); + let trim = LoadOptions { crop: vectorcraft_pdf::CropTo::Trim, ..Default::default() }; + // (a square beside the type, the page's width, the options, whether the PDF part is imported) + let cases = [ + (true, 200.0, &LoadOptions::default(), false), + (true, 200.0, &trim, true), + (false, 200.0, &LoadOptions::default(), false), + (false, 200.0, &trim, true), + (false, 260.0, &LoadOptions::default(), true), + ]; + for (square, page_width, opts, imported) in cases { + let file = type_in_copy_ai("PagewtestInk-Regular", square, page_width, &width); + let before = vectorcraft_pdf::imports_of(&file); + let loaded = load_with("copies.ai", &file, opts).unwrap(); + let case = format!("square {square}, page {page_width}, {:?}: {:?}", opts.crop, loaded.warnings); + assert!(loaded.editing_data, "{case}"); + assert_eq!(vectorcraft_pdf::imports_of(&file) > before, imported, "{case}"); + let art = loaded.doc.layers[0].children().unwrap(); + assert_eq!(art.len(), 1 + usize::from(square), "{case}"); + let Some(NodeKind::Text(t)) = art.iter().map(|n| &n.kind).find(|k| matches!(k, NodeKind::Text(_))) else { panic!("type: {case}") }; + assert_eq!(t.plain_text(), "Hamburg"); + assert_eq!(db.style_face(&t.runs[0].style).unwrap().version, "1.1", "{case}"); + } +} + +/// Installs two copies of family `family` and PostScript name `name`: Inter as version 1.0, loaded +/// first, and Source Sans 3 as 1.1, whose advances (thousandths of an em) the returned function gives. +fn install_width_copies(family: &str, name: &str) -> impl Fn(char) -> f64 + use<> { + let db = vectorcraft_text::FontDb::global(); + for (inter, version) in [(true, "1.0"), (false, "1.1")] { + let font = vectorcraft_text::test_fonts::named_copy(inter, (family, "Regular", version, name)).unwrap(); + assert_eq!(db.add_font(font), 1); + } + let newer = db.postscript_faces(name).into_iter().find(|f| f.version == "1.1").unwrap(); + move |c: char| newer.advance(newer.glyph_for(c)) * 1000.0 / newer.units_per_em() +} + +/// Type the PDF part's widths set in the second copy of its font is saved as `.ai` with that +/// copy's version in its font record, so it opens in the same copy again, from the editing copy +/// alone as from the whole file. +#[test] +fn type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save() { + let (db, width) = (vectorcraft_text::FontDb::global(), install_width_copies("Pagewrt Ink", "PagewrtInk-Regular")); + let mut s = Session::new(); + let r = open(&mut s, "copies.ai", &type_in_copy_ai("PagewrtInk-Regular", true, 200.0, &width), json!({})).unwrap(); + let saved = s.execute("file.saveCopy", &json!({"format": "ai"})).unwrap(); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let versions = |doc: &vectorcraft_doc::Document| -> Vec { + let art = doc.layers[0].children().unwrap(); + art.iter() + .filter_map(|n| if let NodeKind::Text(t) = &n.kind { Some(db.style_face(&t.runs[0].style).unwrap().version.clone()) } else { None }) + .collect() + }; + assert_eq!(versions(&s.doc().unwrap().doc), ["1.1"], "{r}"); + let loaded = load_with("saved.ai", &bytes, &LoadOptions { native: false, ..Default::default() }).unwrap(); + assert!(loaded.editing_data, "{:?}", loaded.warnings); + assert_eq!(versions(&loaded.doc), ["1.1"], "{:?}", loaded.warnings); + let private = vectorcraft_pdf::illustrator_data(&bytes, None).unwrap(); + assert_eq!(versions(&vectorcraft_eps::ai_alone(&private).unwrap().0), ["1.1"]); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 058476d071..dd124c59ed 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -6,7 +6,8 @@ //! of every kind with random contents) opened, placed or pasted, nor PICT pictures (damaged files, //! opcodes with random contents) opened or placed, nor EPS and PostScript files //! (damaged ones, hostile programs) read by the PostScript interpreter, nor the editing data of -//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor Affinity documents +//! Illustrator EPS and `.ai` files (the layers they carry, damaged or hostile), nor the widths a +//! `.ai`'s PDF part gives its fonts' characters (hostile font dictionaries), nor Affinity documents //! (mutated object streams, archives and indexed PNG previews, hostile image dimensions), nor the //! font files a folder search reads (damaged fonts, collections whose headers give any count of //! faces), nor scripts written for the reference app checked without running them (garbage, @@ -896,6 +897,58 @@ proptest! { } } +/// A font dictionary whose widths are hostile, for [`vectorcraft_pdf::Opened::page_widths`]: any +/// subtype, encoding and first code, widths that are huge, negative or not numbers, a composite +/// font's `W` of any shape, and the `ToUnicode` map of object 5. +fn arb_width_font() -> impl Strategy { + ( + prop::sample::select(vec!["/TrueType", "/Type1", "/Type0", "/Type3", "/MMType1", "7"]), + prop::sample::select(vec!["/WinAnsiEncoding", "/Identity-H", "/Identity-V", "/MacRomanEncoding", "<< /Differences [65 /A] >>", "null"]), + prop::sample::select(vec!["0", "65", "-5", "255", "256", "4294967295", "1e30", "/X"]), + prop::collection::vec(prop::sample::select(vec!["500", "0", "-1", "1e40", "NaN", "null", "[1 2]", "/W"]), 0..12), + prop::collection::vec(prop::sample::select(vec!["1", "[500 600]", "65", "4294967295", "300", "-1", "[]", "1e9", "0 65535 7"]), 0..10), + prop::sample::select(vec!["/ABCDEF+Fuzz", "/Fuzz", "/ABCDEF+", "/+", "()", "/Fuzz-Identity-H"]), + any::(), + ) + .prop_map(|(subtype, encoding, first, widths, w, name, mapped)| { + let map = if mapped { "/ToUnicode 5 0 R" } else { "" }; + format!( + "<< /Type /Font /Subtype {subtype} /BaseFont {name} /Encoding {encoding} /FirstChar {first} /Widths [{}] {map} \ + /DescendantFonts [<< /Subtype /CIDFontType2 /BaseFont {name} /W [{}] >>] >>", + widths.join(" "), + w.join(" ") + ) + }) +} + +proptest! { + #![proptest_config(config())] + + /// The widths a page's fonts give their characters (read for a `.ai`'s text document) are read + /// without a panic from hostile font dictionaries, `ToUnicode` maps of any text, and forms that + /// draw themselves. + #[test] + fn pdf_font_widths_never_panic( + fonts in prop::collection::vec(arb_width_font(), 1..4), + cmap in prop::collection::vec(prop::sample::select(vec![ + "begincmap", "1 begincodespacerange", "<0000> ", "<00> ", "endcodespacerange", "2 beginbfchar", "<0001> <0041>", + "<0002> ", "<41> ", "1 beginbfrange", "<0000> <0000>", " <0000> <0041>", "<0001> <0003> [<0041> <0042>]", + "endbfrange", "endbfchar", "endcmap", "/Identity-H usecmap", "99999999999 beginbfchar", + ]), 0..12), + ) { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + let map = cmap.join("\n"); + let form = format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /Font << /F0 {} >> /XObject << /X0 6 0 R >> >> /Length 0 >>\nstream\n\nendstream", + fonts[0] + ); + let more = [format!("<< /Length {} >>\nstream\n{map}\nendstream", map.len() + 1).into_bytes(), form.into_bytes()]; + let pdf = handmade_pdf_with("", &format!("<< /Font << {} >> /XObject << /X0 6 0 R >> >>", list.join(" ")), "[0 0 100 100]", &more); + let read = catch_quiet(|| vectorcraft_pdf::open_pdf(&pdf, None).ok().map(|o| o.page_widths())); + prop_assert!(read.is_ok(), "{fonts:?} {cmap:?}: {read:?}"); + } +} + /// A dictionary value: one the reader reads, or one it skips over but can't parse (a name with a /// broken `#` escape, a number with a stray `-`). fn arb_dict_value() -> impl Strategy { diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..d7a85dee26 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -612,7 +612,7 @@ fn font_name(st: &CharStyle) -> FontRecord { .collect(); let name = face.postscript_name(); // The reader takes the face of a name alone as `postscript_face` finds it. - let by_name = crate::import::postscript_face(&name, None).is_some_and(|f| f.id() == face.id()); + let by_name = crate::import::postscript_face(&name, None, None).is_some_and(|f| f.id() == face.id()); let version = if design.is_empty() && by_name { String::new() } else { face.version.clone() }; FontRecord { name, truetype: face.is_truetype(), design, version } } @@ -659,7 +659,7 @@ fn fixed(v: f32) -> i64 { fn font_kept(st: &CharStyle) -> bool { let record = font_name(st); let version = crate::import::record_version(&record.version); - let (family, style, read) = crate::import::document_font(&record.name, version); + let (family, style, read) = crate::import::document_font(&record.name, version, None); let db = vectorcraft_text::FontDb::global(); let face = |family: &str, style: &str, version: Option<&str>| db.face_version(family, style, version).map(|f| f.id()); family == st.font_family diff --git a/crates/eps/src/import/ai/legacy_text.rs b/crates/eps/src/import/ai/legacy_text.rs index a3864b43d0..e35f61cb54 100644 --- a/crates/eps/src/import/ai/legacy_text.rs +++ b/crates/eps/src/import/ai/legacy_text.rs @@ -564,7 +564,7 @@ impl Reader<'_> { st.cmap = cmap; // The installed face of that PostScript name, as type from a text document // takes it; else the name split into a family and style. - let text = super::super::super::text::named_font(name, None); + let text = super::super::super::text::named_font(name, None, None); let (family, style, version) = text.unwrap_or_else(|| { let (family, style) = super::super::super::text::family_style(name); (family, style, None) diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index b045dd128f..7433243a10 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -217,6 +217,10 @@ pub struct Structure { /// name of the art style that gives each: the styles that are one paint, a pattern this read /// (see `ate::Texts::with_patterns`). pub text_patterns: HashMap, + /// The widths a `.ai`'s PDF part gives the characters of its fonts, which tell installed copies + /// of a font apart for type whose font record keeps no version (see + /// `ate::Texts::with_page_widths`): none until the importer sets them. + pub page_widths: vectorcraft_pdf::PageWidths, /// The file's `%AI24_LargeCanvasScale` (1 when it declares none), applied or not. pub canvas_scale: f64, /// The data's symbols are at their own size, whatever its scale: VectorCraft wrote it (its diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 258d7d584b..06e2de112e 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -1395,6 +1395,7 @@ impl<'a> Reader<'a> { }, styles_read, text_patterns, + page_widths: Default::default(), canvas_scale: self.canvas_scale, symbols_own_size: self.symbols_own_size, xml_ids: self.xml_ids, diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index c971b250f2..9cb3273803 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -23,6 +23,7 @@ //! a layout has its point type's anchor at its frame's point. See [`Story::place`]. use std::collections::{BTreeMap, HashMap}; +use std::sync::Arc; use kurbo::{BezPath, CubicBez, ParamCurve, ParamCurveArclen}; use vectorcraft_color::{Color, Paint}; @@ -564,15 +565,20 @@ struct DocFont { /// Key 5, when the record keeps it: the font's version string (name ID 5), which tells installed /// copies of one font apart. version: Option, - /// [`Self::font`]'s answer, found once for every run that names the record. - font: std::sync::OnceLock, + /// The widths the file's page gives the font's characters, when it has them + /// ([`Texts::with_page_widths`]): without a version, they tell the copies apart. Every record + /// of the font shares them. + widths: Option>, + /// [`Self::font`]'s answer, found once for every run that names the record, and shared by the + /// records of the same name and version, which give the same answer. + font: Arc>, } impl DocFont { /// The font type set in this record's font takes: the installed copy it names /// ([`super::text::document_font`]). fn font(&self) -> &Font { - self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref())) + self.font.get_or_init(|| super::text::document_font(&self.name, self.version.as_deref(), self.widths.as_deref())) } } @@ -616,6 +622,17 @@ impl Texts { Texts { patterns, ..self } } + /// The text document with the widths `page` (the file's page, [`vectorcraft_pdf::PageWidths`]) + /// gives the characters of its fonts, by each record's PostScript name: a record that keeps no + /// version is set in the installed copy of its font that sets them at those widths + /// ([`super::text::postscript_face`]). + pub(super) fn with_page_widths(mut self, page: &vectorcraft_pdf::PageWidths) -> Texts { + for f in &mut self.fonts { + f.widths = page.widths(super::text::bare_name(&f.name)).cloned(); + } + self + } + /// The text document in the editing copy `data`, if it has one that can be read. pub(super) fn read(data: &[u8]) -> Option { fn find(h: &[u8], n: &[u8], from: usize) -> Option { @@ -643,6 +660,8 @@ impl Texts { return None; } let doc = names::numbered(read(&bytes)?); + // Records of one name and version share their answer. + let mut answers: HashMap<(String, Option), Arc>> = HashMap::new(); let fonts = doc .get("0")? .get("1")? @@ -652,11 +671,10 @@ impl Texts { .map(|f| { let record = f.get("0").and_then(|f| f.get("0")); let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); - DocFont { - name: text("0").unwrap_or_default().to_string(), - version: text("5").and_then(record_version).map(str::to_string), - font: std::sync::OnceLock::new(), - } + let name = text("0").unwrap_or_default().to_string(); + let version = text("5").and_then(record_version).map(str::to_string); + let font = answers.entry((name.clone(), version.clone())).or_default().clone(); + DocFont { name, version, widths: None, font } }) .collect(); let main = doc.get("1")?; @@ -1592,6 +1610,40 @@ fn art_scale(to_doc: Affine) -> f64 { mod tests { use super::*; + /// The records of a text document's font list that name one font share the widths the file's + /// page gives it and the face they resolve to, however many there are: 20,000 records of a font + /// whose page gives 4,096 characters hold one copy of those widths, and resolve once. A record + /// of another version is resolved apart. + #[test] + fn records_of_one_font_share_its_page_widths_and_answer() { + let n = 20_000; + let records = "<< /0 << /0 << /0 (Sharetest-Regular) >> >> >> ".repeat(n) + "<< /0 << /0 << /0 (Sharetest-Regular) /5 (2.0) >> >> >>"; + let doc = format!("/0 << /1 << /0 [ {records} ] >> /8 << /0 [ ] >> >>\n/1 << /1 [ ] /2 << >> >>\n"); + let data = + format!("%AI11_BeginTextDocument\n/AI11TextDocument : /ASCII85Decode ,\n{}\n%AI11_EndTextDocument\n", crate::ps::ascii85(doc.as_bytes())); + let mut cmap = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n16 beginbfrange\n"); + for hi in 1..=16u32 { + cmap.push_str(&format!("<{hi:02X}00> <{hi:02X}FF> <{hi:02X}00>\n")); + } + cmap.push_str("endbfrange\nendcmap\n"); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+Sharetest-Regular /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+Sharetest-Regular /W [256 4351 500] >>] >> >>" + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let pdf = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + let widths = vectorcraft_pdf::open_pdf(&pdf, None).unwrap().page_widths(); + let shared = widths.widths("Sharetest-Regular").unwrap(); + assert_eq!(shared.len(), 4096); + let texts = Texts::read(data.as_bytes()).unwrap().with_page_widths(&widths); + assert_eq!(texts.fonts.len(), n + 1); + assert!(texts.fonts.iter().all(|f| f.widths.as_ref().is_some_and(|w| Arc::ptr_eq(w, shared)))); + let first = &texts.fonts[0].font; + assert!(texts.fonts[..n].iter().all(|f| Arc::ptr_eq(&f.font, first))); + assert!(texts.fonts.last().is_some_and(|f| !Arc::ptr_eq(&f.font, first)), "another version resolves apart"); + } + #[test] fn right_to_left_paragraphs_swap_left_and_right_alignment() { let texts = Texts { diff --git a/crates/eps/src/import/native/build.rs b/crates/eps/src/import/native/build.rs index 86d6976d89..5374730368 100644 --- a/crates/eps/src/import/native/build.rs +++ b/crates/eps/src/import/native/build.rs @@ -178,17 +178,25 @@ impl ReadText { self.frames.get_or_insert_with(|| ai::text_frames(data)) } - /// The text document of `data` ([`Texts::read`]), if it has one that can be read. - fn texts(&mut self, data: &[u8]) -> Option<&Texts> { + /// The text document of `data` ([`Texts::read`]), if it has one that can be read, with the widths + /// `page_widths` the file's page gives its fonts ([`Texts::with_page_widths`]). They are given + /// when it is first read, before any of its fonts is found: each is found once, with the widths + /// it has then. Every check and build of one open passes the same widths. + fn texts(&mut self, data: &[u8], page_widths: &vectorcraft_pdf::PageWidths) -> Option<&Texts> { self.forget_in_tests(); - self.texts.get_or_insert_with(|| Texts::read(data)).as_ref() + self.texts.get_or_insert_with(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))).as_ref() } /// [`Self::texts`] with its characters painted by `patterns` ([`Texts::with_patterns`]). - fn texts_with(&mut self, data: &[u8], patterns: std::collections::HashMap) -> Option<&Texts> { + fn texts_with( + &mut self, + data: &[u8], + patterns: std::collections::HashMap, + page_widths: &vectorcraft_pdf::PageWidths, + ) -> Option<&Texts> { self.forget_in_tests(); - let texts = self.texts.take().unwrap_or_else(|| Texts::read(data)).map(|t| t.with_patterns(patterns)); - self.texts.insert(texts).as_ref() + let read = self.texts.take().unwrap_or_else(|| Texts::read(data).map(|t| t.with_page_widths(page_widths))); + self.texts.insert(read.map(|t| t.with_patterns(patterns))).as_ref() } } @@ -217,7 +225,7 @@ fn type_all_made(structure: &Structure, data: &[u8], text: &mut ReadText) -> boo 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) = text.texts(data) else { return false }; + let Some(texts) = text.texts(data, &structure.page_widths) else { return false }; let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos .iter() @@ -336,6 +344,7 @@ pub(super) fn build_weighing( envelopes_drawn, styles_read, text_patterns, + page_widths, canvas_scale, symbols_own_size, xml_ids, @@ -496,7 +505,7 @@ pub(super) fn build_weighing( // The page's type that needs no text object of the layers: the layers' own legacy text, or // placed files that show it. let as_outlines = page_type_elsewhere(infos.is_empty(), infos.iter().all(|i| !i.shown), &mut shown, &mut hidden, &doc, &placed_elsewhere)?; - let texts = text.texts_with(data, text_patterns); + let texts = text.texts_with(data, text_patterns, &page_widths); // Each story is read once, however many text objects name it. let mut read: std::collections::BTreeMap>> = Default::default(); let stories: Vec>> = infos diff --git a/crates/eps/src/import/native/layers.rs b/crates/eps/src/import/native/layers.rs index d46da2b8ff..ef22d928b9 100644 --- a/crates/eps/src/import/native/layers.rs +++ b/crates/eps/src/import/native/layers.rs @@ -149,7 +149,7 @@ pub fn layered_ai_from( all.push(format!("{LAYERS_UNREAD} from its editing data ({why}): they come from its PDF part")); all }; - let AiLayers { data, structure, alone, mut text } = layers; + let AiLayers { data, structure, alone, mut text, page_widths } = layers; let data = match data { Ok(data) => data, Err(why) => return (visible, unread(warnings, &why), false), @@ -189,10 +189,17 @@ pub fn layered_ai_from( add_notes(&mut all, read.notes()); (visible, all, false) }; + // The layers read, with the widths the PDF part gives the characters of its fonts. + let read = || { + ai::read_over_page(&data, false, names).map(|mut structure| { + structure.page_widths = page_widths.clone(); + structure + }) + }; // The envelopes of type the page doesn't hold against layers that don't draw as it, and how many // envelopes of type the layers had. let (mut free, mut count) = (None, 0); - let built = structure.unwrap_or_else(|| ai::read_over_page(&data, false, names).map(Box::new)).and_then(|structure| { + let built = structure.unwrap_or_else(|| read().map(Box::new)).and_then(|structure| { count = structure.warped_type.envelope_count(); build_weighing(*structure, &data, Some(&visible), Page::Artboard, outlined, trust, unit, &mut free, &mut text) }); @@ -205,7 +212,7 @@ pub fn layered_ai_from( let live = free.is_none() && matches!(&built, Ok((done, _)) if holds_type_envelope(&done.layers)); if !live && let Some((mut done, notes)) = alone.and_then(|(pages, unit)| { - let mut structure = ai::read_over_page(&data, false, names).ok()?; + let mut structure = read().ok()?; // With none free, nothing needs settling again: every envelope keeps its drawn art. if let Some(free) = free.as_deref().filter(|free| !free.is_empty()) { structure.warped_type.open_alone(free, count); @@ -244,32 +251,41 @@ fn holds_type_envelope(nodes: &[Arc]) -> bool { /// 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. `names`: the encoding of names that aren't UTF-8. -pub fn ai_layers_alone(private: &[u8], pages: &[(f64, f64)], unit: f64, names: ai::NameEncoding) -> Result<(Document, Vec), AiLayers> { +/// is imported. `names`: the encoding of names that aren't UTF-8. `page_widths`: the widths the +/// PDF part gives the characters of its fonts, which tell installed copies of a font apart +/// ([`AiLayers::with_page_widths`]). +pub fn ai_layers_alone( + private: &[u8], + pages: &[(f64, f64)], + unit: f64, + names: ai::NameEncoding, + page_widths: vectorcraft_pdf::PageWidths, +) -> Result<(Document, Vec), AiLayers> { let data = match ai::decode_private(private) { Ok(data) => data, - Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Err(why), structure: None, alone: None, text: Box::default(), page_widths }), }; if !has_layers(&data) { - return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default() }); + return Err(AiLayers { data: Ok(data), structure: None, alone: None, text: Box::default(), page_widths }); } // An image past the hard limits is read as an unread box, which the PDF part's art replaces. - let structure = match ai::read_over_page(&data, false, names) { + let mut structure = match ai::read_over_page(&data, false, names) { Ok(structure) => structure, - Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default() }), + Err(why) => return Err(AiLayers { data: Ok(data), structure: Some(Err(why)), alone: None, text: Box::default(), page_widths }), }; + structure.page_widths = page_widths.clone(); let mut text = Box::::default(); // An envelope of type opens live only where the layers with it draw as the page, as the other // live envelopes do: the PDF part is imported to compare them with. Should none open live, the // layers open alone as they would have, the envelopes keeping their drawn art ([`layered_ai_from`]). if structure.warped_type.has_envelopes() && alone_scale(&structure, &data, pages, unit, &mut text).is_some() { let alone = Some((pages.to_vec(), unit)); - return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text }); + return Err(AiLayers { data: Ok(data), structure: Some(Ok(Box::new(structure))), alone, text, page_widths }); } match build_without_page(structure, &data, pages, unit, &mut text) { Ok(Ok((doc, notes))) => Ok((doc, notes)), - Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text }), - Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text }), + Ok(_) => Err(AiLayers { data: Ok(data), structure: None, alone: None, text, page_widths }), + Err(structure) => Err(AiLayers { data: Ok(data), structure: Some(Ok(structure)), alone: None, text, page_widths }), } } @@ -286,12 +302,27 @@ pub struct AiLayers { alone: Option<(Vec<(f64, f64)>, f64)>, /// The text objects' frames and the text document of the editing copy, as far as they were read. text: Box, + /// The widths the PDF part gives the characters of its fonts ([`Self::with_page_widths`]). + page_widths: vectorcraft_pdf::PageWidths, } 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, alone: None, text: Box::default() } + Self { data: ai::decode_private(private), structure: None, alone: None, text: Box::default(), page_widths: Default::default() } + } + + /// The editing copy with `page_widths`, the widths the file's PDF part gives the characters of + /// its fonts ([`vectorcraft_pdf::Opened::page_widths`]): type whose font record keeps no + /// version is set in the installed copy of its font that sets them at those widths, where + /// several copies answer to its name. The layers read before take them too, and a text document + /// read before is read again with them, since its fonts are found once, with the widths they had + /// then. + pub fn with_page_widths(mut self, page_widths: vectorcraft_pdf::PageWidths) -> Self { + if let Some(Ok(structure)) = &mut self.structure { + structure.page_widths = page_widths.clone(); + } + Self { page_widths, text: Box::default(), ..self } } } @@ -581,13 +612,17 @@ fn place_art(layer: &mut Node, pages: &[Rect], moves: &[Vec2]) { /// Editing data written on a large canvas comes in at its declared scale: no page holds the size. /// Names that aren't UTF-8 are read as Windows-1252 ([`ai_alone_with`]). pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec), String> { - ai_alone_with(private, ai::NameEncoding::default()) + ai_alone_with(private, ai::NameEncoding::default(), Default::default()) } -/// [`ai_alone`], with the names that aren't UTF-8 read in `names`. -pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding) -> Result<(Document, Vec), String> { +/// [`ai_alone`], with the names that aren't UTF-8 read in `names`, and `page_widths`, the widths the +/// file's PDF part gives the characters of its fonts when it has one that holds the art +/// ([`AiLayers::with_page_widths`]). +pub fn ai_alone_with(private: &[u8], names: ai::NameEncoding, page_widths: vectorcraft_pdf::PageWidths) -> Result<(Document, Vec), String> { let data = ai::decode_private(private)?; - build_from(ai::read_in(&data, true, names)?, &data, None, Page::Artboard, false, false, 1.0) + let mut structure = ai::read_in(&data, true, names)?; + structure.page_widths = page_widths; + build_from(structure, &data, None, Page::Artboard, false, false, 1.0) } /// [`ai_alone`] for a `.ai` whose PDF part can't be read, its first page `page` (width and height) diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index dbac845dad..8780c92c6a 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -3452,6 +3452,105 @@ fn type_from_the_text_document_takes_the_version_its_font_record_keeps() { assert_eq!(version("/0 (VertestInk-Regular) /VersionString (1.1)"), "1.1"); } +/// The widths a `.ai`'s PDF part gives the characters of `text` in its font `name` (a subset of +/// it, a TrueType font in `WinAnsiEncoding`): those `width` gives each, in thousandths of an em. +fn page_widths(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let widths: Vec = (32u8..=126).map(char::from).map(|c| if text.contains(c) { width(c).to_string() } else { "0".into() }).collect(); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+{name} /FirstChar 32 /Widths [{}] /Encoding /WinAnsiEncoding >> >>", + widths.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + vectorcraft_pdf::open_pdf(&vectorcraft_testkit::pdf::pdf_with(&[page], &[], None), None).unwrap().page_widths() +} + +/// [`page_widths`] of a composite font (`Identity-H`, a TrueType CIDFont) whose `ToUnicode` map gives +/// CID 1 the first character of `text`, CID 2 the next and so on, `W` their widths. +fn page_widths_cid(name: &str, text: &str, width: impl Fn(char) -> f64) -> vectorcraft_pdf::PageWidths { + let chars: Vec = text.chars().collect(); + let pairs: Vec = chars.iter().enumerate().map(|(i, c)| format!("<{:04X}> <{:04X}>", i + 1, u32::from(*c))).collect(); + let cmap = format!( + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n{} beginbfchar\n{}\nendbfchar\nendcmap\n", + pairs.len(), + pairs.join("\n") + ); + let w: Vec = chars.iter().map(|c| width(*c).to_string()).collect(); + let extra = vectorcraft_testkit::pdf::first_extra(1); + let font = format!( + "/Font << /F1 << /Type /Font /Subtype /Type0 /BaseFont /ABCDEF+{name}-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /ABCDEF+{name} /W [1 [{}]] >>] >> >>", + w.join(" ") + ); + let page = vectorcraft_testkit::pdf::PdfPage { resources: font, ..vectorcraft_testkit::pdf::PdfPage::new(100.0, 100.0, "") }; + let file = vectorcraft_testkit::pdf::pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len())], None); + vectorcraft_pdf::open_pdf(&file, None).unwrap().page_widths() +} + +/// The advance of `c` in installed `face`, in thousandths of an em. +fn advance(face: &vectorcraft_text::FontFace, c: char) -> f64 { + face.advance(face.glyph_for(c)) * 1000.0 / face.units_per_em() +} + +/// The version of the face that type from the text document of a `.ai` whose font record is +/// `record` (in place of `/0 (Helvetica)`) is set in, its layers read alone with `widths`, the +/// widths its PDF part gives the characters of its fonts. +fn version_on_page(record: &str, widths: vectorcraft_pdf::PageWidths) -> String { + let doc = text_document(&[("Hamburg\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]).replacen("/0 (Helvetica)", record, 1); + let file = private(&native_with_text(&layer("Art", true, &text_object(0)), &doc)); + let names = crate::NameEncoding::default(); + let Ok((d, notes)) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, widths) else { panic!("{record}: opened with the page") }; + let texts = text_of(&d.layers[0]); + assert_eq!(texts.len(), 1, "{record}: {notes:?}"); + vectorcraft_text::FontDb::global().style_face(&texts[0].runs[0].style).unwrap().version.clone() +} + +/// Two installed copies of one font can share its PostScript name, family and style, and differ +/// in their glyphs' widths alone. Type from the text document of a `.ai` whose font record keeps no +/// version is set in the copy that sets the characters its PDF part draws at the widths the PDF +/// part gives them, also when the record spells the name with other punctuation. Without those +/// widths, or when no copy sets the characters at them, it takes the copy it took before (the first +/// loaded); a version the record keeps decides first. The widths of a simple font in +/// `WinAnsiEncoding` and of a composite font with a `ToUnicode` map both tell the copies apart. +#[test] +fn type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths() { + install(&[(true, ("Widtest Ink", "Regular", "1.0", "WidtestInk-Regular")), (false, ("Widtest Ink", "Regular", "1.1", "WidtestInk-Regular"))]); + let copies = vectorcraft_text::FontDb::global().postscript_faces("WidtestInk-Regular"); + let copy = |version: &str| copies.iter().find(|f| f.version == version).unwrap().clone(); + let (old, new) = (copy("1.0"), copy("1.1")); + assert!((advance(&old, 'H') - advance(&new, 'H')).abs() > 10.0, "the copies set the type at other widths"); + let on = |name: &str, face: &vectorcraft_text::FontFace| page_widths(name, "Hamburg", |c| advance(face, c)); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", Default::default()), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &new)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("WidtestInk-Regular", &old)), "1.0"); + // Widths a file rounds are within 1/1000 em of the advances; farther off, they aren't the copy's. + let off = |by: f64| page_widths("WidtestInk-Regular", "Hamburg", |c| advance(&new, c) + by); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(-0.9)), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", off(2.0)), "1.0"); + // A record whose name differs from the copies' in punctuation alone, as its PDF part's font. + assert_eq!(version_on_page("/0 (Widtest-Ink-Regular)", on("Widtest-Ink-Regular", &new)), "1.1"); + // Widths of another font, or no copy setting the characters at the PDF part's widths. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", on("OtherInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths("WidtestInk-Regular", "Hamburg", |_| 1000.0)), "1.0"); + // A version the record keeps picks the copy, and one that isn't installed gives the copy it gave. + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (1.0)", on("WidtestInk-Regular", &new)), "1.0"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular) /5 (9.9)", on("WidtestInk-Regular", &new)), "1.0"); + // The widths of a composite font. + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&new, c))), "1.1"); + assert_eq!(version_on_page("/0 (WidtestInk-Regular)", page_widths_cid("WidtestInk-Regular", "Hamburg", |c| advance(&old, c))), "1.0"); + // A font installed once is set in that copy whatever the widths. + install(&[(true, ("Onewtest Ink", "Regular", "1.0", "OnewtestInk-Regular"))]); + assert_eq!(version_on_page("/0 (OnewtestInk-Regular)", on("OnewtestInk-Regular", &new)), "1.0"); + // Of several copies that set the characters at the widths, the first in the order the faces + // are found (the first loaded). + install(&[ + (true, ("Firstwtest Ink", "Regular", "1.0", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.1", "FirstwtestInk-Regular")), + (false, ("Firstwtest Ink", "Regular", "1.2", "FirstwtestInk-Regular")), + ]); + assert_eq!(version_on_page("/0 (FirstwtestInk-Regular)", on("FirstwtestInk-Regular", &new)), "1.1"); +} + /// A story with no runs, and a run or paragraph that names no style, is set in `[Normal Character /// Style]` and `[Normal Paragraph Style]` before the text document's base attributes. A Large /// Canvas copy (1:10) writes the styles at the art's scale (1.2 for 12 points, 0.6 for a 6-point @@ -6051,7 +6150,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; // A PDF part the layers don't draw as. let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); @@ -6060,7 +6159,7 @@ fn an_envelope_of_type_waits_on_the_page_of_layers_that_would_open_alone() { assert_eq!(loose, [("Note".to_string(), true), ("FLUX".to_string(), false)], "{notes:?}"); assert!(notes.iter().any(|n| n == crate::import::ai::ENVELOPE_TYPE_DRAWN), "{notes:?}"); // A PDF part that draws as those layers, with the drawn art: the envelope opens live. - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, d, vec![], false, false, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6088,7 +6187,7 @@ fn layers_that_open_alone_read_their_text_once() { let doc = unsplit_text_document(&[("Hi there\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Mid\r", 2, (8191.5, 8191.5), (0.0, 0.0), -10.0)]); let art = layer("Art", true, &format!("{}\n{}{}", square(10, 10), text_object(0), text_object(1))); let file = private(&native_with_text(&art, &doc)); - let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default()).ok(); + let open = || crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, crate::NameEncoding::default(), Default::default()).ok(); let (opened, texts, frames) = text_reads(false, open); let Some((d, notes)) = opened else { panic!("didn't open without the page") }; assert_eq!((texts, frames), (1, 1), "{notes:?}"); @@ -6107,7 +6206,7 @@ fn layers_whose_text_document_cannot_be_read_read_it_once_with_the_page() { let file = private(&native_with_text(&art, "not a text document")); let names = crate::NameEncoding::default(); let open = || { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, pdf_part(10.0, 86.0), vec![], false, false, 1.0, names) }; let (opened, texts, frames) = text_reads(false, open); @@ -6134,7 +6233,7 @@ fn an_envelope_of_type_waiting_on_the_page_reads_the_text_once() { let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // A PDF part the layers don't draw as: they open alone, after a build with the page and one without. @@ -6218,7 +6317,7 @@ fn trusted_layers_that_draw_apart_from_the_page_leave_an_envelope_of_type_its_dr let art = format!("u\n{}U\n{}", text_object(1), type_envelope(&arc_keys(0.3), &drawn)); let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; let (d, notes, read) = crate::layered_ai_from(layers, pdf_part(80.0, 80.0), vec![], false, true, 1.0, names); assert!(read, "{notes:?}"); let (envelopes, loose) = envelopes_and_type(&d); @@ -6312,7 +6411,7 @@ fn layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_di let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the envelope's drawn art: what the page draws. @@ -6355,7 +6454,7 @@ fn trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_ let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document, trust: bool| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, trust, 1.0, names) }; let (mut page, _, _) = open(pdf_part(80.0, 80.0), false); @@ -6394,7 +6493,7 @@ fn layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_do let file = private(&native_with_text(&layer("Art", true, &art), &doc)); let names = crate::NameEncoding::default(); let open = |page: Document| { - let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names) else { panic!("opened without the page") }; + let Err(layers) = crate::ai_layers_alone(&file, &[(100.0, 100.0)], 1.0, names, Default::default()) else { panic!("opened without the page") }; crate::layered_ai_from(layers, page, vec![], false, false, 1.0, names) }; // The layers alone, with the drawn art of both envelopes, but the first's: the page draws diff --git a/crates/eps/src/import/text.rs b/crates/eps/src/import/text.rs index 3de16d7bbf..c3bb2f4d7a 100644 --- a/crates/eps/src/import/text.rs +++ b/crates/eps/src/import/text.rs @@ -44,7 +44,7 @@ fn style_word(w: &str) -> String { /// A font's PostScript name without a subset prefix (`ABCDEF+`) or the `*1` of a re-encoded copy /// (`ABCDEF+RollerBabyBV*1` is `RollerBabyBV`). -fn bare_name(name: &str) -> &str { +pub(super) fn bare_name(name: &str) -> &str { let name = match name.split_once('+') { Some((prefix, rest)) if prefix.len() == 6 && prefix.bytes().all(|b| b.is_ascii_uppercase()) => rest, _ => name, @@ -56,14 +56,15 @@ fn bare_name(name: &str) -> &str { } /// The font of type that a text document's font record names: by `name`, its PostScript name, and -/// `version`, the version string (name ID 5) the record keeps, if any. An installed face of that -/// name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) and the -/// family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is +/// `version`, the version string (name ID 5) the record keeps, if any; `widths`, the widths the +/// file's page gives the font's characters, if it has them ([`postscript_face`]). An installed face +/// of that name gives its font ([`named_font`]). Without one, `name` is split ([`family_style`]) +/// and the family spelled as an available family is ([`FontDb::find_family`]: `MicrosoftYaHei` is /// Microsoft YaHei). → (family, style, version). /// /// [`FontDb::find_family`]: vectorcraft_text::FontDb::find_family -pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, String, Option) { - named_font(name, version).unwrap_or_else(|| { +pub(crate) fn document_font(name: &str, version: Option<&str>, widths: Option<&vectorcraft_pdf::FontWidths>) -> (String, String, Option) { + named_font(name, version, widths).unwrap_or_else(|| { let (family, style) = family_style(name); let family = vectorcraft_text::FontDb::global().find_family(&family).unwrap_or(family); (family, style, None) @@ -71,37 +72,69 @@ pub(crate) fn document_font(name: &str, version: Option<&str>) -> (String, Strin } /// The font of type set in the installed face of PostScript name `name` (a subset prefix and a -/// re-encoded copy's `*1` aside) in `version` ([`postscript_face`]): that face's own family and -/// style, and its version when the family and style alone resolve to another installed copy of -/// the font. A library can keep two copies under one family and style that differ in their -/// PostScript names or their versions, and draw the same text at different widths. → (family, -/// style, version); `None` when no installed face has the name. -pub(crate) fn named_font(name: &str, version: Option<&str>) -> Option<(String, String, Option)> { - let face = postscript_face(bare_name(name), version)?; +/// re-encoded copy's `*1` aside) in `version`, or that sets the characters at `widths` +/// ([`postscript_face`]): that face's own family and style, and its version when the family and +/// style alone resolve to another installed copy of the font. A library can keep two copies under +/// one family and style that differ in their PostScript names or their versions, and draw the same +/// text at different widths. → (family, style, version); `None` when no installed face has the name. +pub(crate) fn named_font( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option<(String, String, Option)> { + let face = postscript_face(bare_name(name), version, widths)?; // As the PDF import names a version: only one that the family and style don't resolve to. let default = vectorcraft_text::FontDb::global().face(&face.family, &face.style); let version = default.filter(|d| d.version != face.version).map(|_| face.version.clone()); Some((face.family.clone(), face.style.clone(), version)) } +/// How far an installed face's advance may be from the width a page gives a character, in +/// thousandths of an em, for the face to set it at that width: files write widths rounded. +const PAGE_WIDTH_SLACK: f64 = 1.0; + +/// The most characters of a page's font [`sets_page_widths`] compares. +const MAX_WIDTHS_COMPARED: usize = 512; + +/// Does installed `face` set the characters of `widths` (a page's, [`vectorcraft_pdf::FontWidths`]) +/// at their widths, each within [`PAGE_WIDTH_SLACK`]? The first [`MAX_WIDTHS_COMPARED`] characters +/// in code-point order are compared; a character the face has no glyph for isn't set at its width. +fn sets_page_widths(face: &vectorcraft_text::FontFace, widths: &vectorcraft_pdf::FontWidths) -> bool { + let k = 1000.0 / face.units_per_em(); + widths.iter().take(MAX_WIDTHS_COMPARED).all(|(c, w)| { + let gid = face.glyph_for(*c); + gid != 0 && (face.advance(gid) * k - f64::from(*w)).abs() <= PAGE_WIDTH_SLACK + }) +} + /// The installed face of PostScript name `name` (without a subset prefix), among the installed /// faces that answer to it ([`FontDb::postscript_faces`]): those of exactly that name when there /// are any (PostScript names are case-sensitive, so `SampleSans` isn't the face named /// `SAMPLESANS`, and `SampleSerif-Bold` isn't `SampleSerifBold`), and of those the one in -/// `version` when it is installed, else the first. `None` when no installed face has the name. +/// `version` when it is installed. Without a version, copies whose names, family and style are all +/// one can still set the type at other widths: of those, the first that sets the characters of +/// `widths` (the file's page's, when it has them) at their widths ([`sets_page_widths`], which +/// compares the first 512 characters). Else the first. `None` when no installed face has the name. /// /// [`FontDb::postscript_faces`]: vectorcraft_text::FontDb::postscript_faces -pub(crate) fn postscript_face(name: &str, version: Option<&str>) -> Option> { +pub(crate) fn postscript_face( + name: &str, + version: Option<&str>, + widths: Option<&vectorcraft_pdf::FontWidths>, +) -> Option> { let db = vectorcraft_text::FontDb::global(); let found = db.find_postscript(name)?; - if found.postscript_name() == name && version.is_none_or(|v| v == found.version) { + let widths = widths.filter(|_| version.is_none()); + let on_page = |f: &vectorcraft_text::FontFace| widths.is_none_or(|w| sets_page_widths(f, w)); + if found.postscript_name() == name && version.is_none_or(|v| v == found.version) && on_page(&found) { return Some(found); } let faces = db.postscript_faces(name); let named: Vec<_> = faces.iter().filter(|f| f.postscript_name() == name).cloned().collect(); let pool = if named.is_empty() { faces } else { named }; let in_version = version.and_then(|v| pool.iter().find(|f| f.version == v).cloned()); - Some(in_version.or_else(|| pool.into_iter().next()).unwrap_or(found)) + let by_widths = || pool.iter().find(|f| on_page(f)).cloned(); + Some(in_version.or_else(by_widths).or_else(|| pool.into_iter().next()).unwrap_or(found)) } /// A font's family and style from its PostScript name, without a subset prefix (`ABCDEF+`) or the @@ -620,7 +653,7 @@ impl Interp<'_> { } // The installed face of that PostScript name, as type from a text document takes it; else // the available family's own spelling: `MicrosoftYaHei` is Microsoft YaHei, not "Microsoft Ya Hei". - let (font_family, font_style, font_version) = document_font(&name, None); + let (font_family, font_style, font_version) = document_font(&name, None, None); let fill = if self.g.paint.is_none() { Paint::solid(vectorcraft_color::Color::BLACK) } else { self.g.paint.clone() }; let style = CharStyle { font_family, font_style, font_version, size, fill, stroke: Paint::None, ..CharStyle::default() }; let mut t = TextObject::point(Point::ZERO, text, style); diff --git a/crates/pdf/src/import.rs b/crates/pdf/src/import.rs index e5a5e2e382..46bf544e9f 100644 --- a/crates/pdf/src/import.rs +++ b/crates/pdf/src/import.rs @@ -38,6 +38,7 @@ mod entry; mod reshaped; mod state; +pub(crate) use cid::replacement; #[cfg(test)] pub(crate) use cid::{CidText, font_chars, identify_glyph, unify_radical}; #[cfg(any(test, feature = "read-count"))] diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index e6e34ae429..677a0d4c67 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -842,11 +842,7 @@ impl<'p> Builder<'p> { let data = o.font_data(); let name = self.fonts.get(&key).map(|f| f.name.clone()).or_else(|| data.as_ref().and_then(|d| d.postscript_name.clone())); let (weight, italic) = data.as_ref().map_or((None, false), |d| (d.weight, d.is_italic)); - // A subset's six-letter tag. - let ps = name.as_deref().map(|n| match n.split_once('+') { - Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest.to_string(), - _ => n.to_string(), - }); + let ps = name.as_deref().map(|n| crate::import_scan::without_subset_tag(n).to_string()); let installed = ps.as_deref().and_then(|ps| vectorcraft_text::FontDb::global().find_postscript(ps)); let n = match (installed, name) { (Some(face), _) => FontInfo { family: face.family.clone(), style: face.style.clone(), face: Some(face) }, diff --git a/crates/pdf/src/import/cid.rs b/crates/pdf/src/import/cid.rs index 60a28d15e1..b862ed336e 100644 --- a/crates/pdf/src/import/cid.rs +++ b/crates/pdf/src/import/cid.rs @@ -70,7 +70,7 @@ impl CidText { } /// A ToUnicode value that names no character: U+FFFD alone (#708). -pub(super) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool { +pub(crate) fn replacement(u: &craft_pdf::interpret::hayro_cmap::BfString) -> bool { use craft_pdf::interpret::hayro_cmap::BfString; match u { BfString::Char(c) => *c == char::REPLACEMENT_CHARACTER, diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..c2b81afc65 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -1041,19 +1041,26 @@ pub(crate) fn vertical_metrics(f: &Dict<'_>, embedded: bool) -> Option /// Each CID a `W` or `W2` array (`per` numbers a CID) gives values for, and its values: `c [v…]` /// gives CIDs from c on their values in turn, `c_first c_last v…` the same values to each of the -/// range. At most [`MAX_CIDS`] CIDs are read. -fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { +/// range. At most [`MAX_CIDS`] CIDs are read, and a list's values only as far as they take; `per` +/// is 1 or 3. +pub(crate) fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { let mut it = a.flex_iter(); let mut read = 0; loop { if let Some((first, list)) = it.next::<(u32, Array<'_>)>() { - let values: Vec = list.iter::().collect(); - for (cid, v) in (first..=u32::MAX).zip(values.chunks_exact(per)) { + // Read as they are given, no more than the CIDs read take. + let mut values = list.iter::(); + let mut v = [0.0; 3]; + for cid in first..=u32::MAX { + let Some(group) = v.get_mut(..per) else { return }; + if group.iter_mut().any(|slot| values.next().map(|x| *slot = x).is_none()) { + break; + } read += 1; if read > MAX_CIDS { return; } - each(cid, v); + each(cid, group); } } else if per == 1 && let Some((first, last, w)) = it.next::<(u32, u32, f64)>() @@ -1081,11 +1088,20 @@ fn cid_ranges(a: &Array<'_>, per: usize, mut each: impl FnMut(u32, &[f64])) { } } +/// A font's PostScript name without its subset's six-letter tag (`ABCDEF+Name` is `Name`, ISO +/// 32000-1 §9.6.4). +pub(crate) fn without_subset_tag(name: &str) -> &str { + match name.split_once('+') { + Some((tag, rest)) if tag.len() == 6 && tag.bytes().all(|b| b.is_ascii_uppercase()) => rest, + _ => name, + } +} + /// The PostScript name of font `f`: its `BaseFont`. A composite (Type 0) font's `BaseFont` is its /// CIDFont's name, a hyphen and its CMap's (`Name-Identity-H`, ISO 32000-1 §9.7.6.1), so its /// descendant CIDFont's `BaseFont` is taken, the font program's own name (§9.7.4.1); without one, /// the `BaseFont` without the CMap's name on its end. -fn font_name(f: &Dict<'_>) -> Option { +pub(crate) fn font_name(f: &Dict<'_>) -> Option { if f.get::>(b"Subtype").is_some_and(|s| s.as_ref() == b"Type3") { if let Some(base) = f.get::>(b"BaseFont") { return Some(String::from_utf8_lossy(base.as_ref()).into_owned()); diff --git a/crates/pdf/src/import_text.rs b/crates/pdf/src/import_text.rs index ec4fff092a..e301a91c3a 100644 --- a/crates/pdf/src/import_text.rs +++ b/crates/pdf/src/import_text.rs @@ -1148,11 +1148,7 @@ impl Families { /// The family and style of a font with base (PostScript) name `name`, or of weight `weight` /// and slant `italic` when the name has no style; whether the family is available. pub fn resolve(&self, name: &str, weight: Option, italic: bool) -> (String, String, bool) { - // A subset's six-letter tag. - let name = match name.split_once('+') { - Some((tag, rest)) if tag.len() == 6 && tag.chars().all(|c| c.is_ascii_uppercase()) => rest, - _ => name, - }; + let name = crate::import_scan::without_subset_tag(name); // An installed face of that exact PostScript name: its own family and style. if let Some((family, style)) = vectorcraft_text::FontDb::global().by_postscript_name(name) { return (family, style, true); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index a5f93a2a76..cd070d8c6f 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -61,6 +61,7 @@ mod lab_spot; mod linearize; mod marks; mod output; +mod page_widths; mod pages; mod patch; mod pdfx; @@ -83,6 +84,7 @@ pub use import::{ INVISIBLE_TEXT_NOTE, OFF_ARTBOARD_NOTE, OUTLINED_TEXT_NOTE, PAST_PAGE_NOTE, RESHAPED_TEXT_NOTE, UNMATCHED_GLYPHS_NOTE, UNNAMED_CHARACTERS_NOTE, holds_outlines, import, import_opened, import_with_report, is_glyph_outlines, is_outlines_note, }; +pub use page_widths::{FontWidths, PageWidths}; #[cfg(any(test, feature = "read-count"))] pub use pages::reads_of; pub use pages::{ diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs new file mode 100644 index 0000000000..aa1f122fcd --- /dev/null +++ b/crates/pdf/src/page_widths.rs @@ -0,0 +1,598 @@ +//! The widths a PDF's pages give the characters of the fonts they set type in, read from the font +//! dictionaries alone (no page is drawn): a simple font's `Widths` from its `FirstChar`, or a +//! composite font's descendant's `W`, each code's character from the font's `ToUnicode` map, or for +//! a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding (ISO 32000-1 +//! §9.6.2, §9.6.6, §9.7.4.3, §9.10.3, Annex D.2). + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::rc::Rc; +use std::sync::Arc; + +use craft_pdf::interpret::hayro_cmap::{BfString, CMap}; +use craft_pdf::syntax::object::{Array, Dict, Name, ObjRef, ObjectIdentifier, Stream}; +use craft_pdf::syntax::page::Resources; + +use crate::import::replacement; +use crate::import_scan::{cid_ranges, font_name, without_subset_tag}; + +/// The most fonts read. +const MAX_FONTS: usize = 256; +/// The most form XObjects looked into, and how deep they may nest. +const MAX_FORMS: usize = 4096; +const MAX_FORM_DEPTH: u32 = 16; +/// The most entries of font and XObject resource dictionaries looked at, all pages and forms of the +/// file together (one budget for the whole file, not one a page). +const MAX_KEYS: usize = 1 << 16; +/// The most bytes of width arrays (`Widths`, `W`) read, all fonts together; an array that fonts +/// share by reference is read once. A subset's array is a few kilobytes. +const MAX_WIDTH_TEXT: usize = 4 << 20; +/// The most characters of a font kept. +const MAX_CHARS: usize = 4096; +/// The largest `ToUnicode` map read, decoded: a subset's map names a few hundred codes. A longer one +/// is left unread. +const MAX_TO_UNICODE: usize = 256 << 10; +/// The most bytes of `ToUnicode` maps decoded, all fonts together. +const MAX_TO_UNICODE_TOTAL: usize = 4 << 20; +/// How far apart two widths a file gives one character of one font may be and still be one width, +/// in thousandths of an em: files write widths rounded. +const SAME_WIDTH: f32 = 1.0; + +/// The widths a page gives the characters of one font, in thousandths of an em, by character. +pub type FontWidths = BTreeMap; + +/// The advance widths, in thousandths of an em, that a PDF's pages give the characters of the fonts +/// they set type in, by each font's PostScript name (its `BaseFont` without a subset prefix): what +/// the copy of the font the file was set in draws them at. A `.ai`'s PDF part has them for the type +/// its text document holds, so they tell installed copies of one font apart. A font whose subsets +/// give one character two widths gives none. Cloning it, or a font's widths, shares them. +#[derive(Clone, Debug, Default)] +pub struct PageWidths { + fonts: Arc>>, +} + +impl PageWidths { + /// Each character the pages set in the font of PostScript name `name` (exactly, without a + /// subset prefix) and its width (at most 4096 characters): `None` when the pages set none in + /// that font, or its subsets give a character two widths. + pub fn widths(&self, name: &str) -> Option<&Arc> { + self.fonts.get(name) + } +} + +/// Which dictionary `d` is, to look at it once: where its text lies in the file as read. One +/// dictionary that pages or forms share is read from the same place each time (one in an object +/// stream lies in that stream's decoded data, which the reader keeps); telling it by its contents +/// would hash it again for each of them. +fn dict_key(d: &Dict<'_>) -> (usize, usize) { + let text = d.data(); + (text.as_ptr() as usize, text.len()) +} + +/// Each CID a composite font's `W` gives a width, and that width. +type CidWidths = Rc<[(u32, f32)]>; + +/// What [`page_widths`] has read so far. +#[derive(Default)] +struct Walk { + /// Each font's characters and widths; `None` when two subsets disagree. + fonts: HashMap>, + /// The font dictionaries, form XObjects and resource dictionaries already looked at. + seen_fonts: HashSet<(usize, usize)>, + seen_forms: HashSet, + walked: HashSet<(usize, usize)>, + /// The `ToUnicode` maps parsed, by their stream: `None` for one that can't be read. + maps: HashMap>>, + /// The width arrays that fonts name by reference, read: a simple font's `Widths` (its first 256 + /// numbers) and a composite font's `W` (each CID and its width). + simple_widths: HashMap>>, + cid_widths: HashMap>, + /// How many entries of resource dictionaries have been looked at. + looked: usize, + /// How many bytes of `ToUnicode` maps have been decoded. + decoded: usize, + /// How many width arrays have been read, and how many bytes of them. + arrays_read: usize, + width_text: usize, +} + +impl Walk { + /// Note `widths`, characters of the font of PostScript name `name` and their widths. A width + /// another subset gave the character already must be the same. + fn add(&mut self, name: String, widths: Vec<(char, f32)>) { + let slot = self.fonts.entry(name).or_insert_with(|| Some(BTreeMap::new())); + let Some(have) = slot else { return }; + for (c, w) in widths { + if have.get(&c).is_some_and(|was| (was - w).abs() > SAME_WIDTH) { + *slot = None; + return; + } + if have.len() < MAX_CHARS { + have.insert(c, w); + } + } + } + + /// Look at one more entry of a resource dictionary: `false` once [`MAX_KEYS`] have been. + fn look(&mut self) -> bool { + self.looked += 1; + self.looked <= MAX_KEYS + } + + /// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to + /// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach + /// [`MAX_TO_UNICODE_TOTAL`], or when it can't be read. A map is charged what was decoded of it, + /// at most the limit: a stream written plain comes back whole without being decoded. + fn character_map(&mut self, s: &Stream<'_>) -> Option> { + let id = s.obj_id(); + if !self.maps.contains_key(&id) { + let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1); + let data = s.decoded_within(left).ok(); + self.decoded += data.as_ref().map_or(left, |d| d.len().min(left)); + let map = data.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE).and_then(|d| CMap::parse(&d, |_| None)); + self.maps.insert(id, map.map(Rc::new)); + } + self.maps.get(&id)?.clone() + } + + /// Count `array`'s text against [`MAX_WIDTH_TEXT`]: `None` once the width arrays read reach it. + fn width_array<'a>(&mut self, array: Option>) -> Option> { + let array = array.filter(|_| self.width_text < MAX_WIDTH_TEXT)?; + self.arrays_read += 1; + self.width_text += array.data().len(); + Some(array) + } + + /// The first 256 numbers of simple font `f`'s `Widths`, read once for all the fonts that name + /// the same array. + fn simple_widths(&mut self, f: &Dict<'_>) -> Option> { + let read = |w: &mut Self| w.width_array(f.get::>(b"Widths")).map(|a| a.iter::().take(256).collect::>()); + let Some(r) = f.get_ref(b"Widths") else { return read(self) }; + if let Some(have) = self.simple_widths.get(&r) { + return have.clone(); + } + let got = read(self); + self.simple_widths.insert(r, got.clone()); + got + } + + /// Each CID that composite font descendant `d`'s `W` gives a width, and the width, read once for all + /// the fonts that name the same array. + fn cid_widths(&mut self, d: &Dict<'_>) -> Option { + let read = |w: &mut Self| { + let a = w.width_array(d.get::>(b"W"))?; + let mut out = Vec::new(); + cid_ranges(&a, 1, |cid, v| { + if let [w0] = v { + out.push((cid, *w0 as f32)); + } + }); + Some(out.into()) + }; + let Some(r) = d.get_ref(b"W") else { return read(self) }; + if let Some(have) = self.cid_widths.get(&r) { + return have.clone(); + } + let got = read(self); + self.cid_widths.insert(r, got.clone()); + got + } +} + +/// [`PageWidths`] of the fonts of `pages` (each page's resources) and of the forms they draw. +pub(crate) fn page_widths<'a>(pages: impl IntoIterator>) -> PageWidths { + let walk = walk(pages); + let fonts = walk.fonts.into_iter().filter_map(|(name, w)| Some((name, Arc::new(w.filter(|w| !w.is_empty())?)))).collect(); + PageWidths { fonts: Arc::new(fonts) } +} + +/// Read the fonts of `pages` and of the forms they draw. Each resource dictionary is walked once, +/// though pages and forms share it; a form without resources of its own takes those of what draws +/// it, which are walked already. At most [`MAX_KEYS`] entries are looked at. +fn walk<'a>(pages: impl IntoIterator>) -> Walk { + let mut w = Walk::default(); + let mut stack: Vec<(Resources<'a>, u32)> = pages.into_iter().map(|r| (r.clone(), 0)).collect(); + while let Some((res, depth)) = stack.pop() { + if w.walked.insert(dict_key(&res.fonts)) { + for key in res.fonts.keys() { + if w.seen_fonts.len() >= MAX_FONTS || !w.look() { + break; + } + let Some(f) = res.fonts.get::>(key.as_ref()) else { continue }; + if w.seen_fonts.insert(dict_key(&f)) + && let Some((name, widths)) = font_widths(&f, &mut w) + { + w.add(name, widths); + } + } + } + if depth >= MAX_FORM_DEPTH || !w.walked.insert(dict_key(&res.x_objects)) { + continue; + } + for key in res.x_objects.keys() { + if w.seen_forms.len() >= MAX_FORMS || !w.look() { + break; + } + let Some(s) = res.x_objects.get::>(key.as_ref()) else { continue }; + let d = s.dict(); + let form = d.get::>(b"Subtype").is_some_and(|t| t.as_ref() == b"Form"); + if let (true, Some(own)) = (form, d.get::>(b"Resources")) + && w.seen_forms.insert(s.obj_id()) + { + stack.push((Resources::from_scope(Some(own), res.clone()), depth + 1)); + } + } + } + w +} + +/// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each +/// character it names, at most [`MAX_CHARS`]. A code's character comes from the font's `ToUnicode` +/// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding; +/// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A +/// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its +/// widths are in its own glyph space) and a font whose codes' characters can't be told. +fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32)>)> { + let subtype = f.get::>(b"Subtype")?; + if subtype.as_ref() == b"Type3" { + return None; + } + let name = without_subset_tag(&font_name(f)?).to_string(); + let composite = subtype.as_ref() == b"Type0"; + let encoding = f.get::>(b"Encoding"); + let to_unicode = f.get::>(b"ToUnicode").and_then(|s| walk.character_map(&s)); + let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding"); + if to_unicode.is_none() && !win_ansi { + return None; + } + let char_of = |code: u32| match &to_unicode { + Some(map) => match map.lookup_bf_string(code).filter(|u| !replacement(u)) { + Some(BfString::Char(c)) => Some(c), + _ => None, + }, + None => win_ansi_char(code), + }; + let width = |w: f32| (w.is_finite() && w > 0.0 && w < 1e5).then_some(w); + let mut widths = Vec::new(); + if composite { + if !encoding.is_some_and(|e| matches!(e.as_ref(), b"Identity-H" | b"Identity-V")) { + return None; + } + let d = f.get::>(b"DescendantFonts").and_then(|a| a.iter::>().next())?; + for (cid, w) in walk.cid_widths(&d)?.iter() { + if widths.len() >= MAX_CHARS { + break; + } + if let (Some(c), Some(w)) = (char_of(*cid), width(*w)) { + widths.push((c, w)); + } + } + } else { + let first = f.get::(b"FirstChar")?; + // A simple font's codes are bytes. + for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) { + if let (Some(c), Some(w)) = (char_of(code), width(*w)) { + widths.push((c, w)); + } + } + } + Some((name, widths)) +} + +/// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252 +/// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which +/// it gives the space and the hyphen a second time. +fn win_ansi_char(code: u32) -> Option { + /// Codes 128 to 159; `\0` where the encoding has no character. + const HIGH: [char; 32] = [ + '\u{20AC}', '\0', '\u{201A}', '\u{192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}', '\u{2C6}', '\u{2030}', '\u{160}', '\u{2039}', + '\u{152}', '\0', '\u{17D}', '\0', '\0', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}', '\u{2DC}', + '\u{2122}', '\u{161}', '\u{203A}', '\u{153}', '\0', '\u{17E}', '\u{178}', + ]; + match code { + 0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF => char::from_u32(code), + 0x80..=0x9F => HIGH.get(usize::try_from(code - 0x80).ok()?).copied().filter(|c| *c != '\0'), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with}; + + /// A simple font named `name`, in `encoding`, whose widths from code `first` on are `widths`. + fn simple(subtype: &str, name: &str, encoding: &str, first: u32, widths: &str) -> String { + format!("<< /Type /Font /Subtype /{subtype} /BaseFont /{name} /Encoding /{encoding} /FirstChar {first} /Widths [{widths}] >>") + } + + /// The pages' fonts are read from their resources and from the forms they draw, a subset's + /// prefix aside: a simple font's characters from `WinAnsiEncoding` (a code 0 wide is left out) + /// or its `ToUnicode` map, a composite font's from its `ToUnicode` map, by CID. The subsets of one + /// font come together; a font whose subsets give a character two widths, a font in another + /// encoding without a `ToUnicode` map, and a Type 3 font give none. + #[test] + fn the_pages_give_each_font_the_widths_of_its_characters() { + let extra = first_extra(2); + let fonts = [ + simple("TrueType", "ABCDEF+Sample-Regular", "WinAnsiEncoding", 65, "600 0 520.5"), + simple("Type1", "GHIJKL+Sample-Regular", "WinAnsiEncoding", 128, "700"), + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /MNOPQR+Wide-Bold-Identity-H /Encoding /Identity-H /ToUnicode {extra} 0 R \ + /DescendantFonts [<< /Type /Font /Subtype /CIDFontType2 /BaseFont /MNOPQR+Wide-Bold /W [3 [250 610]] >>] >>" + ), + simple("Type1", "Roman-Mac", "MacRomanEncoding", 65, "500"), + format!( + "<< /Type /Font /Subtype /Type1 /BaseFont /Mapped /Encoding /MacRomanEncoding /FirstChar 3 /Widths [333] /ToUnicode {extra} 0 R >>" + ), + "<< /Type /Font /Subtype /Type3 /BaseFont /Drawn /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [1] /FontMatrix [1 0 0 1 0 0] >>" + .to_string(), + simple("TrueType", "STUVWX+Clash", "WinAnsiEncoding", 65, "640"), + ]; + let resources = |fonts: &[String], more: &str| { + let list: Vec = fonts.iter().enumerate().map(|(i, f)| format!("/F{i} {f}")).collect(); + format!("/Font << {} >> {more}", list.join(" ")) + }; + let first = PdfPage { resources: resources(&fonts, &format!("/XObject << /Fm0 {} 0 R >>", extra + 1)), ..PdfPage::new(100.0, 100.0, "") }; + let second = PdfPage { + resources: resources(&[simple("TrueType", "YZABCD+Clash", "WinAnsiEncoding", 65, "600")], ""), + ..PdfPage::new(100.0, 100.0, "") + }; + let cmap = + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n2 beginbfchar\n<0003> <0020>\n<0004> <03A9>\nendbfchar\nendcmap\n"; + let form_font = simple("TrueType", "EFGHIJ+Formed", "WinAnsiEncoding", 97, "480"); + let file = pdf_with( + &[first, second], + &[ + &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), + &format!( + "<< /Type /XObject /Subtype /Form /BBox [0 0 10 10] /Resources << /Font << /F0 {form_font} >> >> /Length 0 >>\nstream\n\nendstream" + ), + ], + None, + ); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + let got = |name: &str| widths.widths(name).map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()); + assert_eq!(got("Sample-Regular"), Some(vec![('A', 600.0), ('C', 520.5), ('€', 700.0)])); + assert_eq!(got("Wide-Bold"), Some(vec![(' ', 250.0), ('Ω', 610.0)])); + assert_eq!(got("Mapped"), Some(vec![(' ', 333.0)])); + assert_eq!(got("Formed"), Some(vec![('a', 480.0)])); + for none in ["ABCDEF+Sample-Regular", "Roman-Mac", "Drawn", "Clash", "Missing"] { + assert_eq!(got(none), None, "{none}"); + } + } + + /// [`super::walk`] of the pages of `file`. + fn walked(file: &[u8]) -> super::Walk { + let o = crate::open_pdf(file, None).unwrap(); + let pages = o.pdf.pages(); + super::walk(pages.iter().map(|p| p.resources())) + } + + /// Each resource dictionary is walked once: forms without resources of their own (which take + /// those of what draws them), forms that share one, and pages that share one look at each + /// entry once, so a file of thousands of them reads in time in proportion to it. + #[test] + fn shared_resources_are_walked_once() { + let n = 4000; + let extra = first_extra(1); + let font = simple("TrueType", "Shared", "WinAnsiEncoding", 65, "500"); + // Forms without resources, then forms that share one resource dictionary (the last object). + let shared = extra + 2 * n; + let forms: Vec = (0..2 * n) + .map(|i| { + let own = if i < n { String::new() } else { format!("/Resources {shared} 0 R ") }; + format!("<< /Type /XObject /Subtype /Form /BBox [0 0 1 {i}] {own}/Length 0 >>\nstream\n\nendstream") + }) + .chain(std::iter::once(format!("<< /Font << /F0 {} >> >>", simple("TrueType", "Formed", "WinAnsiEncoding", 66, "600")))) + .collect(); + let names: Vec = (0..2 * n).map(|i| format!("/X{i} {} 0 R", extra + i)).collect(); + let page = PdfPage { resources: format!("/Font << /F0 {font} >> /XObject << {} >>", names.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let refs: Vec<&str> = forms.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert!(w.fonts.contains_key("Shared") && w.fonts.contains_key("Formed")); + // The page's font and forms, and the shared dictionary's font. + assert!(w.looked <= 1 + 2 * n + 1, "{} entries looked at", w.looked); + // A thousand pages that share one font dictionary of 4000 entries. + let pages_n = 1000; + let extra = first_extra(pages_n); + let entries: Vec = (0..n).map(|i| format!("/F{i} {} 0 R", extra + 1 + i % 50)).collect(); + let objects: Vec = std::iter::once(format!("<< {} >>", entries.join(" "))) + .chain((0..50).map(|i| simple("TrueType", &format!("S{i}"), "WinAnsiEncoding", 65, "500"))) + .collect(); + let pages: Vec = + (0..pages_n).map(|_| PdfPage { resources: format!("/Font {extra} 0 R"), ..PdfPage::new(100.0, 100.0, "") }).collect(); + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&pages, &refs, None)); + assert_eq!(w.fonts.len(), 50); + assert!(w.looked <= n, "{} entries looked at", w.looked); + } + + /// Past [`super::MAX_FONTS`] fonts no more entries are looked at. + #[test] + fn fonts_past_the_most_read_are_not_looked_at() { + let fonts: Vec = + (0..super::MAX_FONTS + 100).map(|i| format!("/F{i} {}", simple("TrueType", &format!("N{i}"), "WinAnsiEncoding", 65, "500"))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let w = walked(&pdf_with(&[page], &[], None)); + assert_eq!(w.fonts.len(), super::MAX_FONTS); + assert!(w.looked <= super::MAX_FONTS + 1, "{} entries looked at", w.looked); + } + + /// Past [`super::MAX_KEYS`] entries of resource dictionaries, none are looked at: a font + /// dictionary of more entries than that, all naming one font, is looked at that far. + #[test] + fn entries_past_the_most_looked_at_are_left() { + let extra = first_extra(1); + let entries: Vec = (0..super::MAX_KEYS + 1000).map(|i| format!("/F{i} {extra} 0 R")).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", entries.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let w = walked(&pdf_with(&[page], &[&simple("TrueType", "Many", "WinAnsiEncoding", 65, "500")], None)); + assert_eq!(w.fonts.len(), 1); + assert!(w.looked <= super::MAX_KEYS + 1, "{} entries looked at", w.looked); + } + + /// A width array that fonts share by reference is read once for all of them: 128 composite + /// fonts naming one `W` and 128 simple fonts naming one `Widths`, each of 100,000 numbers. + #[test] + fn a_width_array_fonts_share_is_read_once() { + let numbers = 100_000; + let big: String = std::iter::repeat_n("500 ", numbers).collect(); + let extra = first_extra(1); + let cmap = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfrange\n<0000> <00FF> <0041>\nendbfrange\nendcmap\n"; + let fonts: Vec = (0..256) + .map(|i| { + if i % 2 == 0 { + format!( + "/F{i} << /Type /Font /Subtype /Type0 /BaseFont /W{i} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W {extra} 0 R >>] >>", + extra + 1 + ) + } else { + format!( + "/F{i} << /Type /Font /Subtype /TrueType /BaseFont /S{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>", + extra + 2 + ) + } + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let file = pdf_with( + &[page], + &[&format!("[0 [{big}]]"), &format!("<< /Length {} >>\nstream\n{cmap}endstream", cmap.len()), &format!("[{big}]")], + None, + ); + let w = walked(&file); + assert_eq!(w.arrays_read, 2); + assert!(w.width_text <= 2 * (big.len() + 10), "{} bytes of width arrays read", w.width_text); + assert_eq!(w.fonts.len(), 256); + assert!(w.fonts.values().all(|f| f.as_ref().is_some_and(|f| f.get(&'A') == Some(&500.0)))); + } + + /// Past [`super::MAX_WIDTH_TEXT`] bytes of width arrays no more are read: of six fonts each with + /// an array of a million bytes, the sixth gives no widths. + #[test] + fn width_arrays_past_the_most_read_are_left() { + let big: String = std::iter::repeat_n("500 ", 250_000).collect(); + let extra = first_extra(1); + let fonts: Vec = (0..6) + .map(|i| { + format!( + "/F{i} << /Type /Font /Subtype /TrueType /BaseFont /M{i} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths {} 0 R >>", + extra + i + ) + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let arrays: Vec = (0..6).map(|_| format!("[{big}]")).collect(); + let refs: Vec<&str> = arrays.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert_eq!(w.arrays_read, 5); + assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5); + } + + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an + /// incomplete last group left out) and a range's to each, and reads no more of a long list than + /// the CIDs it takes. + #[test] + fn cid_ranges_give_each_cid_its_values() { + let extra = first_extra(1); + let long: String = std::iter::repeat_n("7 ", 70_000).collect(); + let arrays = ["[1 [10 20 30] 100 102 7]".to_string(), "[1 [1 2 3 4 5 6 7]]".to_string(), format!("[0 [{long}]]")]; + let page = PdfPage { + resources: format!("/Properties << /A {extra} 0 R /B {} 0 R /C {} 0 R >>", extra + 1, extra + 2), + ..PdfPage::new(10.0, 10.0, "") + }; + let refs: Vec<&str> = arrays.iter().map(String::as_str).collect(); + let file = pdf_with(&[page], &refs, None); + let o = crate::open_pdf(&file, None).unwrap(); + let pages = o.pdf.pages(); + let props = &pages.iter().next().unwrap().resources().properties; + let ranges = |key: &str, per: usize| { + let mut out = vec![]; + crate::import_scan::cid_ranges(&props.get::>(key).unwrap(), per, |cid, v| { + out.push((cid, v.to_vec())) + }); + out + }; + let one = |v: &[(u32, f64)]| v.iter().map(|(c, w)| (*c, vec![*w])).collect::>(); + assert_eq!(ranges("A", 1), one(&[(1, 10.0), (2, 20.0), (3, 30.0), (100, 7.0), (101, 7.0), (102, 7.0)])); + assert_eq!(ranges("B", 3), [(1, vec![1.0, 2.0, 3.0]), (2, vec![4.0, 5.0, 6.0])]); + assert_eq!(ranges("C", 1).len(), 65_536); + } + + /// A `ToUnicode` map written plain and longer than the limits is charged no more than a + /// decoded one could be: the small maps of the other fonts are still read. + #[test] + fn a_long_plain_map_leaves_the_others_read() { + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE_TOTAL + 1000 { + big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let small = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0042>\nendbfchar\nendcmap\n"; + let extra = first_extra(1); + let cid = |name: &str, map: usize| { + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>", + extra + map + ) + }; + let n = 40; + let fonts: Vec = + std::iter::once(format!("/A {}", cid("Big", 0))).chain((0..n).map(|i| format!("/F{i} {}", cid(&format!("Small{i}"), 1 + i)))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let objects: Vec = std::iter::once(format!("<< /Length {} >>\nstream\n{big}endstream", big.len())) + .chain((0..n).map(|_| format!("<< /Length {} >>\nstream\n{small}endstream", small.len()))) + .collect(); + let refs: Vec<&str> = objects.iter().map(String::as_str).collect(); + let w = walked(&pdf_with(&[page], &refs, None)); + assert!(w.fonts.get("Big").is_some_and(Option::is_none) || !w.fonts.contains_key("Big")); + assert_eq!((0..n).filter(|i| w.fonts.get(&format!("Small{i}")).is_some_and(|f| f.as_ref().is_some_and(|m| !m.is_empty()))).count(), n); + assert!(w.decoded <= super::MAX_TO_UNICODE + 1 + n * small.len(), "{} bytes charged", w.decoded); + } + + /// A `ToUnicode` map is parsed once however many fonts name it, and one longer than + /// [`super::MAX_TO_UNICODE`] decoded is left unread, whether its stream is written plain or + /// compressed: its fonts give no widths. + #[test] + fn a_to_unicode_map_is_read_once_and_only_up_to_its_limit() { + use std::io::Write as _; + let small = + "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\nendcmap\n".to_string(); + let mut big = String::from("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE { + big.push_str("1 beginbfchar\n<0001> <0041>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + z.write_all(big.as_bytes()).unwrap(); + let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02X}")).collect(); + let extra = first_extra(1); + let cid = |name: &str, map: usize| { + format!( + "<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500]] >>] >>", + extra + map + ) + }; + let fonts: Vec = (0..64).map(|i| format!("/F{i} {}", cid(&format!("U{i}"), i % 3))).collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let file = pdf_with( + &[page], + &[ + &format!("<< /Length {} >>\nstream\n{small}endstream", small.len()), + &format!("<< /Length {} >>\nstream\n{big}endstream", big.len()), + &format!("<< /Length {} /Filter [/ASCIIHexDecode /FlateDecode] >>\nstream\n{hex}>\nendstream", hex.len() + 1), + ], + None, + ); + let w = walked(&file); + assert_eq!(w.maps.len(), 3, "each map parsed once"); + // Each long one charged up to just past the limit. + assert!(w.decoded <= small.len() + 2 * (super::MAX_TO_UNICODE + 1), "{} bytes charged", w.decoded); + assert_eq!(w.maps.values().filter(|m| m.is_some()).count(), 1, "the long ones left unread"); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert_eq!(widths.widths("U0").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()), Some(vec![('A', 500.0)])); + assert!(widths.widths("U1").is_none() && widths.widths("U2").is_none()); + // Every font of the name shares one map of its widths. + assert!(std::sync::Arc::ptr_eq(widths.widths("U0").unwrap(), widths.clone().widths("U0").unwrap())); + } +} diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 64e6217148..1c9a2c3908 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -276,6 +276,13 @@ impl Opened { crate::file_info::file_info_in(&self.pdf) } + /// The widths the pages give the characters of the fonts they set type in, from the fonts' + /// dictionaries ([`crate::PageWidths`]), without importing any page's art. + pub fn page_widths(&self) -> crate::PageWidths { + let pages = self.pdf.pages(); + crate::page_widths::page_widths(pages.iter().map(|p| p.resources())) + } + /// How many pages the PDF has, as [`info`] lists them. pub fn page_count(&self) -> usize { self.pdf.pages().len() diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 0cc9985a9c..3e87bbb974 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-15 · **Change:** minor (PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where several copies share its PostScript name, follows #6983; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -59,7 +59,7 @@ private editing data. VectorCraft: and the paragraph's hyphenation options and tab stops. Stroked type keeps its stroke's cap, join and miter limit. Type filled or stroked with a pattern keeps its pattern, placed in the document as a path's pattern fill would be: a character's paint names an art style of one paint, and the pattern is in that style (its colour in the text document is black). A pattern the file - doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one + doesn't define, or a style that isn't a pattern, keeps the colour as before. Type keeps its manual kerning (key 8 of a story's text, thousandths of an em after a character). Its font is an installed face of the PostScript name its font record gives: one of exactly that name, case and punctuation included (`SampleSans` isn't the face named `SAMPLESANS`, nor `SampleSerif-Bold` the one named `SampleSerifBold`), when one is installed, else one whose name differs only in them. The type takes that face's own family and style, not another family spelled alike (`SAMPLE INK` beside `Sample/Ink`, whose PostScript name is `SampleInk`). Among those faces the record's version (key 5, name ID 5) picks the one in that version when it is installed; a version that isn't installed gives the first, without a note. A record that keeps no version, in a `.ai` with a PDF part, takes among those faces the first that sets the characters the PDF part draws in that font (the first 512 in code-point order) each within 1/1000 em of the width the PDF part gives it (its `Widths` or `W`, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding`): two copies can share a name, family and style and set the type at other widths (two releases of one font). Without such widths, or with no face that sets them all, it takes the first, as before. The type names the face's version when its family and style alone resolve to another installed copy. Copies that share their family, style and version (an OpenType and a TrueType build of one release) can't be told apart: only the first of them loads. Type that a PostScript program sets, and legacy `.ai` type, take the face of their font's name the same way, with no version to read. Area type of one frame whose last lines the file sets but which don't fit here (the fallback font, or a descent past the frame's bottom) may get a frame taller from its bottom, by its lines' deepest descent plus 0.05 pt and only when that shows more of those lines, with a warning when it does. RGB in the PDF page's `ICCBased` spaces keeps the file's numbers in a `.ai` (the `uncalibrated_rgb` @@ -361,6 +361,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version (no key 5), where several installed faces answer to the record's PostScript name, is set in the one whose advances match the widths the file's PDF part gives the characters it draws in that font: the case #6983 left out, two copies of one PostScript name, family and style (two releases of one font) that differ only in their widths. The PDF part's fonts are read from their dictionaries alone, without importing its pages (`Opened::page_widths`, which looks into the forms they draw too): a simple font's `Widths` from its `FirstChar`, a composite font's descendant's `W` under an `Identity-H` or `Identity-V` CMap, each code's character from the font's `ToUnicode` map or, for a simple font without one, `WinAnsiEncoding` (ISO 32000-1 §9.6.2, §9.7.4.3, §9.10.3, Annex D.2), by `BaseFont` without its subset prefix. A code 0 wide is one the subset doesn't use and is left out; a font whose subsets give one character two widths gives none. Each resource dictionary is walked once, though pages and forms share it, and at most 65,536 of their entries (for the whole file, all pages together), 256 fonts and 4,096 forms are looked at; a width array that fonts share by reference is read once, and no more are read past 4 MB of them; a `ToUnicode` map is parsed once for all the fonts that name it, and one longer than 256 KB decoded, or past 4 MB of maps in all (each charged at most what could be decoded of it), is left unread. All the records of one font share its widths and the face they resolve to, so a text document of many records of one font holds one copy of them. Of the faces `postscript_face` finds for the name, the first that sets those characters (the first 512 of them in code-point order) each within 1/1000 em of its width takes the type, and the type names its version as before. With no widths for the font, one face, a version in the record (installed or not), or no face that sets them all, the face is the one taken before; each record is still resolved once. It applies whether the layers open alone, with the PDF part imported, or from the editing data alone beside a PDF part that is only type; a `.ai` saved without its PDF part, EPS and legacy `.ai` are unchanged. On 224 users' files (used locally, never committed), 332 font records have widths to compare: 299 already took a face that sets every character within 1/1000 em, 29 have none that does and keep their face, 1 keeps the version its record names, and 3 (one font installed in two releases, in 3 files) change copy, from up to 66/1000 em off the page to within 0.5/1000 em. Those 3 renders at 40 ppi, and no others, change, all closer to the file's own page (30.0% → 24.5%, 18.0% → 12.3% and 1.03% → 0.02% of the page differing; in the first two only that font's type changes, and the rest that differs is untouched); envelopes of type that open live go from 185 to 186, none fewer in any file; no file opens another way; in one file the note on type in an envelope gives way to the note of how far the layers differ from the page (0.2%), as its envelope now opens live. Tests: `page_widths::tests::the_pages_give_each_font_the_widths_of_its_characters`, `shared_resources_are_walked_once`, `fonts_past_the_most_read_are_not_looked_at`, `a_to_unicode_map_is_read_once_and_only_up_to_its_limit`, `a_long_plain_map_leaves_the_others_read`, `a_width_array_fonts_share_is_read_once`, `width_arrays_past_the_most_read_are_left`, `cid_ranges_give_each_cid_its_values` (`vectorcraft-pdf`), `tests_native::type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths`, `ate::tests::records_of_one_font_share_its_page_widths_and_answer` (`vectorcraft-eps`), `tests_aiimport::type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in`, `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save`, and the fuzz target `import_fuzz::pdf_font_widths_never_panic` (`vectorcraft-engine`). Scores unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) came in with butt caps, miter joins and a miter limit of 10 whatever the file stroked it with, while paths kept the graphics state's. The characters' stroke now takes the line cap (`J`), line join (`j`) and miter limit (`M`) of the graphics state, as a path's stroke does, and glyphs stroked with other ones start a run of their own, also a glyph filled and then stroked otherwise than the run its fill joined, so the glyphs before it keep their stroke (#7741). Test `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`. Scores and estimates unchanged. | | 2026-11-13 | minor | `.ai` and EPS import: layers that don't draw as the page, even with the drawn art of every live envelope put back, no longer put back the drawn art of every envelope of type. Each live envelope of type is weighed in the page check's own drawing of the pages it lies on, on the pixels that it and its drawn art ink there (the two drawn together on a layer of their own, without the rest of the layers; a pixel inks with an alpha above 8 of 255): it keeps its drawn art and its type, hidden, with the note, where the layers with it differ from the page in more of those pixels than its own check allows against its drawn art (10% of them, or 3% differing with all their neighbours, away from type), or where the envelopes of type that stay live, in the order they were read, would together differ there in more of a page than half of what the page check allows (a budget of the same size as the one their own checks share, kept apart from it). Art that differs elsewhere on the page no longer costs them their editable type; art that differs on their pixels still does. An envelope of type that a clip group or a clipping sublayer clips, an opacity mask masks, or a group with an appearance of its own, another envelope, a repeat or a blend holds keeps its drawn art as before, wherever it lies: drawn on its own it would be weighed elsewhere than it draws, and what holds it can draw it onto the page from off it. An envelope on no page stays live, as the page check doesn't see it, unless the page holds all the art that prints (an EPS's page that is its art's box, where art past the page is compared too): there one reaching past the page keeps its drawn art. Past 12 of them on the pages, all keep it. This holds where the editing data is trusted, where the objects that differ come in as the page's art (the placed files' other placement weighed on its own, as it draws them elsewhere under or over the envelopes; layers that draw as the page with only the envelopes the page holds put back are used as they are; where none of the objects that differ can then come in as the page's art, because an object holds type, the drawn art of every envelope of type is put back and that is tried again, as before), and for a `.ai` whose layers would open alone, which still opens alone: its envelopes of type are all settled again as they were with the page, in the same order and with the same checks, so each that opens live draws as it was weighed, and those the page held get their drawn art back. Where putting the drawn art of every live envelope back makes the layers draw as the page, it is still put back (#5065). In 224 users' files (used locally, never committed): envelopes of type that open live go from 174 to 186, in 8 files, none fewer in any file; no file changes between its layers and its PDF part; 7 renders change, by at most 0.7% of their pixels at 40 ppi (1 closer to the page, 1 alike, 5 further, by at most 0.7 of a percentage point, where VectorCraft's own envelope draws a little apart from the drawn art, within its check); the note for type in an envelope goes from 6 files. Of the 14 envelopes of type that had opened live and lost it to the page check, 2 keep their drawn art: one where the page draws something else where it is, and one in a file that comes in as its PDF part (#7141). Tests `build::candidate_tests::the_page_holds_back_only_envelopes_of_type_where_it_differs_from_them`, `envelopes_of_type_stay_live_within_half_of_what_the_page_check_allows`, `an_envelope_of_type_differing_in_more_of_its_pixels_than_its_check_allows_is_held_back`, `envelopes_of_type_the_layers_dont_draw_in_place_are_held_back`, `on_a_page_that_holds_all_the_art_an_envelope_of_type_past_it_is_held_back`, `objects_come_in_as_the_page_art_with_every_envelope_of_type_put_back_where_a_live_one_holds_a_difference`, `tests_native::layers_that_would_open_alone_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `layers_that_would_open_alone_keep_live_only_the_envelopes_of_type_the_page_doesnt_hold`, `trusted_layers_that_would_open_alone_open_alone_with_an_envelope_of_type_the_page_doesnt_hold_live`, `layers_with_objects_that_come_in_as_the_page_art_keep_an_envelope_of_type_that_draws_as_the_page_live`, `trusted_layers_keep_an_envelope_of_type_live_where_other_art_differs_from_the_page`, `trusted_layers_leave_an_envelope_of_type_the_page_draws_otherwise_its_drawn_art`, `build::candidate_tests::the_other_placement_of_placed_files_is_weighed_on_its_own`, `layers_that_draw_as_the_page_with_the_held_envelopes_of_type_put_back_are_used_so` | | 2026-11-13 | minor | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.rs`). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f393c7b8d8..5eeaededb5 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-16 · **Change:** minor (Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,6 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | From 5fb65f8448c5dc5443bc9d104c2c1a161cd633ed Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 16:53:26 +0000 Subject: [PATCH 003/104] pdf: page widths: a character's widths must all agree, not each the one before `Walk::add` compared each width a subset gave a character with the last one kept, and kept the new one. Widths that drift a little at a time (600, 600.8, 601.6) passed though the first and last are further apart than `SAME_WIDTH`, and the same subsets read in another order gave none. It now keeps the narrowest and widest width of each character and gives the font none once they are more than `SAME_WIDTH` apart; the width kept is the first one read. Test `widths_that_drift_apart_over_several_subsets_give_none`. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/page_widths.rs | 49 +++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs index aa1f122fcd..2632aa5449 100644 --- a/crates/pdf/src/page_widths.rs +++ b/crates/pdf/src/page_widths.rs @@ -76,6 +76,8 @@ type CidWidths = Rc<[(u32, f32)]>; struct Walk { /// Each font's characters and widths; `None` when two subsets disagree. fonts: HashMap>, + /// The narrowest and widest width given each character of each font so far. + bounds: HashMap>, /// The font dictionaries, form XObjects and resource dictionaries already looked at. seen_fonts: HashSet<(usize, usize)>, seen_forms: HashSet, @@ -96,18 +98,23 @@ struct Walk { } impl Walk { - /// Note `widths`, characters of the font of PostScript name `name` and their widths. A width - /// another subset gave the character already must be the same. + /// Note `widths`, characters of the font of PostScript name `name` and their widths. All the + /// widths given one character, by this and the other subsets, must be the same: no two more + /// than [`SAME_WIDTH`] apart. fn add(&mut self, name: String, widths: Vec<(char, f32)>) { - let slot = self.fonts.entry(name).or_insert_with(|| Some(BTreeMap::new())); + let slot = self.fonts.entry(name.clone()).or_insert_with(|| Some(BTreeMap::new())); let Some(have) = slot else { return }; + let bounds = self.bounds.entry(name).or_default(); for (c, w) in widths { - if have.get(&c).is_some_and(|was| (was - w).abs() > SAME_WIDTH) { - *slot = None; - return; - } - if have.len() < MAX_CHARS { + if let Some((lo, hi)) = bounds.get_mut(&c) { + (*lo, *hi) = (lo.min(w), hi.max(w)); + if *hi - *lo > SAME_WIDTH { + *slot = None; + return; + } + } else if have.len() < MAX_CHARS { have.insert(c, w); + bounds.insert(c, (w, w)); } } } @@ -488,6 +495,32 @@ mod tests { assert_eq!(w.fonts.values().filter(|f| f.as_ref().is_some_and(|f| !f.is_empty())).count(), 5); } + /// Widths that drift past [`super::SAME_WIDTH`] over several subsets are two widths, though + /// each lies within it of the one read before: subsets giving `A` 600, 600.8 and 601.6 give the + /// font none, as do subsets giving `B` 501.5, 500.6 and 500. Two within it still give one. Each + /// subset is on a page of its own, so they are read in turn (a font dictionary's entries come in + /// no set order). + #[test] + fn widths_that_drift_apart_over_several_subsets_give_none() { + let tags = ["AAAAAA", "BBBBBB", "CCCCCC"]; + let pages: Vec = (0..3) + .map(|i| { + let mut fonts = vec![ + format!("/D {}", simple("TrueType", &format!("{}+Drift", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8", "601.6"][i])), + format!("/B {}", simple("TrueType", &format!("{}+Back", tags[i]), "WinAnsiEncoding", 65, ["0 501.5", "0 500.6", "0 500"][i])), + ]; + if i < 2 { + fonts.push(format!("/S {}", simple("TrueType", &format!("{}+Steady", tags[i]), "WinAnsiEncoding", 65, ["600", "600.8"][i]))); + } + PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") } + }) + .collect(); + let widths = crate::open_pdf(&pdf_with(&pages, &[], None), None).unwrap().page_widths(); + assert!(widths.widths("Drift").is_none()); + assert!(widths.widths("Back").is_none()); + assert!(widths.widths("Steady").is_some_and(|w| w.contains_key(&'A'))); + } + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an /// incomplete last group left out) and a range's to each, and reads no more of a long list than /// the CIDs it takes. From 51ce7e9b9df5483b79102a619f2cc046b5ca41f7 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 16:53:26 +0000 Subject: [PATCH 004/104] pdf: page widths: a ToUnicode map that can't be read gives no widths A simple font in `WinAnsiEncoding` whose `ToUnicode` map was left unread (past the size limits, or not a map at all) took its characters from the encoding, as a font without a map does, so a code the map gives another character lent its width to the encoding's. Only a font with no `ToUnicode` entry now falls back to its encoding; one whose map can't be read gives no widths. Test `a_to_unicode_map_that_cant_be_read_gives_no_widths`. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/page_widths.rs | 38 ++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs index 2632aa5449..8f63f91f95 100644 --- a/crates/pdf/src/page_widths.rs +++ b/crates/pdf/src/page_widths.rs @@ -246,7 +246,13 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) let name = without_subset_tag(&font_name(f)?).to_string(); let composite = subtype.as_ref() == b"Type0"; let encoding = f.get::>(b"Encoding"); - let to_unicode = f.get::>(b"ToUnicode").and_then(|s| walk.character_map(&s)); + // Only a font without a `ToUnicode` map falls back to its encoding: one whose map can't be + // read gives none. + let to_unicode = match f.get::>(b"ToUnicode") { + Some(s) => Some(walk.character_map(&s)?), + None if f.contains_key(b"ToUnicode") => return None, + None => None, + }; let win_ansi = !composite && encoding.as_ref().is_some_and(|e| e.as_ref() == b"WinAnsiEncoding"); if to_unicode.is_none() && !win_ansi { return None; @@ -521,6 +527,36 @@ mod tests { assert!(widths.widths("Steady").is_some_and(|w| w.contains_key(&'A'))); } + /// Only a simple font without a `ToUnicode` map takes its characters from `WinAnsiEncoding`: + /// one whose map is left unread (longer than [`super::MAX_TO_UNICODE`]) or isn't a stream gives + /// no widths. + #[test] + fn a_to_unicode_map_that_cant_be_read_gives_no_widths() { + let mut big = String::from("begincmap\n1 begincodespacerange\n<00> \nendcodespacerange\n"); + while big.len() <= super::MAX_TO_UNICODE { + big.push_str("1 beginbfchar\n<41> <0042>\nendbfchar\n"); + } + big.push_str("endcmap\n"); + let extra = first_extra(1); + let font = |name: &str, to_unicode: &str| { + format!("<< /Type /Font /Subtype /TrueType /BaseFont /{name} /Encoding /WinAnsiEncoding /FirstChar 65 /Widths [600]{to_unicode} >>") + }; + let page = PdfPage { + resources: format!( + "/Font << /F0 {} /F1 {} /F2 {} >>", + font("Unread", &format!(" /ToUnicode {extra} 0 R")), + font("Named", " /ToUnicode /Identity-H"), + font("Plain", "") + ), + ..PdfPage::new(100.0, 100.0, "") + }; + let file = pdf_with(&[page], &[&format!("<< /Length {} >>\nstream\n{big}endstream", big.len())], None); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert!(widths.widths("Unread").is_none()); + assert!(widths.widths("Named").is_none()); + assert_eq!(widths.widths("Plain").map(|w| w.get(&'A').copied()), Some(Some(600.0))); + } + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an /// incomplete last group left out) and a range's to each, and reads no more of a long list than /// the CIDs it takes. From 5f9017da2e79f15d81673c03261e9cf594c3104f Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 23:02:24 +0000 Subject: [PATCH 005/104] docs: note the installed copy that sets the PDF part's widths (#8087) in the File formats rows and evidence The area rows and the evidence list name the change and its tests, as AGENTS.md asks of a change that lands. Scores and estimates unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/target-app-parity.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5eeaededb5..445f967b5f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -270,9 +270,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) | | Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged | @@ -535,7 +535,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 | | View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 | | Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units | -| File formats | 6 | 85% | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | +| File formats | 6 | 85% | `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (#8087, follows #6983; scores and estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; scores and estimates unchanged); PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) | | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 | | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 | | Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 | @@ -585,6 +585,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- **`.ai` type in the copy its PDF part sets (#8087, follows #6983):** `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs` covers two installed copies of one font that differ only in their widths: type whose font record keeps no version is set in the copy that sets the characters at the widths the PDF part gives them. `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs` checks that records of one font share those widths and the answer. The tests in `crates/pdf/src/page_widths.rs` cover reading the widths from the font dictionaries alone (simple and composite fonts, `ToUnicode` maps, `WinAnsiEncoding`, forms) within the file's bounds; a font whose subsets give a character widths more than 1/1000 em apart, or whose `ToUnicode` map can't be read, gives none. `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs` cover opening and a save and reopen; `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs` feeds hostile font dictionaries. Synthetic files written in the tests, with the copies of a font the test installs itself; no fixtures added. Scores and hours unchanged. + - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. From 931b0cd469e7208ce87104aa9d803c503c642851 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 23:10:34 +0000 Subject: [PATCH 006/104] docs: the first File formats row names the saved editing copy's limits (#868) It still said Illustrator's editing data isn't written, while the other two File formats rows give what a saved `.ai`'s editing copy leaves out. It now has their words. Scores and estimates unchanged. Co-Authored-By: Claude Opus 5.5 --- 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 445f967b5f..b220c8b45a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -270,7 +270,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them | | Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) | -| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | +| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects other than grouped column, stacked column, line and area graphs the `.ai` reader reads back whole as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. Graphs saved to `.ai` in either form open again as live graphs (`ai_editing::tests::graphs_are_written_with_their_records_and_open_live`, `legacy_ai::tests::graphs_are_written_with_their_records_and_open_live`, `cmd::graph::tests::a_drawn_graph_saved_as_ai_opens_as_a_graph_unless_the_save_warns`); other graphs are still written as their art (`graphs_the_records_cant_keep_are_written_as_their_art`); score and hours unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. PDF import: stroked type (text rendering modes 1, 2, 5 and 6) keeps the file's line cap, line join and miter limit, as paths do (#7741, `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`); score, gaps and hours unchanged. `.ai` import: type from the text document whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, where copies of one PostScript name, family and style differ only in their widths (#8087, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`); score, gaps and hours unchanged. | | View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) | From 40d1bef059fe2ae4389a8083da6e03e528c2cea3 Mon Sep 17 00:00:00 2001 From: jmverges Date: Mon, 16 Nov 2026 23:45:35 +0000 Subject: [PATCH 007/104] docs: roadmap M4 Files row notes #8087 The status line, the M4 Files row and the revision history name the change, as AGENTS.md asks of a change that lands. Estimates unchanged. Co-Authored-By: Claude Opus 5.5 --- docs/roadmap.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index bfaa10db30..d71364fe34 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-16 · **Change:** minor (M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, #8087; scores and estimates unchanged; previously: M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -160,7 +160,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; 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); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 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 copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); 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; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ 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; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` import: type takes the installed copy of its font that sets its PDF part's widths (#8087; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ 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; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | | 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) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 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; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), 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; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | @@ -212,6 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | From 400b4c96f9942a57616eb5be474b87591e3a9dcd Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 17 Nov 2026 06:09:11 +0000 Subject: [PATCH 008/104] pdf: page widths: bound the work of looking up a font's characters In the pinned CMap, each lookup of a code in a `bfrange` copies the range's whole destination and decodes it, so a `ToUnicode` map under the 256 KB limit with one long destination, shared by many fonts whose `W` names every CID, cost millions of long copies. `MAX_CHARS` didn't stop it, since such lookups give no character. - A `ToUnicode` map holding a string longer than 128 bytes decoded (`MAX_DESTINATION`: hex, literal, or any ASCII85 string, whose `z` stands for four bytes), or written as a binary CMap, is left unread, as one past the size limits is: its fonts give no widths. The scan steps over dictionaries (`<<`) and comments as the CMap reader does. - A composite font looks up at most `MAX_LOOKUPS` (16,384) of its codes with a width, in `W` order, and keeps what it found among them. Tests `a_to_unicode_map_with_a_long_destination_is_left_unread` and `codes_past_the_most_looked_up_are_left`, each failing without its part. Co-Authored-By: Claude Opus 5.5 --- crates/pdf/src/page_widths.rs | 159 ++++++++++++++++++++++++++++++++-- 1 file changed, 153 insertions(+), 6 deletions(-) diff --git a/crates/pdf/src/page_widths.rs b/crates/pdf/src/page_widths.rs index 8f63f91f95..eb2ab53ff5 100644 --- a/crates/pdf/src/page_widths.rs +++ b/crates/pdf/src/page_widths.rs @@ -33,6 +33,13 @@ const MAX_CHARS: usize = 4096; const MAX_TO_UNICODE: usize = 256 << 10; /// The most bytes of `ToUnicode` maps decoded, all fonts together. const MAX_TO_UNICODE_TOTAL: usize = 4 << 20; +/// The longest string a `ToUnicode` map read may hold, decoded, in bytes: a destination is a +/// character or a short run of them (a ligature's), and each lookup of a code in a range copies its +/// range's whole destination. A map with a longer one is left unread. +const MAX_DESTINATION: usize = 128; +/// The most codes of a composite font whose characters are looked up (its first, in `W` order): +/// [`MAX_CHARS`] bounds the characters kept, not the codes looked at to find them. +const MAX_LOOKUPS: usize = 4 * MAX_CHARS; /// How far apart two widths a file gives one character of one font may be and still be one width, /// in thousandths of an em: files write widths rounded. const SAME_WIDTH: f32 = 1.0; @@ -127,7 +134,8 @@ impl Walk { /// The `ToUnicode` map `s`, parsed once however many fonts name it: `None` when it decodes to /// more than [`MAX_TO_UNICODE`] bytes, when the maps decoded so far reach - /// [`MAX_TO_UNICODE_TOTAL`], or when it can't be read. A map is charged what was decoded of it, + /// [`MAX_TO_UNICODE_TOTAL`], when it holds a string longer than [`MAX_DESTINATION`], or when it + /// can't be read. A map is charged what was decoded of it, /// at most the limit: a stream written plain comes back whole without being decoded. fn character_map(&mut self, s: &Stream<'_>) -> Option> { let id = s.obj_id(); @@ -135,7 +143,9 @@ impl Walk { let left = MAX_TO_UNICODE_TOTAL.saturating_sub(self.decoded).min(MAX_TO_UNICODE + 1); let data = s.decoded_within(left).ok(); self.decoded += data.as_ref().map_or(left, |d| d.len().min(left)); - let map = data.filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE).and_then(|d| CMap::parse(&d, |_| None)); + let map = data + .filter(|d| d.len() < left && d.len() <= MAX_TO_UNICODE && !d.starts_with(b"bcmap") && longest_string(d) <= MAX_DESTINATION) + .and_then(|d| CMap::parse(&d, |_| None)); self.maps.insert(id, map.map(Rc::new)); } self.maps.get(&id)?.clone() @@ -233,7 +243,8 @@ fn walk<'a>(pages: impl IntoIterator>) -> Walk { } /// The PostScript name of font `f` (its `BaseFont` without a subset prefix) and the width of each -/// character it names, at most [`MAX_CHARS`]. A code's character comes from the font's `ToUnicode` +/// character it names, at most [`MAX_CHARS`] (of a composite font, among its first [`MAX_LOOKUPS`] +/// codes with a width). A code's character comes from the font's `ToUnicode` /// map or, for a simple font without one whose `Encoding` is `WinAnsiEncoding`, from that encoding; /// a composite font's codes are its CIDs, so only under an `Identity-H` or `Identity-V` CMap. A /// width of 0 is a code the subset doesn't use, and is left out. `None` for a Type 3 font (its @@ -271,11 +282,14 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) return None; } let d = f.get::>(b"DescendantFonts").and_then(|a| a.iter::>().next())?; + let mut looked = 0; for (cid, w) in walk.cid_widths(&d)?.iter() { - if widths.len() >= MAX_CHARS { + if widths.len() >= MAX_CHARS || looked >= MAX_LOOKUPS { break; } - if let (Some(c), Some(w)) = (char_of(*cid), width(*w)) { + let Some(w) = width(*w) else { continue }; + looked += 1; + if let Some(c) = char_of(*cid) { widths.push((c, w)); } } @@ -283,7 +297,8 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) let first = f.get::(b"FirstChar")?; // A simple font's codes are bytes. for (code, w) in (first..256).zip(walk.simple_widths(f)?.iter()) { - if let (Some(c), Some(w)) = (char_of(code), width(*w)) { + let Some(w) = width(*w) else { continue }; + if let Some(c) = char_of(code) { widths.push((c, w)); } } @@ -291,6 +306,63 @@ fn font_widths(f: &Dict<'_>, walk: &mut Walk) -> Option<(String, Vec<(char, f32) Some((name, widths)) } +/// The decoded length, in bytes, of the longest string in CMap text `data`: a hex string's digits +/// halved, or a literal string's bytes (escapes counted as written, so at least its length). A `<<` +/// opens a dictionary, not a string, and a `%` outside a string starts a comment. An ASCII85 +/// string (`<~`), which no `ToUnicode` map writes and whose `z` stands for four bytes, counts as +/// longer than any. +fn longest_string(data: &[u8]) -> usize { + let mut longest = 0; + let mut i = 0; + while let Some(&b) = data.get(i) { + i += 1; + let len = match b { + b'%' => { + while data.get(i).is_some_and(|b| !matches!(b, b'\n' | b'\r')) { + i += 1; + } + continue; + } + b'<' if data.get(i) == Some(&b'~') => return usize::MAX, + b'<' if data.get(i) == Some(&b'<') => { + i += 1; + continue; + } + b'<' => { + let mut digits = 0; + while let Some(&b) = data.get(i) { + i += 1; + if b == b'>' { + break; + } + digits += usize::from(b.is_ascii_hexdigit()); + } + digits.div_ceil(2) + } + b'(' => { + let (mut depth, mut len) = (1usize, 0); + while let Some(&b) = data.get(i) { + i += 1; + match b { + b'\\' => i += 1, + b'(' => depth += 1, + b')' => depth -= 1, + _ => {} + } + if depth == 0 { + break; + } + len += 1; + } + len + } + _ => continue, + }; + longest = longest.max(len); + } + longest +} + /// The character of code `code` in `WinAnsiEncoding` (ISO 32000-1 Annex D.2), which is Windows-1252 /// but for the codes it leaves unused: `None` for those, for the controls, and for 160 and 173, which /// it gives the space and the hyphen a second time. @@ -557,6 +629,81 @@ mod tests { assert_eq!(widths.widths("Plain").map(|w| w.get(&'A').copied()), Some(Some(600.0))); } + /// A `ToUnicode` map with a destination longer than [`super::MAX_DESTINATION`] is left unread, + /// though the whole map is under [`super::MAX_TO_UNICODE`]: each lookup of a code in its range + /// would copy the whole destination. A hex destination of 60,000 characters, a literal one of + /// 600, and ASCII85 ones (`z` stands for four bytes, and one can hide the rest of its line + /// behind a `%` the pre-scan would take for a comment) are all left unread. A map with a long + /// name in a dictionary (`<<`) and a comment with an unclosed `(`, more than the limit before + /// the map's end, is still read. + #[test] + fn a_to_unicode_map_with_a_long_destination_is_left_unread() { + let head = "begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<0001> <0041>\nendbfchar\n"; + let range = |dst: &str| format!("{head}1 beginbfrange\n<0100> <01FF> {dst}\nendbfrange\nendcmap\n"); + let hex = range(&format!("<{}>", "0042".repeat(60_000))); + let literal = range(&format!("({})", "B".repeat(600))); + let zeros = range(&format!("<~{}~>", "z".repeat(1_000))); + let hidden = format!("{head}<~>%~> 1 beginbfrange <0100> <01FF> <{}> endbfrange\nendcmap\n", "0042".repeat(300)); + let padding = "1 beginbfchar\n<0002> <0042>\nendbfchar\n".repeat(10); + let short = format!( + "/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 /{} 1 >> def\n% (an unclosed comment\n{head}{padding}endcmap\n", + "A".repeat(600) + ); + assert!(hex.len() < super::MAX_TO_UNICODE); + let extra = first_extra(1); + let names = ["Hex", "Literal", "Zeros", "Hidden", "Short"]; + let fonts: Vec = names + .iter() + .enumerate() + .map(|(i, name)| { + format!( + "/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W [1 [500] 256 511 500] >>] >>", + extra + i + ) + }) + .collect(); + let page = PdfPage { resources: format!("/Font << {} >>", fonts.join(" ")), ..PdfPage::new(100.0, 100.0, "") }; + let maps: Vec = + [hex, literal, zeros, hidden, short].iter().map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect(); + let refs: Vec<&str> = maps.iter().map(String::as_str).collect(); + let file = pdf_with(&[page], &refs, None); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + for unread in ["Hex", "Literal", "Zeros", "Hidden"] { + assert!(widths.widths(unread).is_none(), "{unread}"); + } + let short = widths.widths("Short").map(|w| w.iter().map(|(c, w)| (*c, *w)).collect::>()); + assert_eq!(short, Some(vec![('A', 500.0)])); + } + + /// Past [`super::MAX_LOOKUPS`] codes of a composite font, no more are looked up, though few of + /// them gave a character: of two fonts whose `W` gives all 65,536 CIDs a width, the one whose + /// map gives CID 1 a character gives its width, and the one whose map only gives CID 20,000 one + /// gives none. + #[test] + fn codes_past_the_most_looked_up_are_left() { + let cmap = |code: &str| { + format!("begincmap\n1 begincodespacerange\n<0000> \nendcodespacerange\n1 beginbfchar\n<{code}> <0041>\nendbfchar\nendcmap\n") + }; + const { assert!(20_000 > super::MAX_LOOKUPS) }; + let extra = first_extra(1); + let font = |name: &str, map: usize| { + format!( + "/{name} << /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H /ToUnicode {} 0 R \ + /DescendantFonts [<< /Subtype /CIDFontType2 /W {} 0 R >>] >>", + extra + map, + extra + 2 + ) + }; + let page = PdfPage { resources: format!("/Font << {} {} >>", font("Near", 0), font("Far", 1)), ..PdfPage::new(100.0, 100.0, "") }; + let maps: Vec = + ["0001", "4E20"].iter().map(|c| cmap(c)).map(|m| format!("<< /Length {} >>\nstream\n{m}endstream", m.len())).collect(); + let file = pdf_with(&[page], &[&maps[0], &maps[1], "[0 65535 500]"], None); + let widths = crate::open_pdf(&file, None).unwrap().page_widths(); + assert_eq!(widths.widths("Near").map(|w| w.get(&'A').copied()), Some(Some(500.0))); + assert!(widths.widths("Far").is_none()); + } + /// [`crate::import_scan::cid_ranges`] gives each CID of a `W` its values, a list's in turn (an /// incomplete last group left out) and a range's to each, and reads no more of a long list than /// the CIDs it takes. From c04ffd5f3fa4b58328b81251794b46b63108e1d6 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 17 Nov 2026 07:41:26 +0000 Subject: [PATCH 009/104] docs: roadmap: the copy pick's fallback and its 512 characters (#8087) The status line and the revision history said type is set in the copy that sets its characters at the PDF part's widths. The pick compares the first 512 characters, and without those widths, or with no copy that sets them all, it is the one before; both entries now say so. Co-Authored-By: Claude Opus 5.5 --- docs/roadmap.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index d71364fe34..d9d03a3300 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-16 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, #8087; scores and estimates unchanged; previously: M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M4: `.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), #8087; scores and estimates unchanged; previously: M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -212,7 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| -| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | +| 2026-11-16 | minor | M4: `.ai` import (#8087, follows #6983): type from the text document whose font record keeps no version, where installed copies of one font differ only in their widths, is set in the copy that sets the characters at the widths the file's PDF part gives them, compared on its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | | 2026-11-16 | minor | M1: rows or the selected-art square dragged over the Layers panel's list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | From 76892e8abfc540cf4b6d89e202d0826d2b2121a1 Mon Sep 17 00:00:00 2001 From: jmverges Date: Tue, 17 Nov 2026 08:34:34 +0000 Subject: [PATCH 010/104] docs: the parity status line and revision row give the copy pick's limits (#8087) As the roadmap now does: the pick compares the first 512 characters, and without the PDF part's widths, or with no installed copy that sets them all, it is the one before. Co-Authored-By: Claude Opus 5.5 --- docs/target-app-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b220c8b45a..e6e5a4dc4c 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-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them, follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (`.ai` import: type whose font record keeps no version is set in the installed copy of its font that sets the characters at the widths the file's PDF part gives them (its first 512 characters; without those widths, or with no copy that sets them all, the pick is the one before), follows #6983; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -61,7 +61,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | +| 2026-11-16 | minor | `.ai` import: type from the text document whose font record keeps no version, where installed copies of one PostScript name, family and style differ only in their widths, is set in the copy that sets the characters the file's PDF part draws at the widths the PDF part gives them, read from its font dictionaries without importing its pages; the pick compares the first 512 characters, and without those widths, or with no copy that sets them all, it is the one before (follows #6983; details in [file-format-parity.md](file-format-parity.md); tests in `crates/pdf/src/page_widths.rs`, `type_from_the_text_document_takes_the_copy_that_sets_the_pages_widths` in `crates/eps/src/import/tests_native.rs`, `records_of_one_font_share_its_page_widths_and_answer` in `crates/eps/src/import/ate.rs`, `type_from_the_text_document_takes_the_copy_its_pdf_part_sets_it_in` and `type_in_the_copy_its_pdf_part_sets_comes_back_in_it_from_a_save` in `crates/engine/src/cmd/fileio/tests_aiimport.rs`, `pdf_font_widths_never_panic` in `crates/engine/tests/import_fuzz.rs`). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); area score and estimate unchanged. | From 054d183842916742bc0d490676c7f0745ea3f1d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:44:20 -0800 Subject: [PATCH 011/104] Live Corners: pick any corner widget with Direct Selection Part of #1232. With Direct Selection and some corners picked, the widgets of the other corners used to hide, so a Shift-click could remove a picked corner but not add another one. Now every eligible widget shows: a picked corner's widget has a dot at its center and the others are hollow. - A click on a widget that is not picked picks its corner alone. A click on a picked widget keeps the picks, so Shift-clicking several corners and then double-clicking one of them opens Corners for all of them. A Shift-click adds or removes a corner on any selected path and keeps the other picks; on a path selected whole beside a path with picked corners it removes that corner (select.anchorsMany, mode toggle). While every corner of every path is picked, a click or Shift-click still picks that corner alone, as #6106 made it. - A drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, as one undo step, and does not pick it. A drag on a picked widget edits the picked corners alone. - Over a widget that is not picked, the end of a selected anchor's direction handle, or an anchor at least as near to the pointer as the widget's center, takes the press, the cursor and the double-click. Hollow widgets are drawn below the anchors and handles. - A Shift-click on a rounded corner picked by one of its two anchors removes the corner instead of swapping that anchor for the other. - The Selection tool and the shape tools still show and edit the picked corners' widgets alone, drawn as before. The angle, side length and Hide Corner Widget rules are unchanged. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md, docs/ui-parity.md. --- crates/engine/src/tests.rs | 30 +++ crates/tools/src/corners.rs | 210 ++++++++++++++----- crates/tools/src/corners/tests.rs | 289 ++++++++++++++++++++++++-- crates/tools/src/direct.rs | 22 +- crates/ui-egui/src/canvas/overlays.rs | 57 +++-- crates/ui-egui/src/canvas/tests.rs | 17 ++ crates/ui-egui/src/dialogs/corners.rs | 9 +- docs/control-protocol.md | 3 +- docs/mcp.md | 16 +- docs/target-app-parity.md | 5 +- docs/ui-parity.md | 2 +- 11 files changed, 564 insertions(+), 96 deletions(-) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index c39c88cbbb..f7bbd5ac2f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5024,6 +5024,36 @@ fn malformed_anchor_selection_never_replaces_or_partially_changes_selection() { assert!(!s.doc().unwrap().selection.contains(b)); } +/// #1232: through the session, Direct Selection's corner widgets pick corners across paths. With +/// a corner of `a` picked and `b` selected whole, a Shift-click on a widget of `b` deselects that +/// corner and keeps `b`'s other corners and `a`'s pick; one on a widget of `a` that is not picked +/// adds its corner. A Ctrl/Cmd-click (the Selection tool, lent) leaves the picks as they are. +#[test] +fn corner_widgets_pick_corners_across_paths_through_the_session() { + let mut s = session(); + let v = ViewInfo::default(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + let all = json!([[0, 0], [0, 1], [0, 2], [0, 3]]); + let start = json!({"items": [{"id": a.0, "anchors": [[0, 0]]}, {"id": b.0, "anchors": all}]}); + s.select_tool("directSelection", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64, mods: vectorcraft_tools::Mods| { + s.execute("select.anchorsMany", &start).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, x, y).with_mods(mods), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y).with_mods(mods), v).unwrap(); + let sel = &s.doc().unwrap().selection; + assert!(sel.contains(a) && sel.contains(b), "both stay selected"); + (sel.partial(a).cloned(), sel.partial(b).cloned()) + }; + let shift = vectorcraft_tools::Mods { shift: true, ..Default::default() }; + // The top-right widget of b. + assert_eq!(click(&mut s, 390.0, 110.0, shift), (Some([(0, 0)].into()), Some([(0, 0), (0, 2), (0, 3)].into()))); + // The top-right widget of a, not picked. + assert_eq!(click(&mut s, 190.0, 110.0, shift), (Some([(0, 0), (0, 1)].into()), None)); + let cmd = vectorcraft_tools::Mods { cmd: true, ..Default::default() }; + assert_eq!(click(&mut s, 190.0, 110.0, cmd), (Some([(0, 0)].into()), None), "a Ctrl/Cmd-click leaves the picks"); +} + #[test] fn path_commands_reject_bad_anchors_before_modifying_geometry() { let mut s = session(); diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index ab234cf507..a003391cce 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -1,8 +1,12 @@ //! Live Corners: the widgets inside the corners of the selected paths. The Selection tool shows //! them on live rectangles and polygons, Direct Selection on any path (a star, a pen path) at each //! corner anchor: one that isn't smooth, where two sides, straight or curved, meet at an angle. Dragging one rounds (or -//! sharpens) the corners whose widgets show together, on every selected path (#938): every corner -//! of a path selected whole, those with a selected anchor when Direct Selection picked some. Alt-clicking a widget cycles their corner +//! sharpens) the picked corners together, on every selected path (#938): every corner of a path +//! selected whole, those with a selected anchor when Direct Selection picked some. Direct Selection +//! also shows the widgets of the corners it did not pick, drawn apart from the picked ones, so a +//! click or Shift-click on any of them picks it (#1232); a plain click on a picked one keeps the +//! picks, so a double-click opens Corners for all of them; dragging or Alt-clicking one that is +//! not picked adds its corner to the edit. Alt-clicking a widget cycles their corner //! kind (round, inverted round, chamfer), as the Up and Down arrows do while one is dragged //! (#2898); double-clicking one opens the Corners dialog. The //! Selection and Direct Selection tools share this, and the canvas draws the widgets from the same @@ -39,6 +43,8 @@ struct Widget { angle: f64, /// The widget's centre in the document. at: Point, + /// Its corner is picked: a drag, an Alt-click and the Corners dialog edit it. + picked: bool, } /// The corner widgets of one selected path. @@ -47,16 +53,19 @@ struct PathWidgets { id: NodeId, /// Maps the corners' space into the document (a live rectangle's own; else none). xf: Affine, - /// The widgets that show (and which a drag edits), in anchor order. + /// The widgets that show, picked or not, in anchor order. widgets: Vec, - /// Every corner of the path shows its widget. - all: bool, + /// How many corners the path has, shown or not. + total: usize, + /// Every corner of the path is selected: the path selected whole, or every corner's anchor. + whole: bool, } impl PathWidgets { /// The widgets of path `id` at `zoom` (screen px per document point), if it has any: any path - /// with Direct Selection (`any_path`), live rectangles and polygons with Selection. `id` is - /// editable ([`Document::is_editable`]). + /// with Direct Selection (`any_path`), every corner's, picked or not; live rectangles' and + /// polygons' with Selection, the picked corners' alone. `id` is editable + /// ([`Document::is_editable`]). fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool) -> Option { if selection.segments.contains_key(&id) { return None; @@ -72,27 +81,45 @@ impl PathWidgets { } // Screen pixels per unit of the corners' space (a rectangle's may be skewed). let scale = zoom * det.sqrt(); - let picked = lc.picked(selection.partial(id)); + let partial = selection.partial(id); + let picked = lc.picked(partial); + let whole = partial.is_none_or(|anchors| lc.all().is_subset(&lc.corners_of(anchors))); let widgets: Vec<_> = lc .corners .iter() - .filter(|c| picked.contains(&c.index) && c.lu.min(c.lv) * scale >= MIN_SIDE_PX) + .filter(|c| (any_path || picked.contains(&c.index)) && c.lu.min(c.lv) * scale >= MIN_SIDE_PX) .map(|c| { // On the bisector at the centre of the arc as drawn, at least the minimum inset // in and at most half the shorter side. let (radius, drawn) = (lc.radius(c.index), lc.drawn_radius(c.index)); let k = (drawn / c.sin()).max(MIN_INSET_PX / (scale * (1.0 + c.cos()).sqrt())).min(c.lu.min(c.lv) / 2.0); - Widget { corner: *c, radius, drawn, kind: lc.kind(c.index), angle: angle_in(lc.xf, c), at: lc.xf * c.on_bisector(k) } + let at = lc.xf * c.on_bisector(k); + Widget { corner: *c, radius, drawn, kind: lc.kind(c.index), angle: angle_in(lc.xf, c), at, picked: picked.contains(&c.index) } }) .collect(); - let all = widgets.len() == lc.corners.len(); - (!widgets.is_empty()).then_some(Self { id, xf: lc.xf, widgets, all }) + (!widgets.is_empty()).then_some(Self { id, xf: lc.xf, widgets, total: lc.corners.len(), whole }) } /// The corners whose widgets show: anchor indices of the path's uncut outline. fn corners(&self) -> Vec { self.widgets.iter().map(|w| w.corner.index).collect() } + + /// The shown corners that are picked, which an edit changes. + fn edited(&self) -> Vec { + self.widgets.iter().filter(|w| w.picked).map(|w| w.corner.index).collect() + } + + /// An edit changes every corner of the path, which the selection already selects: each one + /// shows and is picked, and none was picked by the press alone. + fn edits_every(&self) -> bool { + self.whole && self.widgets.len() == self.total && self.widgets.iter().all(|w| w.picked) + } + + /// Is shown corner `index` edited? + fn edits(&self, index: usize) -> bool { + self.widgets.iter().any(|w| w.picked && w.corner.index == index) + } } /// The corner widgets of the selected paths that have some. @@ -115,9 +142,7 @@ impl CornerWidgets { /// corners wider than `max` degrees (in the document) hide; none if all do. pub fn within_angle(mut self, max: f64) -> Option { for p in &mut self.paths { - let n = p.widgets.len(); p.widgets.retain(|w| w.angle <= max + 1e-9); - p.all &= p.widgets.len() == n; } self.paths.retain(|p| !p.widgets.is_empty()); (!self.paths.is_empty()).then_some(self) @@ -141,12 +166,13 @@ impl CornerWidgets { /// The centres of the widgets that show. pub fn visible(&self) -> impl Iterator + '_ { - self.visible_on().map(|(_, at)| at) + self.visible_on().map(|(_, at, _)| at) } - /// The centres of the widgets that show, each with the object it belongs to. - pub fn visible_on(&self) -> impl Iterator + '_ { - self.paths.iter().flat_map(|p| p.widgets.iter().map(move |w| (p.id, w.at))) + /// The centers of the widgets that show, each with the object it belongs to and whether its + /// corner is picked. + pub fn visible_on(&self) -> impl Iterator + '_ { + self.paths.iter().flat_map(|p| p.widgets.iter().map(move |w| (p.id, w.at, w.picked))) } /// The corners whose widgets show, path after path: anchor indices of each path's uncut @@ -155,28 +181,37 @@ impl CornerWidgets { self.paths.iter().flat_map(PathWidgets::corners).collect() } - /// The widget nearest to `p` within `tol` (document units): its path's and its own index. + /// The shown corners that are picked, path after path, which a drag, an Alt-click or the + /// Corners dialog edit. + pub fn picked(&self) -> Vec { + self.paths.iter().flat_map(PathWidgets::edited).collect() + } + + /// The widget nearest to `p` within `tol` (document units): its path's and its own index. Of + /// widgets at the same spot, a picked one. fn hit(&self, p: Point, tol: f64) -> Option<(usize, usize)> { let d = |&(i, k): &(usize, usize)| self.widget(i, k).map_or(f64::INFINITY, |w| w.at.distance(p)); + let unpicked = |&(i, k): &(usize, usize)| self.widget(i, k).is_none_or(|w| !w.picked); self.paths .iter() .enumerate() .flat_map(|(i, path)| (0..path.widgets.len()).map(move |k| (i, k))) .filter(|ik| d(ik) <= tol) - .min_by(|a, b| d(a).total_cmp(&d(b))) + .min_by(|a, b| d(a).total_cmp(&d(b)).then(unpicked(a).cmp(&unpicked(b)))) } fn widget(&self, path: usize, k: usize) -> Option<&Widget> { self.paths.get(path).and_then(|p| p.widgets.get(k)) } - /// `object.setLiveShape` params setting `key` on the shown corners (every corner of a path - /// unless some are hidden, which `corners` then leaves out): one path by its `id`, several as - /// `items`. + /// `object.setLiveShape` params setting `key` on the picked corners that show (every corner of + /// a path when all are, which `corners` then leaves out): one path by its `id`, several as + /// `items`. Paths with no picked corner whose widget shows are left out. fn command(&self, key: &str, value: Value) -> Value { - let corners = |p: &PathWidgets| (!p.all).then(|| p.corners()); + let corners = |p: &PathWidgets| (!p.edits_every()).then(|| p.edited()); + let paths: Vec<&PathWidgets> = self.paths.iter().filter(|p| p.widgets.iter().any(|w| w.picked)).collect(); let mut out = Map::new(); - match self.paths.as_slice() { + match paths.as_slice() { [p] => { out.insert("id".into(), json!(p.id.0)); if let Some(c) = corners(p) { @@ -209,15 +244,37 @@ fn angle_in(xf: Affine, c: &Corner) -> f64 { /// Is `p` over a corner widget the active tool would drag (Direct Selection: `any_path`)? pub fn over_widget(cx: &ToolContext, p: Point, any_path: bool) -> bool { - CornerWidgets::for_tool(cx, any_path).and_then(|w| w.hit(p, cx.tol(5.0))).is_some() + widget_at(cx, p, any_path).is_some() } -/// A double-click on a corner widget opens the Corners dialog for the shown corners of its path. -pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option { +/// The corner widget at `p` the active tool would drag (Direct Selection: `any_path`): whether its +/// corner is picked, and its center. +pub fn widget_at(cx: &ToolContext, p: Point, any_path: bool) -> Option<(bool, Point)> { let w = CornerWidgets::for_tool(cx, any_path)?; - let (i, _) = w.hit(p, cx.tol(5.0))?; + let (i, k) = w.hit(p, cx.tol(5.0))?; + w.widget(i, k).map(|w| (w.picked, w.at)) +} + +/// A double-click on a corner widget opens the Corners dialog for the picked corners of its path +/// that show, or for the clicked widget's corner alone when it is not picked. With Direct +/// Selection the double-click's first click has left the picks as they are on a picked widget, +/// and picked that corner alone on one that is not (`CornerDrag::finish`). +pub fn double_click(cx: &ToolContext, p: Point, any_path: bool) -> Option { + double_click_unless(cx, p, any_path, |_| false) +} + +/// [`double_click`], except that a widget whose corner is not picked does nothing when `yields` +/// for its center (something else under the pointer takes the double-click). +pub fn double_click_unless(cx: &ToolContext, p: Point, any_path: bool, yields: impl FnOnce(Point) -> bool) -> Option { + let w = CornerWidgets::for_tool(cx, any_path)?; + let (i, k) = w.hit(p, cx.tol(5.0))?; let path = w.paths.get(i)?; - Some(Action::Dialog(DIALOG.into(), json!({ "id": path.id.0, "corners": path.corners() }))) + let clicked = path.widgets.get(k)?; + if !clicked.picked && yields(clicked.at) { + return None; + } + let corners: Vec = if clicked.picked { path.edited() } else { vec![clicked.corner.index] }; + Some(Action::Dialog(DIALOG.into(), json!({ "id": path.id.0, "corners": corners }))) } /// A path's uncut outline with its corners' radii and kinds, and the corners' space (to outline @@ -253,6 +310,8 @@ pub struct CornerDrag { at: Point, /// Direct Selection: what a click (no drag) on the pressed widget selects. click: Option, + /// The pressed widget's corner was not picked: the press adds it to the edit. + unpicked: bool, /// The corner kind the Up and Down arrows picked during the drag, which it sets with the /// radius (#2898); None: the corners keep theirs. kind: Option, @@ -264,7 +323,21 @@ pub struct CornerDrag { struct CornerClick { id: NodeId, anchors: Vec<(usize, usize)>, - shift: bool, + mode: ClickMode, +} + +/// How a click on a widget changes the selected anchors. +#[derive(Clone, Copy, Debug, PartialEq)] +enum ClickMode { + /// The corner alone is selected. + Set, + /// The selection stays as it is: a plain click on a picked widget while some corners are not + /// picked, as a plain click on one of several selected anchors keeps them. + Keep, + /// The corner's anchors are toggled on a path with some anchors selected. + Toggle, + /// The corner's anchors are toggled on a path selected whole, starting from all of them. + ToggleWhole, } impl CornerDrag { @@ -273,26 +346,62 @@ impl CornerDrag { self.began } + /// The pressed widget's corner is not picked. + pub fn on_unpicked(&self) -> bool { + self.unpicked + } + + /// The pressed widget's center. + pub fn widget_center(&self) -> Option { + self.widgets.widget(self.widget.0, self.widget.1).map(|w| w.at) + } + /// Start a drag when the press `ev` is on a widget of the selection (Direct Selection: /// `any_path`). pub fn hit(cx: &ToolContext, ev: &PointerEvent, any_path: bool) -> Option { - let (widgets, p) = (CornerWidgets::for_tool(cx, any_path)?, ev.pos); + let (mut widgets, p) = (CornerWidgets::for_tool(cx, any_path)?, ev.pos); let widget = widgets.hit(p, cx.tol(5.0))?; - let radius = widgets.widget(widget.0, widget.1)?.radius; + let (radius, unpicked) = widgets.widget(widget.0, widget.1).map(|w| (w.radius, !w.picked))?; let click = any_path .then(|| { let path = widgets.paths.get(widget.0)?; let corner = path.widgets.get(widget.1)?.corner.index; let lc = cx.doc.node(path.id).and_then(LiveCorners::of)?; - // While every corner is selected (the path selected whole), a Shift-click picks - // this corner alone, as the first click of "click one widget, then Shift-click the - // others" does: toggling it would deselect it and leave the rest (#5188). Selected - // anchors that are no corner show every widget too, but select no corner: there a - // Shift-click adds the corner. - let every = cx.selection.partial(path.id).is_none_or(|anchors| lc.all().is_subset(&lc.corners_of(anchors))); - Some(CornerClick { id: path.id, anchors: lc.anchors_of(&[corner].into()).into_iter().collect(), shift: ev.mods.shift && !every }) + // While every corner of every path with widgets is selected (the paths selected + // whole), a Shift-click picks this corner alone, as the first click of "click one + // widget, then Shift-click the others" does: toggling it would deselect it and + // leave the rest (#5188). Selected anchors that are no corner show every widget + // too, but select no corner: there a Shift-click adds the corner. + let every = widgets.paths.iter().all(|p| p.whole); + // A plain click on a widget whose corner is selected keeps the picks, so the second + // click of a double-click opens Corners for all of them. Anchors that are no corner + // pick every widget but select no corner. + let selected = cx.selection.partial(path.id).is_none_or(|anchors| lc.corners_of(anchors).contains(&corner)); + let mode = match (ev.mods.shift && !every, cx.selection.partial(path.id).is_some()) { + (false, _) if !every && !unpicked && selected => ClickMode::Keep, + (false, _) => ClickMode::Set, + (true, true) => ClickMode::Toggle, + // A path selected whole beside others with corners picked: the Shift-click + // deselects this corner and keeps the rest of the path selected. + (true, false) => ClickMode::ToggleWhole, + }; + // A toggle takes the corner out or puts it in whole: of a corner drawn with two + // anchors, it flips only the selected ones of a selected corner and only the others + // of a corner not selected, so one selected anchor does not swap for the other. + let partial = cx.selection.partial(path.id); + let anchors = lc + .anchors_of(&[corner].into()) + .into_iter() + .filter(|a| mode != ClickMode::Toggle || partial.is_some_and(|s| s.contains(a)) == selected) + .collect(); + Some(CornerClick { id: path.id, anchors, mode }) }) .flatten(); + // Pressing a widget whose corner is not picked adds that corner to what the press edits; + // the press does not pick it. + if let Some(w) = widgets.paths.get_mut(widget.0).and_then(|path| path.widgets.get_mut(widget.1)) { + w.picked = true; + } let outlines = widgets .paths .iter() @@ -315,6 +424,7 @@ impl CornerDrag { at_limit: false, at: p, click, + unpicked, kind: None, }) } @@ -333,21 +443,21 @@ impl CornerDrag { (r.min(max).max(0.0), max > 0.0 && r >= max) } - /// The largest radius `corner` of shown path `path` draws while the drag sets every shown + /// The largest radius `corner` of shown path `path` draws while the drag sets every edited /// corner of that path to one radius: up to the cuts of its neighbours, as far as its own /// sides when they are square (#2332). fn max_radius(&self, path: usize, corner: &Corner) -> f64 { let (Some(shown), Some(o)) = (self.widgets.paths.get(path), self.outlines.get(path)) else { return corner.max_radius() }; - corner.max_shared_radius(&o.corners, &o.radii, |k| shown.widgets.iter().any(|w| w.corner.index == k)) + corner.max_shared_radius(&o.corners, &o.radii, |k| shown.edits(k)) } /// The cuts of the edited corners that are at their largest radius, in document coordinates. fn corners_at_limit(&self) -> BezPath { let mut out = BezPath::new(); for (n, (shown, o)) in self.widgets.paths.iter().zip(&self.outlines).enumerate() { - let shown = &shown.widgets; + let shown: Vec<&Widget> = shown.widgets.iter().filter(|w| w.picked).collect(); let mut radii = o.radii.clone(); - for w in shown { + for w in &shown { if let Some(r) = radii.get_mut(w.corner.index) { *r = self.radius; } @@ -430,9 +540,15 @@ impl CornerDrag { vec![Action::Exec("object.setLiveShape".into(), self.widgets.command("kind", json!(w.kind.next())))] } else if let Some(c) = self.click { // Direct Selection: the click selects the widget's corner, so the next drag on this - // widget rounds that corner alone (its widget is then the only one showing). - let mode = if c.shift { "toggle" } else { "set" }; - vec![Action::Exec("select.anchors".into(), json!({"id": c.id.0, "anchors": c.anchors, "mode": mode}))] + // widget rounds that corner alone; the other corners' widgets show as not picked. + match c.mode { + ClickMode::Keep => vec![], + ClickMode::Set => vec![Action::Exec("select.anchors".into(), json!({"id": c.id.0, "anchors": c.anchors, "mode": "set"}))], + ClickMode::Toggle => vec![Action::Exec("select.anchors".into(), json!({"id": c.id.0, "anchors": c.anchors, "mode": "toggle"}))], + ClickMode::ToggleWhole => { + vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": c.id.0, "anchors": c.anchors}], "mode": "toggle"}))] + } + } } else { vec![] } diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 21b240b453..182e9bb221 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -119,10 +119,12 @@ fn widgets_of_several_selected_paths_drag_together() { assert!((radius(&preview[1]) - 15.0).abs() < 1e-9); let Action::Preview(_, v) = &preview[1] else { panic!() }; assert_eq!(v["items"], json!([{"id": a.0}, {"id": b.0}])); - // Direct Selection with one anchor of the first: its corner, and the whole second. + // Direct Selection with one anchor of the first: every widget shows, and a drag edits its + // corner and the whole second. s.anchors.insert(a, [(0, 2)].into()); let w = CornerWidgets::of(&d, &s, 1.0, true).unwrap(); - assert_eq!(w.corners(), [2, 0, 1, 2, 3]); + assert_eq!(w.corners(), [0, 1, 2, 3, 0, 1, 2, 3]); + assert_eq!(w.picked(), [2, 0, 1, 2, 3]); assert_eq!(w.command("radius", json!(5.0)), json!({"items": [{"id": a.0, "corners": [2]}, {"id": b.0}], "radius": 5.0})); } @@ -213,11 +215,11 @@ fn a_click_on_a_widget_with_direct_selection_selects_its_corner() { assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, w.x, w.y)).is_empty()); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, w.x, w.y)); assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": anchors, "mode": "set"}))]); - // With that corner selected, its widget alone shows, and a drag rounds it alone - // (`direct_selected_corners_show_their_widgets_alone_and_round_alone`). + // With that corner selected, its widget alone is picked, and a drag on it rounds it alone + // (`direct_selected_corners_are_picked_and_round_alone`). let mut part = selected(id); part.anchors.insert(id, anchors.iter().copied().collect()); - assert_eq!(CornerWidgets::of(&d, &part, 1.0, true).unwrap().corners(), [2]); + assert_eq!(CornerWidgets::of(&d, &part, 1.0, true).unwrap().picked(), [2]); // A Shift-click on it then deselects it. let shift = Mods { shift: true, ..Mods::default() }; let one = crate::testutil::cx(&d, &part, &p); @@ -256,12 +258,40 @@ fn a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner() { let mut every = selected(id); every.anchors.insert(id, (0..4).flat_map(anchors).collect()); assert_eq!(click(&every, w[1]), pick(1, "set")); - // Two corners picked: a Shift-click on either widget deselects that corner. + // Two corners picked: every widget still shows; a Shift-click on a picked one deselects that + // corner, and on one not picked adds it (#1232). let mut two = selected(id); two.anchors.insert(id, [0, 2].into_iter().flat_map(anchors).collect()); let shown = pts(&CornerWidgets::of(&d, &two, 1.0, true).unwrap()); - assert_eq!(shown, [w[0], w[2]]); + assert_eq!(shown, w); assert_eq!(click(&two, w[0]), pick(0, "toggle")); + assert_eq!(click(&two, w[1]), pick(1, "toggle")); +} + +/// #1232: a Shift-click on the widget of a rounded corner picked by one of its two anchors takes +/// the corner out whole (that anchor), and on a corner not picked puts both anchors in, so it never +/// swaps one anchor for the other and leaves the corner picked. +#[test] +fn a_shift_click_toggles_a_rounded_corner_whole() { + let (d, id) = live_rect(10.0, Affine::translate((100.0, 100.0))); + let p = paint(); + let lc = LiveCorners::of(d.node(id).unwrap()).unwrap(); + let anchors = |k: usize| -> Vec<(usize, usize)> { lc.anchors_of(&[k].into()).into_iter().collect() }; + // One anchor of corner 0 and one of corner 2. + let (first, second) = (anchors(0)[0], anchors(2)[1]); + let mut s = selected(id); + s.anchors.insert(id, [first, second].into()); + let cx = cx(&d, &s, &p); + let w = pts(&CornerWidgets::for_tool(&cx, true).unwrap()); + let shift = Mods { shift: true, ..Mods::default() }; + let click = |at: Point| { + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(shift)) + }; + let toggle = |a: Vec<(usize, usize)>| vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": a, "mode": "toggle"}))]; + assert_eq!(click(w[2]), toggle(vec![second])); + assert_eq!(click(w[1]), toggle(anchors(1))); } /// #5188: an anchor selected that is no corner (here half way along a side) shows every widget @@ -285,10 +315,233 @@ fn a_shift_click_on_a_widget_adds_to_anchors_that_are_no_corner() { t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift)); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(shift)); assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": anchors, "mode": "toggle"}))]); + // A plain click picks the corner alone: no corner was selected to keep (#1232). + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y)); + assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": anchors, "mode": "set"}))]); +} + +/// Two live 100 × 100 rectangles with square corners, at (100, 100) and (300, 100). +fn two_rects() -> (Document, NodeId, NodeId) { + let (mut d, a) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let live = LiveShape::Rectangle { + w: 100.0, + h: 100.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((300.0, 100.0)), + }; + let b = d.alloc_id(); + let mut n = Node::path(b, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + (d, a, b) +} + +/// #1232: with some corners picked, a press on a widget that is not picked adds its corner to what +/// the press edits: a drag rounds it with the picked ones and an Alt-click cycles their kind, and +/// the press picks nothing. A drag on a picked widget edits the picked corners alone. A plain +/// click on a widget not picked picks its corner alone, and on a picked one keeps the picks, so a +/// double-click on a picked widget opens Corners for every picked corner. +#[test] +fn a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners() { + let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + // The top-left and bottom-right corners picked. + let mut s = selected(id); + s.anchors.insert(id, [(0, 0), (0, 2)].into()); + let p = paint(); + let cx = cx(&d, &s, &p); + let preview = |at: (f64, f64), to: (f64, f64)| { + let mut t = crate::create("directSelection"); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.0, at.1)).is_empty()); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)); + assert_eq!(a[0], Action::Begin("Corner Radius".into())); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1)), vec![Action::Commit], "one undo step"); + a[1].clone() + }; + // The top-right widget (not picked) dragged in: corners 0, 1 and 2 round. + assert_eq!( + preview((190.0, 110.0), (175.0, 125.0)), + Action::Preview("object.setLiveShape".into(), json!({"id": id.0, "radius": 15.0, "corners": [0, 1, 2]})) + ); + // The top-left widget (picked) dragged in: corners 0 and 2 alone. + assert_eq!( + preview((110.0, 110.0), (125.0, 125.0)), + Action::Preview("object.setLiveShape".into(), json!({"id": id.0, "radius": 15.0, "corners": [0, 2]})) + ); + // With three picked, the fourth widget's drag edits every corner, named one by one: without + // `corners`, the command would edit the three the selection picks. + let mut three = selected(id); + three.anchors.insert(id, [(0, 0), (0, 1), (0, 2)].into()); + let cx3 = crate::testutil::cx(&d, &three, &p); + let mut t = crate::create("directSelection"); + t.pointer(&cx3, &PointerEvent::new(PointerKind::Down, 110.0, 190.0)); + let a = t.pointer(&cx3, &PointerEvent::new(PointerKind::Drag, 125.0, 175.0)); + assert_eq!(a[1], Action::Preview("object.setLiveShape".into(), json!({"id": id.0, "radius": 15.0, "corners": [0, 1, 2, 3]}))); + // An Alt-click on the bottom-left widget (not picked) cycles the kind of 0, 2 and 3. + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 190.0).with_mods(alt)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 190.0).with_mods(alt)); + assert_eq!(a, vec![Action::Exec("object.setLiveShape".into(), json!({"id": id.0, "kind": "invertedRound", "corners": [0, 2, 3]}))]); + // A double-click on it opens Corners for its corner alone, which its first click picks. + let a = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 190.0)); + assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [3]}))]); + // A plain click on it (no drag) picks its corner alone. + let bottom_left: Vec<(usize, usize)> = LiveCorners::of(d.node(id).unwrap()).unwrap().anchors_of(&[3].into()).into_iter().collect(); + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 190.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 190.0)); + assert_eq!(a, vec![Action::Exec("select.anchors".into(), json!({"id": id.0, "anchors": bottom_left, "mode": "set"}))]); + // A plain click on the picked top-left widget keeps both picks, so a double-click there, whose + // first click is such a click, opens Corners for both. + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 110.0)); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 110.0, 110.0)).is_empty()); + let a = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 110.0)); + assert_eq!(a, vec![Action::Dialog(DIALOG.into(), json!({"id": id.0, "corners": [0, 2]}))]); +} + +/// #1232: over a widget whose corner is not picked, the end of a selected anchor's direction +/// handle takes the press, the cursor and the double-click; here the handle of a curve's first +/// anchor ends on the rectangle's top-left widget. A picked widget there still takes them. +#[test] +fn a_handle_end_over_a_widget_not_picked_takes_the_press() { + let (mut d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let line = d.alloc_id(); + let (a, b) = (Point::new(150.0, 150.0), Point::new(250.0, 150.0)); + let anchors = vec![vectorcraft_geom::Anchor::with_handles(a, a, Point::new(110.0, 110.0)), vectorcraft_geom::Anchor::with_handles(b, b, b)]; + let path = PathData::single(vectorcraft_geom::SubPath::new(anchors, false)); + let l = d.layers[0].id; + d.insert(Some(l), 1, Node::path(line, path, Appearance::default_art())).unwrap(); + let p = paint(); + let pressed = |s: &Selection| { + let cx = crate::testutil::cx(&d, s, &p); + let mut t = crate::create("directSelection"); + let cursor = t.cursor(&cx, Point::new(110.0, 110.0), Mods::default()); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 110.0)); + let corner = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 125.0)).contains(&Action::Begin("Corner Radius".into())); + let double = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 110.0, 110.0)); + (corner, cursor == crate::Cursor::CornerRadius, double.iter().any(|a| matches!(a, Action::Dialog(k, _) if k == DIALOG))) + }; + // The bottom-right corner picked and the curve's first anchor selected: the top-left widget is + // not picked, and the handle end takes the press, the cursor and the double-click. + let mut s = selected(id); + s.add(line); + s.anchors.insert(id, [(0, 2)].into()); + s.anchors.insert(line, [(0, 0)].into()); + assert_eq!(pressed(&s), (false, false, false)); + // The top-left corner picked: its widget takes them. + s.anchors.insert(id, [(0, 0)].into()); + assert_eq!(pressed(&s), (true, true, true)); +} + +/// #1232: over a widget whose corner is not picked, an anchor no farther from the pointer than the +/// widget's center takes the press, the cursor and the double-click; here the end of a line that is +/// not selected, pressed off the widget's center or on it. One farther than the center, though +/// within point tolerance, leaves them to the widget. +#[test] +fn a_nearer_anchor_over_a_widget_not_picked_takes_the_press() { + for (end, at, widget) in + [((113.0, 113.0), (112.0, 112.0), false), ((110.0, 110.0), (110.0, 110.0), false), ((109.0, 109.0), (112.0, 112.0), true)] + { + let (mut d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let line = d.alloc_id(); + let path = PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(end.0, end.1), Point::new(150.0, 160.0)], false)); + let l = d.layers[0].id; + d.insert(Some(l), 1, Node::path(line, path, Appearance::default_art())).unwrap(); + let p = paint(); + let mut s = selected(id); + s.anchors.insert(id, [(0, 2)].into()); + let cx = crate::testutil::cx(&d, &s, &p); + let at = Point::new(at.0, at.1); + let mut t = crate::create("directSelection"); + let cursor = t.cursor(&cx, at, Mods::default()) == crate::Cursor::CornerRadius; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let corner = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 125.0)).contains(&Action::Begin("Corner Radius".into())); + let double = crate::create("directSelection").pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, at.x, at.y)); + let dialog = double.iter().any(|a| matches!(a, Action::Dialog(k, _) if k == DIALOG)); + assert_eq!((corner, cursor, dialog), (widget, widget, widget), "line end at {end:?}, pressed at {at:?}"); + } +} + +/// #1232: corners are picked across paths. With a corner of one rectangle picked and the other +/// rectangle selected whole, a Shift-click on a widget of either toggles that corner and keeps the +/// rest of the selection: on the whole rectangle it deselects the corner and leaves the other +/// three selected. A drag on a widget not picked edits it with every picked corner of both. +#[test] +fn widgets_are_picked_across_paths() { + let (d, a, b) = two_rects(); + let mut s = selected(a); + s.add(b); + s.anchors.insert(a, [(0, 0)].into()); + let p = paint(); + let cx = cx(&d, &s, &p); + let w = CornerWidgets::for_tool(&cx, true).unwrap(); + assert_eq!(w.corners(), [0, 1, 2, 3, 0, 1, 2, 3]); + assert_eq!(w.picked(), [0, 0, 1, 2, 3]); + let shift = Mods { shift: true, ..Mods::default() }; + let click = |at: Point| { + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(shift)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(shift)) + }; + // The second rectangle's top-right widget (picked, the rectangle selected whole). + assert_eq!( + click(Point::new(390.0, 110.0)), + vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": b.0, "anchors": [[0, 1]]}], "mode": "toggle"}))] + ); + // The first rectangle's top-right widget (not picked). + assert_eq!( + click(Point::new(190.0, 110.0)), + vec![Action::Exec("select.anchors".into(), json!({"id": a.0, "anchors": [[0, 1]], "mode": "toggle"}))] + ); + // Dragging the first rectangle's bottom-left widget (not picked). + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 110.0, 190.0)); + let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 125.0, 175.0)); + assert_eq!( + out[1], + Action::Preview("object.setLiveShape".into(), json!({"items": [{"id": a.0, "corners": [0, 3]}, {"id": b.0}], "radius": 15.0})) + ); + // Both selected whole: a Shift-click still picks that corner alone (#5188). + let both = { + let mut s = selected(a); + s.add(b); + s + }; + let cxb = crate::testutil::cx(&d, &both, &p); + let mut t = crate::create("directSelection"); + t.pointer(&cxb, &PointerEvent::new(PointerKind::Down, 390.0, 110.0).with_mods(shift)); + let out = t.pointer(&cxb, &PointerEvent::new(PointerKind::Up, 390.0, 110.0).with_mods(shift)); + assert_eq!(out, vec![Action::Exec("select.anchors".into(), json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"}))]); +} + +/// #1232: a path whose picked corners are all hidden (wider than the angle preference) is left +/// out of a drag that starts on another path; the drag edits only corners that are picked or +/// pressed. +#[test] +fn a_path_with_no_picked_widget_showing_is_left_out_of_a_drag() { + let (d, a, b) = two_rects(); + let mut s = selected(a); + s.add(b); + // One anchor of a picked; b selected whole. + s.anchors.insert(a, [(0, 0)].into()); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut w = CornerWidgets::for_tool(&cx, true).unwrap(); + // Drop the picked flag of a's widgets as if they were all hidden, keeping one unpicked shown. + w.paths[0].widgets.retain(|w| !w.picked); + assert_eq!(w.command("radius", json!(5.0)), json!({"id": b.0, "radius": 5.0})); } #[test] -fn direct_selected_corners_show_their_widgets_alone_and_round_alone() { +fn direct_selected_corners_are_picked_and_round_alone() { let (d, id) = live_rect(0.0, Affine::translate((100.0, 100.0))); // Direct Selection picked the bottom-right anchor. let mut s = selected(id); @@ -296,9 +549,15 @@ fn direct_selected_corners_show_their_widgets_alone_and_round_alone() { let p = paint(); let cx = cx(&d, &s, &p); let w = CornerWidgets::of(&d, &s, 1.0, true).unwrap(); - assert_eq!(w.corners(), [2]); - assert_eq!(pts(&w), [Point::new(190.0, 190.0)]); - assert!(!over_widget(&cx, Point::new(110.0, 110.0), true), "the other corners hide theirs"); + assert_eq!(w.picked(), [2]); + let states: Vec<_> = w.visible_on().map(|(_, at, picked)| (at, picked)).collect(); + let at = |x, y| Point::new(x, y); + assert_eq!(states, [(at(110.0, 110.0), false), (at(190.0, 110.0), false), (at(190.0, 190.0), true), (at(110.0, 190.0), false)]); + assert!(over_widget(&cx, Point::new(110.0, 110.0), true), "the other corners' widgets show and can be pressed (#1232)"); + // The Selection tool still shows the picked corners' widgets alone. + let selection = CornerWidgets::of(&d, &s, 1.0, false).unwrap(); + assert_eq!(pts(&selection), [Point::new(190.0, 190.0)]); + assert!(!over_widget(&cx, Point::new(110.0, 110.0), false)); let mut t = crate::create("directSelection"); assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 190.0, 191.0)).is_empty()); let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 175.0, 176.0)); @@ -326,7 +585,7 @@ fn a_corner_rounded_alone_rounds_up_to_its_neighbours() { s.anchors.insert(id, [(0, if top_right > 0.0 { 3 } else { 2 })].into()); let p = paint(); let cx = cx(&d, &s, &p); - assert_eq!(CornerWidgets::of(&d, &s, 1.0, true).unwrap().corners(), [2]); + assert_eq!(CornerWidgets::of(&d, &s, 1.0, true).unwrap().picked(), [2]); let mut t = crate::create("directSelection"); t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 190.0, 190.0)); assert!((radius(&t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 130.0))[1]) - 60.0).abs() < 1e-9); @@ -462,7 +721,7 @@ fn star_path(d: &Document, id: NodeId) -> PathData { path.clone() } -/// #511: a Direct-Selected anchor of the star shows its corner's widget alone, and the +/// #511: a Direct-Selected anchor of the star picks its corner's widget alone, and the /// preference hides the star's wide inner corners (about 125°) below their angle. #[test] fn star_corners_follow_the_anchors_and_the_angle_preference() { @@ -472,9 +731,9 @@ fn star_corners_follow_the_anchors_and_the_angle_preference() { let p = paint(); let c = cx(&d, &s, &p); let w = CornerWidgets::for_tool(&c, true).unwrap(); - assert_eq!(w.corners(), [3]); + assert_eq!(w.picked(), [3]); let mut t = crate::create("directSelection"); - let at = pts(&w)[0]; + let at = pts(&w)[3]; t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)); let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, at.x + 20.0, at.y + 20.0)); assert!(matches!(&a[1], Action::Preview(_, v) if v["corners"] == json!([3])), "{a:?}"); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index cd4432c3c8..62624f0889 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -61,7 +61,7 @@ use vectorcraft_doc::{AnchorRef, Node, NodeId, NodeKind, Selection, symbol_overr use vectorcraft_geom::{Anchor, PathData, PathSeg, Point, Rect, Vec2}; use crate::bbox::move_delta; -use crate::corners::{self, CornerDrag, over_widget}; +use crate::corners::{self, CornerDrag}; use crate::guides::{HandleSnap, Leave, PointSnap, Targets}; use crate::meshedit::{MeshEdit, grid_of}; use crate::pathtype::{self, BracketDrag, near_bracket}; @@ -680,6 +680,13 @@ fn type_path_handles(cx: &ToolContext) -> Vec { /// The end of a shown direction handle ([`handle_anchors`]) nearest to `p` within `tol`, and /// nearer to it than the handle's anchor (a short handle leaves its anchor to be picked): (path, /// subpath, anchor, is_out). +/// A press at `p` on a corner widget centered at `widget` whose corner is not picked goes to a +/// direction handle end within point tolerance, or to an anchor no farther from `p` than the +/// widget's center, instead; so do the cursor and a double-click (#1232). +fn yields_to_point(cx: &ToolContext, p: Point, widget: Point) -> bool { + hit_handle(cx, p, cx.point_tol()).is_some() || hit_anchor(cx, p, cx.point_tol().min(widget.distance(p))).is_some() +} + pub(crate) fn hit_handle(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, usize, bool)> { let mut best: Option<((NodeId, usize, usize, bool), f64)> = None; for (id, si, ai, a) in handle_anchors(cx) { @@ -912,7 +919,9 @@ impl Tool for DirectSelectionTool { self.click_segment = None; self.click_group = None; self.frame_click = None; - if let Some(c) = CornerDrag::hit(cx, ev, true) { + if let Some(c) = CornerDrag::hit(cx, ev, true) + && !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w))) + { self.state = State::Corner(c); return vec![]; } @@ -1173,7 +1182,10 @@ impl Tool for DirectSelectionTool { } } fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { - if !self.group && (matches!(self.state, State::Corner(_)) || over_widget(cx, p, true)) { + if !self.group + && (matches!(self.state, State::Corner(_)) + || corners::widget_at(cx, p, true).is_some_and(|(picked, w)| picked || !yields_to_point(cx, p, w))) + { return Cursor::CornerRadius; } if !self.group && (matches!(self.state, State::Bracket(_)) || near_bracket(cx, p) && !over_path_type_anchor(cx, p)) { @@ -1416,7 +1428,9 @@ impl DirectSelectionTool { } fn double_click(&mut self, cx: &ToolContext, ev: &PointerEvent, p: Point) -> Vec { self.state = State::Idle; - if let Some(a) = corners::double_click(cx, p, true) { + // As with a press, a handle end or a nearer anchor takes the double-click from a widget that + // is not picked. + if let Some(a) = corners::double_click_unless(cx, p, true, |w| yields_to_point(cx, p, w)) { return vec![a]; } if let Some(a) = release_guide_at(cx, p, ev.mods) { diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index b4d2d44aac..240ead0e93 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -105,6 +105,16 @@ pub(super) fn curve_point(p: &egui::Painter, c: Pos2, color: Color32, filled: bo p.circle(c, size / 2.0, if filled { color } else { Color32::WHITE }, Stroke::new(1.0, color)); } +/// A Live Corners widget at `c`: a white disc ringed in `color`, with a dot of `color` at its +/// center when its corner is `picked`. +fn corner_widget(p: &egui::Painter, c: Pos2, color: Color32, picked: bool) { + p.circle_filled(c, 3.0, Color32::WHITE); + p.circle_stroke(c, 3.0, Stroke::new(1.0, color)); + if picked { + p.circle_filled(c, 1.0, color); + } +} + /// How the current tool and preferences draw the selection's marks. pub(super) fn mark_options(app: &VectorcraftApp, curve_points_from_tool: bool) -> MarkOptions<'_> { let tool = app.session.tool_id(); @@ -173,6 +183,30 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: let options = mark_options(app, curve_points_from_tool); let grow = options.look.grow; let anchor = |direct: bool| grow + if direct { 5.0 } else { 4.0 }; + // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon while Show + // Shape Widgets is on, Direct Selection on any path). A picked corner's widget has a dot in the + // layer color at its center. Direct Selection draws the other corners' widgets hollow, below the + // anchors and handles, which take a press there first. + let shape_widgets = app.ui.view.shape_widgets; + let (picked_widgets, hollow_widgets): (Vec<_>, Vec<_>) = if matches!(tool, "selection" | "directSelection") || (shape_tool && !drawing) { + vectorcraft_tools::corners::CornerWidgets::showing( + &st.doc, + &st.selection, + xf.zoom, + tool == "directSelection", + app.ui.view.corner_widgets && (tool == "directSelection" || shape_widgets), + app.session.prefs.hide_corner_widget_above, + ) + .map(|w| w.visible_on().collect::>()) + .unwrap_or_default() + .into_iter() + .partition(|&(_, _, picked)| picked) + } else { + (vec![], vec![]) + }; + for (id, q, _) in hollow_widgets { + corner_widget(p, xf.to_screen(q), c32(st.doc.layer_color(id)), false); + } // The temporary halftone selects its dots; their marks obscure the art (#6369). if show_marks { // Too many paths to outline: the selection's bounds stand for them. @@ -216,25 +250,10 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: anchor_square(p, xf.to_screen(a.p), color, false, anchor(direct)); } } - // Live Corners widgets (Selection and the shape tools on a live rectangle or polygon while Show - // Shape Widgets is on, Direct Selection on any path). - let shape_widgets = app.ui.view.shape_widgets; - if (matches!(tool, "selection" | "directSelection") || (shape_tool && !drawing)) - && let Some(w) = vectorcraft_tools::corners::CornerWidgets::showing( - &st.doc, - &st.selection, - xf.zoom, - tool == "directSelection", - app.ui.view.corner_widgets && (tool == "directSelection" || shape_widgets), - app.session.prefs.hide_corner_widget_above, - ) - { - for (id, q) in w.visible_on() { - let (sp, color) = (xf.to_screen(q), c32(st.doc.layer_color(id))); - p.circle_filled(sp, 3.0, Color32::WHITE); - p.circle_stroke(sp, 3.0, Stroke::new(1.0, color)); - p.circle_filled(sp, 1.0, color); - } + // Live Corners widgets whose corners are picked, above the anchors and handles (the hollow + // ones are drawn below them). + for (id, q, _) in picked_widgets { + corner_widget(p, xf.to_screen(q), c32(st.doc.layer_color(id)), true); } // Bounding box with handles (Selection tool). // The layer color of the box's first object: with Real-time Drawing off, the shape being drawn diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index d5244aa234..4f4a5594b6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -6964,6 +6964,23 @@ fn a_star_shows_corner_widgets_with_direct_selection() { assert_eq!(widgets(&mut app), 0); } +/// #1232: with two of a star's corners picked, Direct Selection still draws all ten widgets; the +/// two picked ones have a dot in the layer color at their center and the others are hollow. +#[test] +fn direct_selection_draws_picked_corner_widgets_with_a_dot() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = app.session.execute("shape.star", &json!({"cx": 200, "cy": 150, "radius1": 80, "radius2": 40})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + let layer = c32(app.session.active().unwrap().doc.layer_color(vectorcraft_doc::NodeId(id))); + let ctx = egui::Context::default(); + app.select_tool("directSelection"); + let drawn = shapes(&mut app, &ctx); + let discs = drawn.iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == 3.0 && c.fill == Color32::WHITE)).count(); + let dots = drawn.iter().filter(|s| matches!(s, Shape::Circle(c) if c.radius == 1.0 && c.fill == layer)).count(); + assert_eq!((discs, dots), (10, 2)); +} + /// The type widget beside selected type's bounding box: hollow (white) on point type, filled /// in the layer colour on area type. #[test] diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index e5300fe5e4..ae435707b8 100644 --- a/crates/ui-egui/src/dialogs/corners.rs +++ b/crates/ui-egui/src/dialogs/corners.rs @@ -1,6 +1,7 @@ //! Corners: double-clicking a Live Corners widget (or `ui.corners`) sets the corner kind and -//! radius of a path's corners: those whose widgets show (the Direct-Selected ones, else every -//! corner). OK runs `object.setLiveShape` for them, one undo step. +//! radius of a path's corners: the picked ones (the Direct-Selected ones, else every corner), or +//! the double-clicked widget's corner alone when Direct Selection did not pick it. OK runs +//! `object.setLiveShape` for them, one undo step. //! //! Fields: `id`, `corners` (anchor indices of the path with its corners uncut: a rectangle's 0–3 //! from the top-left clockwise), `kind` ("round", "invertedRound" or "chamfer") and `radius` @@ -223,12 +224,12 @@ mod tests { #[test] fn double_clicking_a_direct_selected_corner_edits_it_alone() { let (mut app, id) = app(); - // Direct Selection picks the bottom-right anchor: only its widget shows. + // Direct Selection picks the bottom-right anchor: its widget alone is picked. app.run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "set"})).unwrap(); app.select_tool("directSelection"); let view = app.view_info(); let st = app.session.active().unwrap(); - let at: Vec<_> = CornerWidgets::of(&st.doc, &st.selection, view.zoom, true).unwrap().visible().collect(); + let at: Vec<_> = CornerWidgets::of(&st.doc, &st.selection, view.zoom, true).unwrap().visible_on().filter(|w| w.2).map(|w| w.1).collect(); assert_eq!(at.len(), 1); crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::DoubleClick, at[0].x, at[0].y), view); let d = app.ui.dialog.clone().expect("Corners opened"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index dafab93a58..1ba14a1817 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -659,7 +659,8 @@ changed points takes both changes. These rules for several points are VectorCraf points, one or several, are refused when those points changed since the dialog opened or another document is active. Corners: double-clicking a Live Corners widget with the Selection or Direct Selection tool, or `ui.corners {id?, -corners?}`, opens the `corners` dialog for a path's corners (the Direct-Selected ones, else every corner; fields `id`, +corners?}`, opens the `corners` dialog for a path's corners (the Direct-Selected ones, else every corner; a +double-click on a Direct Selection widget that is not picked opens it for that widget's corner alone; fields `id`, `corners`: anchor indices of the path with its corners uncut, a rectangle's 0–3 clockwise from the top-left, `kind`: round, invertedRound or chamfer, `radius` in points; `kind` or `radius` is absent while the corners differ). `ui.dialog.confirm` runs `object.setLiveShape` with them. diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..7eb5fb0a2d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7688,10 +7688,20 @@ draws no larger than takes the cut halfway along the corner's shorter side (half same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale, or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform (elliptical corners) gets circular ones in document units when its corners are next set. Dragging a corner widget -rounds the corners whose widgets show (every corner, or the Direct-Selected ones) on every selected path at once, +rounds the picked corners (every corner, or the Direct-Selected ones) on every selected path at once, outlining in red those that reach their limit; the Selection tool shows the widgets of live rectangles and polygons, -the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on the live rectangles among the targets -alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the +the Direct Selection tool those of any path. Direct Selection shows the widget of every corner, picked or not: a +picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked +picks its corner alone (`select.anchors` with mode `set`), and a click on a picked widget leaves the picks as they +are. A Shift-click adds or removes that corner, on any selected path, and keeps the other picks (`select.anchors` +with mode `toggle`, or `select.anchorsMany` with mode `toggle` on a path selected whole). While every corner of every +path with widgets is picked, a click or Shift-click picks that corner alone. A drag or Alt-click on a widget whose +corner is not picked edits that corner with the picked ones and does not pick it. A double-click on a +picked widget opens Corners for the picked corners of its path, and on a widget that is not picked, for its corner +alone; while every corner is picked, the double-click's first click has already picked the widget's corner alone. A +selected anchor's handle end, or an anchor as near to the pointer as the center of a widget that is not picked or nearer, takes +the press there. `rectanglesOnly: true` sets them on +the live rectangles among the targets alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: `items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`, dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..bdd5a891f5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -779,7 +779,8 @@ since 2026-10-01. - **Backquote/~ arrow pattern nudges (#7717):** Backquote plus an arrow moves selected pattern fills and strokes by Keyboard Increment; Shift keeps the tenfold step and existing constrain angle. This works with Selection, ordinary Direct Selection including partial anchors, and other idle tools. Object geometry, guides, anchor selection, shared patterns and unselected users stay fixed. Releasing Backquote restores ordinary nudging. Existing Alt-copy remains available, including copying selected solid-only art. Without Alt-copy, solid-only and guide-only pattern nudges are no-ops. Tool-owned arrows, active operations, typing, focused fields and user shortcuts retain precedence. Tests: `crates/ui-egui/tests/pattern_only_nudge.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`. -- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of a path is selected (the path selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. The other corners' widgets then hide; a Shift-click on another corner's anchor adds that corner and shows its widget, and a Shift-click on a showing widget deselects its corner. Adding a corner by Shift-clicking its widget while it is hidden stays open (#1232). Corner widgets are chosen by clicking one and Shift-clicking the others ([Logos By Nick, rounded corners in Illustrator](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. +- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of a path is selected (the path selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. +- **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks, a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). @@ -1479,7 +1480,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, an Alt-click on a path selected whole adds its group, and each further Alt-click adds the next group up, as Group Selection's clicks do; the climb stops below the layer and its sublayers and at the isolated object. An Alt-drag still copies the selection, and Alt+Shift-click on a segment or the fill still adds or removes the path. Public references: [Select objects](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copies). With Alt held at the press, a Direct Selection marquee is Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), not the anchors inside it, and the Group Selection pointer stays until the release (#4890; test `an_alt_marquee_selects_the_paths_it_touches_whole`). With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). + - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). Every corner's widget shows while some corners are picked, hollow when its corner is not picked, and a click on a picked widget keeps the picks (#1232). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..6001b3e47c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -267,7 +267,7 @@ tools, never checked side by side) isn't captured row by row. | Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | | Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | -| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908), and adding widgets to the selection by Shift-click (#1232) is missing; the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | +| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908); with some corners picked, every corner's widget shows, a click on one that is not picked picks its corner alone, a click on a picked one keeps the picks, and a Shift-click adds or removes a corner across paths (#1232); the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | From 894fc64b8e09102564c03d376e650a2423bc6992 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 01:15:23 -0800 Subject: [PATCH 012/104] Live Corners: a path with hidden widgets keeps its picks The check for every corner being picked now counts every selected path with corners, including one whose widgets are hidden because its sides are too short on screen. A click or Shift-click on another path's widget then keeps or toggles as usual instead of picking that corner alone and dropping the hidden path's picks. The docs now state the all-picked exception for a plain click and the multi-path case for a Shift-click. --- crates/tools/src/corners.rs | 27 ++++++++++++-------- crates/tools/src/corners/tests.rs | 41 +++++++++++++++++++++++++++++++ docs/mcp.md | 2 +- docs/target-app-parity.md | 6 ++--- docs/ui-parity.md | 2 +- 5 files changed, 63 insertions(+), 15 deletions(-) diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index a003391cce..40abf02e03 100644 --- a/crates/tools/src/corners.rs +++ b/crates/tools/src/corners.rs @@ -62,9 +62,10 @@ struct PathWidgets { } impl PathWidgets { - /// The widgets of path `id` at `zoom` (screen px per document point), if it has any: any path - /// with Direct Selection (`any_path`), every corner's, picked or not; live rectangles' and - /// polygons' with Selection, the picked corners' alone. `id` is editable + /// The widgets of path `id` at `zoom` (screen px per document point), if it has corners: any + /// path with Direct Selection (`any_path`), every corner's, picked or not; live rectangles' and + /// polygons' with Selection, the picked corners' alone. Corners whose sides are too short on + /// screen show no widget, so `widgets` can be empty. `id` is editable /// ([`Document::is_editable`]). fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool) -> Option { if selection.segments.contains_key(&id) { @@ -97,7 +98,7 @@ impl PathWidgets { Widget { corner: *c, radius, drawn, kind: lc.kind(c.index), angle: angle_in(lc.xf, c), at, picked: picked.contains(&c.index) } }) .collect(); - (!widgets.is_empty()).then_some(Self { id, xf: lc.xf, widgets, total: lc.corners.len(), whole }) + Some(Self { id, xf: lc.xf, widgets, total: lc.corners.len(), whole }) } /// The corners whose widgets show: anchor indices of the path's uncut outline. @@ -126,6 +127,9 @@ impl PathWidgets { #[derive(Clone, Debug, PartialEq)] pub struct CornerWidgets { paths: Vec, + /// Every corner of every selected path with corners is selected, those whose widgets are + /// hidden included. + every: bool, } impl CornerWidgets { @@ -133,9 +137,11 @@ impl CornerWidgets { /// path with Direct Selection (`any_path`), on live rectangles and polygons with Selection. pub fn of(doc: &Document, selection: &Selection, zoom: f64, any_path: bool) -> Option { let editable = doc.editable(); - let paths: Vec<_> = + let mut paths: Vec<_> = selection.objects.iter().filter(|id| editable(**id)).filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path)).collect(); - (!paths.is_empty()).then_some(Self { paths }) + let every = paths.iter().all(|p| p.whole); + paths.retain(|p| !p.widgets.is_empty()); + (!paths.is_empty()).then_some(Self { paths, every }) } /// Selection & Anchor Display → Hide Corner Widget for angles greater than: the widgets of @@ -367,12 +373,13 @@ impl CornerDrag { let path = widgets.paths.get(widget.0)?; let corner = path.widgets.get(widget.1)?.corner.index; let lc = cx.doc.node(path.id).and_then(LiveCorners::of)?; - // While every corner of every path with widgets is selected (the paths selected + // While every corner of every selected path is selected (the paths selected // whole), a Shift-click picks this corner alone, as the first click of "click one // widget, then Shift-click the others" does: toggling it would deselect it and - // leave the rest (#5188). Selected anchors that are no corner show every widget - // too, but select no corner: there a Shift-click adds the corner. - let every = widgets.paths.iter().all(|p| p.whole); + // leave the rest (#5188). A path whose widgets are all hidden counts too, so its + // picks are kept. Selected anchors that are no corner show every widget too, but + // select no corner: there a Shift-click adds the corner. + let every = widgets.every; // A plain click on a widget whose corner is selected keeps the picks, so the second // click of a double-click opens Corners for all of them. Anchors that are no corner // pick every widget but select no corner. diff --git a/crates/tools/src/corners/tests.rs b/crates/tools/src/corners/tests.rs index 182e9bb221..a397f00386 100644 --- a/crates/tools/src/corners/tests.rs +++ b/crates/tools/src/corners/tests.rs @@ -522,6 +522,47 @@ fn widgets_are_picked_across_paths() { assert_eq!(out, vec![Action::Exec("select.anchors".into(), json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"}))]); } +/// #1232: a selected path whose widgets are all hidden (its sides too short on screen) still counts +/// when deciding whether every corner is picked. With one corner of a small rectangle picked and a +/// larger one selected whole, a click on the larger one's widget keeps the picks and a Shift-click +/// deselects that corner, so the small rectangle's pick stays. +#[test] +fn a_path_with_hidden_widgets_keeps_its_picks() { + let (mut d, big) = live_rect(0.0, Affine::translate((100.0, 100.0))); + let live = LiveShape::Rectangle { + w: 20.0, + h: 20.0, + radii: [0.0; 4], + kinds: Default::default(), + radii_relative: false, + xf: Affine::translate((300.0, 100.0)), + }; + let small = d.alloc_id(); + let mut n = Node::path(small, live.to_path(), Appearance::default_art()); + if let NodeKind::Path { live: slot, .. } = &mut n.kind { + *slot = Some(Box::new(live)); + } + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + let mut s = selected(big); + s.add(small); + s.anchors.insert(small, [(0, 0)].into()); + let p = paint(); + let cx = cx(&d, &s, &p); + let w = CornerWidgets::for_tool(&cx, true).unwrap(); + assert_eq!(w.paths.len(), 1, "the small rectangle shows no widget"); + let press = |mods: Mods| { + let mut t = crate::create("directSelection"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 190.0, 110.0).with_mods(mods)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 190.0, 110.0).with_mods(mods)) + }; + assert!(press(Mods::default()).is_empty()); + assert_eq!( + press(Mods { shift: true, ..Mods::default() }), + vec![Action::Exec("select.anchorsMany".into(), json!({"items": [{"id": big.0, "anchors": [[0, 1]]}], "mode": "toggle"}))] + ); +} + /// #1232: a path whose picked corners are all hidden (wider than the angle preference) is left /// out of a drag that starts on another path; the drag edits only corners that are picked or /// pressed. diff --git a/docs/mcp.md b/docs/mcp.md index 7eb5fb0a2d..91dde25bd5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7695,7 +7695,7 @@ picked corner's widget has a dot at its center and the others are hollow. A clic picks its corner alone (`select.anchors` with mode `set`), and a click on a picked widget leaves the picks as they are. A Shift-click adds or removes that corner, on any selected path, and keeps the other picks (`select.anchors` with mode `toggle`, or `select.anchorsMany` with mode `toggle` on a path selected whole). While every corner of every -path with widgets is picked, a click or Shift-click picks that corner alone. A drag or Alt-click on a widget whose +selected path is picked, paths whose widgets are hidden included, a click or Shift-click picks that corner alone. A drag or Alt-click on a widget whose corner is not picked edits that corner with the picked ones and does not pick it. A double-click on a picked widget opens Corners for the picked corners of its path, and on a widget that is not picked, for its corner alone; while every corner is picked, the double-click's first click has already picked the widget's corner alone. A diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bdd5a891f5..bf5da22577 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -779,8 +779,8 @@ since 2026-10-01. - **Backquote/~ arrow pattern nudges (#7717):** Backquote plus an arrow moves selected pattern fills and strokes by Keyboard Increment; Shift keeps the tenfold step and existing constrain angle. This works with Selection, ordinary Direct Selection including partial anchors, and other idle tools. Object geometry, guides, anchor selection, shared patterns and unselected users stay fixed. Releasing Backquote restores ordinary nudging. Existing Alt-copy remains available, including copying selected solid-only art. Without Alt-copy, solid-only and guide-only pattern nudges are no-ops. Tool-owned arrows, active operations, typing, focused fields and user shortcuts retain precedence. Tests: `crates/ui-egui/tests/pattern_only_nudge.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`. -- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of a path is selected (the path selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. -- **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks, a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`. +- **Shift-click on corner widgets (#5188):** with Direct Selection, when every corner of every selected path is selected (the paths selected whole), a Shift-click on a corner widget picks that corner alone, so the next drag rounds just it. When another selected path has only some corners picked, a Shift-click on a widget of a path selected whole deselects that corner and keeps the other picks. The other corners' widgets then show as not picked; a Shift-click on another corner's anchor or widget adds that corner, and a Shift-click on a picked widget deselects its corner. Corner widgets are chosen by clicking one and Shift-clicking the others ([a tutorial on rounded corners](https://logosbynick.com/?p=15787)). Test: `corners::tests::a_shift_click_on_a_widget_of_a_whole_path_picks_its_corner`. +- **Picking corner widgets (#1232):** with Direct Selection, every corner's widget shows while some corners are picked: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked picks its corner alone, a Shift-click adds or removes a corner across selected paths, and a double-click on a picked widget opens Corners for the picked corners of its path ([Live Corners help page, archived](https://web.archive.org/web/2019/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, a plain click on a picked widget keeps the picks (while every corner of every selected path is picked, it picks that corner alone, and a double-click then opens Corners for that corner), a drag or Alt-click on a widget that is not picked edits its corner together with the picked ones, and over a widget that is not picked, a selected anchor's handle end or a nearer anchor takes the press. Tests: `corners::tests::a_press_on_a_widget_not_picked_edits_it_with_the_picked_corners`, `corners::tests::widgets_are_picked_across_paths`, `corners::tests::a_handle_end_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_nearer_anchor_over_a_widget_not_picked_takes_the_press`, `corners::tests::a_shift_click_toggles_a_rounded_corner_whole`, `corners::tests::a_path_with_hidden_widgets_keeps_its_picks`, `tests::corner_widgets_pick_corners_across_paths_through_the_session`. - **TIFF in screen and asset export:** both format menus expose the existing TIFF encoder and Format Settings. Headless UI regressions choose TIFF and check scaled dimensions, artboard selection, filenames, encoding options, saved settings and collected-asset output. Public reference: [Export for Screens](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-for-screens.html), updated 2026-09-28, lists TIFF for both artboards and assets. Adobe staff [confirmed support in 30.2.1](https://illustrator.uservoice.com/forums/333657-illustrator-desktop-feature-requests/suggestions/49081034-add-tiff-format-into-export-for-screens-assets-d) on 2026-02-19; the older 2025 Collect assets guide omits TIFF. - **Lossy WebP with a Quality setting:** WebP Options has a Compression menu (Lossless, Lossy) and a Quality slider from 0 to 100 that is enabled for Lossy. Lossy writes a `VP8 ` WebP file, with an `ALPH` chunk that keeps the alpha exactly when some pixels are not opaque. `document.export`, `document.serialize` and Export for Screens take `lossless: false` with `quality` (default 90, VectorCraft's own value), in a format row or in `settings.webp`; Format Settings for WebP keeps both. Lossless stays the default, and a quality above 100 or one that is not a whole number is refused. Public reference: [export file format options](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/export-file-format-options-in-illustrator.html) describes Lossless and Lossy WebP and a Quality setting for Lossy (`webp_is_lossless_by_default_and_lossy_when_asked`, `lossy_webp_keeps_translucent_pixels`, `webp_quality_out_of_its_range_is_refused` in `crates/engine/src/cmd/fileio/tests_text.rs`, `webp_options_choose_lossless_or_lossy_at_a_quality`). - **Export for Screens of the selected artboards:** while the Artboard tool is in use, File › Export › Export for Screens… (`file.exportForScreens`) opens with the artboards the tool has selected checked on its Artboards tab, and Export Artboard writes only those. Shift-clicks on the canvas, or Shift- or Ctrl/Cmd-clicks on the Artboards panel's rows, select several. The other fields show the settings the document last exported with. With another tool in use, the dialog takes its artboard choice from those settings too. Public reference: [Export selected artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/export-artboards.html). @@ -1480,7 +1480,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, an Alt-click on a path selected whole adds its group, and each further Alt-click adds the next group up, as Group Selection's clicks do; the climb stops below the layer and its sublayers and at the isolated object. An Alt-drag still copies the selection, and Alt+Shift-click on a segment or the fill still adds or removes the path. Public references: [Select objects](https://web.archive.org/web/20250904012025/https://helpx.adobe.com/illustrator/using/selecting-objects.html) and [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (archived copies). With Alt held at the press, a Direct Selection marquee is Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), not the anchors inside it, and the Group Selection pointer stays until the release (#4890; test `an_alt_marquee_selects_the_paths_it_touches_whole`). With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). Every corner's widget shows while some corners are picked, hollow when its corner is not picked, and a click on a picked widget keeps the picks (#1232). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). + - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). Every corner's widget shows while some corners are picked, hollow when its corner is not picked, and a click on a picked widget keeps the picks unless every corner of every selected path is picked, when it picks that corner alone (#1232). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6001b3e47c..62b43edbe9 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -267,7 +267,7 @@ tools, never checked side by side) isn't captured row by row. | Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | | Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | -| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908); with some corners picked, every corner's widget shows, a click on one that is not picked picks its corner alone, a click on a picked one keeps the picks, and a Shift-click adds or removes a corner across paths (#1232); the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | +| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner of every selected path selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908); with some corners picked, every corner's widget shows, a click on one that is not picked picks its corner alone, a click on a picked one keeps the picks, and a Shift-click adds or removes a corner across paths (#1232); the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | From c2e61ac55e6eb4f6152a90c14930d7885d422e7a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:50:09 -0800 Subject: [PATCH 013/104] Swatches: a swatch replaced during a drag is not duplicated or deleted on drop New Swatch and Delete Swatch took the dragged rows by name. When a dragged swatch was deleted and a new one was made under its name before the drop, the drop duplicated or deleted the new swatch, which was never dragged. The panel now records each dragged swatch or color group when the drag starts and, until the drop, checks it against the states the document's undo steps keep and against the current state. A row that one of them does not hold unchanged is left out of the drop, also when the new row has the same name and paint. A row that stays unchanged is duplicated or deleted as before. --- crates/ui-egui/src/panels/swatches/actions.rs | 106 ++++++++++++++++-- crates/ui-egui/src/panels/swatches/body.rs | 4 +- crates/ui-egui/src/panels/swatches/tests.rs | 42 ++++++- 3 files changed, 138 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index dc26c78550..7ba6fda3dd 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -1,8 +1,13 @@ +use std::sync::{Arc, Weak}; + +use vectorcraft_color::SwatchGroup; +use vectorcraft_engine::DocState; + use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; use super::{ - Kind, LibraryKind, PanelDrag, Response, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, - widgets, + Document, Kind, LibraryKind, PanelDrag, Response, Swatch, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, + set_pstate, widgets, }; /// The selected swatches and groups that can be deleted: every color group in the document and @@ -117,9 +122,81 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { /// The panel state key of the document (`uid`) the swatches being dragged from the list belong to. pub(super) const DRAG_DOC: &str = "swatch-drag-doc"; +/// The panel state key of the rows being dragged from the list ([`HeldRows`]). +const DRAG_ROWS: &str = "swatch-drag-rows"; + +/// A row dragged from the list as it was when the drag started: its swatch or its color group. +#[derive(Clone, PartialEq)] +enum HeldRow { + Swatch(Swatch), + Group(SwatchGroup), +} + +impl HeldRow { + /// Row `name` of `d`: its swatch, else the color group of that name. + fn of(d: &Document, name: &str) -> Option { + match d.swatch(name) { + Some(w) => Some(HeldRow::Swatch(w.clone())), + None => d.swatch_groups.iter().find(|g| g.name == name).cloned().map(HeldRow::Group), + } + } + /// Whether `d` holds this row unchanged. + fn unchanged_in(&self, d: &Document) -> bool { + match self { + HeldRow::Swatch(w) => d.swatch(&w.name) == Some(w), + HeldRow::Group(g) => d.swatch_groups.iter().any(|x| x == g), + } + } +} + +/// The rows being dragged from the list, in the order of the drag's names, and the document they +/// were last checked against. A row is `None` once a state of the document since the drag started +/// did not hold it unchanged: deleted, edited, or deleted and made again under its name, also with +/// the same paint. +#[derive(Clone, Default)] +struct HeldRows { + doc: Weak, + rows: Vec<(String, Option)>, +} + +/// Records the document and the rows a drag from the list started with this frame, so that New +/// Swatch and Delete Swatch act only on rows that stay unchanged until it is dropped. +pub(super) fn drag_started(app: &VectorcraftApp, ctx: &egui::Context) { + let st = app.session.active(); + set_pstate(ctx, DRAG_DOC, st.map(|st| st.uid)); + let held = match (st, egui::DragAndDrop::payload::(ctx).as_deref()) { + (Some(st), Some(PanelDrag::Paint { rows: Some(r), .. })) => { + HeldRows { doc: Arc::downgrade(&st.doc), rows: r.names.iter().map(|n| (n.clone(), HeldRow::of(&st.doc, n))).collect() } + } + _ => HeldRows::default(), + }; + set_pstate(ctx, DRAG_ROWS, held); +} + +/// The dragged rows ([`HeldRows`]) checked against every state document `st` passed through since +/// they were last checked: the states its undo steps kept since then, and the current one. When +/// the last checked state is not among them (an undo, or steps dropped past the history's limits), +/// only the current state is checked. +fn held_rows(st: &DocState, ctx: &egui::Context) -> HeldRows { + let mut held: HeldRows = pstate(ctx, DRAG_ROWS); + if std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc)) { + return held; + } + let since = st.history.undo.iter().rposition(|e| std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&e.doc))); + let between = since.and_then(|i| st.history.undo.get(i + 1..)).unwrap_or_default(); + for (_, row) in &mut held.rows { + if row.as_ref().is_some_and(|r| !(between.iter().all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc))) { + *row = None; + } + } + held.doc = Arc::downgrade(&st.doc); + set_pstate(ctx, DRAG_ROWS, held.clone()); + held +} + /// The swatches and color groups of the active document being dragged from the list that Delete -/// Swatch can delete: neither None nor Registration, and still in the document. Empty for any other -/// drag, and for a drag started in another document. +/// Swatch can delete: neither None nor Registration, and still in the document unchanged. Empty for +/// any other drag, and for a drag started in another document. fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { let Some(st) = app.session.active() else { return vec![] }; let d = &st.doc; @@ -127,16 +204,25 @@ fn dragged_deletable(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { } /// The names of the swatches or color groups of the active document being dragged from the list, -/// in panel order. Empty for any other drag, and for a drag started in another document. +/// in panel order, that the document has held unchanged since the drag started ([`held_rows`]). +/// Empty for any other drag, and for a drag started in another document. fn dragged_rows(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { let Some(st) = app.session.active() else { return vec![] }; if pstate::>(ctx, DRAG_DOC) != Some(st.uid) { return vec![]; } - match egui::DragAndDrop::payload::(ctx).as_deref() { - Some(PanelDrag::Paint { rows: Some(r), .. }) => r.names.clone(), - _ => vec![], + let drag = egui::DragAndDrop::payload::(ctx); + let Some(PanelDrag::Paint { rows: Some(r), .. }) = drag.as_deref() else { return vec![] }; + let held = held_rows(st, ctx); + if held.rows.len() != r.names.len() { + return vec![]; } + r.names + .iter() + .zip(&held.rows) + .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc))) + .map(|(n, _)| n.clone()) + .collect() } /// Swatches or color groups (`names`) dragged onto Delete Swatch (`button`): the button is @@ -157,8 +243,8 @@ fn drop_on_delete(app: &mut VectorcraftApp, ui: &Ui, button: &Response, names: V } /// The swatches of the active document being dragged from the list that New Swatch can duplicate, -/// in panel order: the dragged rows ([`dragged_rows`]) that are swatches still in the document, -/// other than None and Registration. +/// in panel order: the dragged rows ([`dragged_rows`]) that are swatches still in the document +/// unchanged, other than None and Registration. fn dragged_swatches(app: &VectorcraftApp, ctx: &egui::Context) -> Vec { let Some(st) = app.session.active() else { return vec![] }; dragged_rows(app, ctx).into_iter().filter(|n| st.doc.swatch(n).is_some_and(|w| !w.is_reserved())).collect() diff --git a/crates/ui-egui/src/panels/swatches/body.rs b/crates/ui-egui/src/panels/swatches/body.rs index 944a245b9e..4ec269d5dd 100644 --- a/crates/ui-egui/src/panels/swatches/body.rs +++ b/crates/ui-egui/src/panels/swatches/body.rs @@ -1,4 +1,4 @@ -use super::actions::{DRAG_DOC, bottom, edit_group}; +use super::actions::{bottom, drag_started, edit_group}; use super::dnd::{TileEvents, apply_drop, click_selection, highlighted, selection, tile_input, zone_input}; use super::tiles::{ draw_folder, draw_registration, folder_tile, global_mark, list_icons, list_row, list_row_name, pattern_thumb, tile_grid, tile_id, @@ -133,7 +133,7 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut Ui, salt: &'static str) { None => {} } if ev.started { - set_pstate(ui.ctx(), DRAG_DOC, app.session.active().map(|st| st.uid)); + drag_started(app, ui.ctx()); } if let Some(drop) = ev.drop { apply_drop(app, drop); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index a3e7120c7a..58e767817c 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -788,7 +788,8 @@ fn swatches_dropped_on_delete_swatch_are_deleted_after_asking() { /// Delete Swatch takes only swatches dragged from the active document's list: a paint dragged from /// elsewhere, art, and a swatch dragged from another document whose name the active document also /// has delete nothing, ask nothing and are not outlined. A secondary button released while a swatch -/// is held over the button ends the drag without asking. +/// is held over the button ends the drag without asking, and a swatch deleted while it is dragged +/// leaves alone a new swatch made under its name. #[test] fn delete_swatch_ignores_other_drags() { let mut app = app(); @@ -848,6 +849,23 @@ fn delete_swatch_ignores_other_drags() { assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some() && undo_steps(&app) == undo_new, "the other document keeps Orange"); assert!(app.session.set_active(0)); unchanged(&app, "the first document"); + // A swatch deleted while it is dragged, and a new swatch made under its name before the drop. + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 5.0); + let from = tile_center(&ctx, "Orange"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 5.1); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 5.2); + assert!(egui::DragAndDrop::payload::(&ctx).is_some(), "Orange is dragged"); + let orange = app.session.doc().unwrap().doc.swatch("Orange").cloned(); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert_eq!(replaced.swatch("Orange").cloned(), orange, "the new swatch is the same as the one deleted"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 5.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 5.4); + assert!(!outlined(&held, trash), "the new swatch of that name is not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 5.5); + assert_eq!(dialog_message(&app), None, "the new swatch of that name asks nothing"); + assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (replaced, undo_replaced), "the new swatch of that name is kept"); } /// Swatches dragged from the list onto New Swatch are duplicated without a dialog, in thumbnail @@ -920,7 +938,8 @@ fn swatches_dropped_on_new_swatch_are_duplicated() { /// New Swatch duplicates only swatches dragged from the active document's list that are still in /// it: a paint dragged from elsewhere, art, a swatch dragged from another document, and a swatch -/// deleted while it is dragged duplicate nothing. A secondary button released while a swatch is +/// deleted while it is dragged duplicate nothing, nor does a new swatch made under the name of a +/// swatch deleted while it is dragged. A secondary button released while a swatch is /// held over the button ends the drag without duplicating, and a click still opens New Swatch. #[test] fn new_swatch_ignores_other_drags() { @@ -977,6 +996,25 @@ fn new_swatch_ignores_other_drags() { frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 4.5); assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (gone, undo_gone), "a deleted swatch is not duplicated"); app.run("edit.undo", json!({})).unwrap(); + // A swatch deleted while it is dragged, and a new swatch made under its name before the drop. + hold_orange(&mut app, 4.6); + let orange = app.session.doc().unwrap().doc.swatch("Orange").cloned(); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert_eq!(replaced.swatch("Orange").cloned(), orange, "the new swatch is the same as the one deleted"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 4.85); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 4.9); + assert!(!outlined(&held, new), "the new swatch of that name is not outlined"); + frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 4.95); + assert!(app.ui.dialog.is_none(), "the new swatch of that name opens no dialog"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (replaced, undo_replaced), + "the new swatch of that name is not duplicated" + ); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); // A swatch dragged from this document while another document with the same swatches becomes // active. hold_orange(&mut app, 5.0); From b5f7b1ded7d5c6b5b81dfb3e971838402f62377c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:55:37 -0800 Subject: [PATCH 014/104] Live Corners: state the all-picked click case in the UI table The Live Corners row now says that while every corner of every selected path is picked, a click on a picked widget picks that corner alone, as docs/target-app-parity.md and docs/mcp.md already say. --- docs/ui-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 62b43edbe9..4930e58ac3 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -267,7 +267,7 @@ tools, never checked side by side) isn't captured row by row. | Alt with Direct Selection makes a marquee Group Selection's for the drag: it selects every path it touches, whole (Shift toggles them), and the Group Selection pointer stays until the release | done | #4890 | | Direct Selection: a click on a selected object's centre point (Attributes › Show Center) selects the object whole, and a drag from it moves the object in one undo step | done | #4891 | | Escape cancels a Direct Selection drag | done | #1803 (#1743) | -| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner of every selected path selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908); with some corners picked, every corner's widget shows, a click on one that is not picked picks its corner alone, a click on a picked one keeps the picks, and a Shift-click adds or removes a corner across paths (#1232); the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | +| Live Corners widgets (radius readout, Alt-click cycles kind, double-click the Corners dialog) | done | a Direct Selection click on a widget selects its corner (#1239), and with every corner of every selected path selected a Shift-click on a widget picks that corner alone instead of deselecting it (#5188); a press-and-drag on a widget of a path selected whole still rounds every corner (#908); with some corners picked, every corner's widget shows, a click on one that is not picked picks its corner alone, a click on a picked one keeps the picks (while every corner of every selected path is picked, it picks that corner alone), and a Shift-click adds or removes a corner across paths (#1232); the bounding box hides while a widget is dragged with the Selection tool (#1229); a round corner next to a curved side curves smoothly instead of sticking out of the shape (#1512); a corner rounds until its cut reaches its neighbours' cuts, so one corner of a square alone reaches the whole side (#2332) | | Corners between curved sides (#1144), Relative rounding | done | #1144 closed; Relative rounding in the Corners dialog (Relative / Absolute, radius as a percentage of each corner's maximum, kept as the shape is resized; `object.setLiveShape` `relativeRadii`, #3091, `tests_livecorners::relative_corner_rounding_keeps_fraction_on_resize`) | | Pie widgets on a live ellipse: drag one to set Pie Start or End Angle, double-click one to make the ellipse whole | done | Selection tool, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets | | Side widget on a live polygon: drag it to set the number of sides from 3 to 11 | done | Selection tool and the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, with the bounding box showing, while the Control bar's Hide Shape Widgets has not hidden the widgets; a drag down adds sides and a drag up removes them; Escape cancels ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html)) | From ff6c3d8356647315d23066206239d241c4ecc132 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:07:26 -0800 Subject: [PATCH 015/104] Live Corners: a drag rounds only the picked corners whose widgets show --- docs/mcp.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 366b4dcd44..41580c9ac0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7707,7 +7707,7 @@ draws no larger than takes the cut halfway along the corner's shorter side (half same limit for its four corners), the corners stay circular through uneven scales (the radius scales by the mean scale, or keeps its size with Scale Corners off), and a rectangle from a file that kept an uneven scale in its transform (elliptical corners) gets circular ones in document units when its corners are next set. Dragging a corner widget -rounds the picked corners (every corner, or the Direct-Selected ones) on every selected path at once, +rounds the picked corners (every corner, or the Direct-Selected ones) whose widgets show, on every selected path at once, outlining in red those that reach their limit; the Selection tool shows the widgets of live rectangles and polygons, the Direct Selection tool those of any path. Direct Selection shows the widget of every corner, picked or not: a picked corner's widget has a dot at its center and the others are hollow. A click on a widget that is not picked From 45f6c20380d68b8b159970d106660c34c1f4624f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:14:52 -0800 Subject: [PATCH 016/104] Color Wheel: a contrast fix also passes with its values rounded to 8 bits color.contrast's fix search now accepts a candidate only when it meets the level both as measured and with the color, the background, the art below each group or layer, the opacities, and the pixel and alpha each level gives rounded to 8 bits per channel. The renderer rounds the paint's color and alpha that way, so a fix that meets 4.5:1 only before rounding (a gray of about 118.7/255 on white, which paints as #777777 at 4.48:1) is no longer offered. The reported ratio and its pass results are unchanged. The per-level drawing of the backdrop moves into Pass::draw, which both the measured ratio and the 8-bit check use. --- crates/engine/src/cmd/colorcmds.rs | 84 +++++++++++++++++------- crates/engine/src/tests/colorcontrast.rs | 56 ++++++++++++++-- docs/mcp.md | 2 + 3 files changed, 113 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index b938c40d0b..c9338e510d 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1016,28 +1016,50 @@ pub struct Backdrop { } /// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color -/// and its alpha), and for a level that blends without isolating, the alpha of what it holds drawn -/// alone. +/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of +/// the art below it inside the level around it, while a blending level lies further out. #[derive(Clone, Debug, PartialEq)] struct Pass { blend: BlendMode, opacity: f32, backdrop: ([f32; 3], f32), - alone: Option, + blends: bool, + isolate: bool, + inner: f32, } +/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next +/// level out holds drawn alone. +type Through = ([f32; 3], f32, f32); + impl Pass { - /// What the level draws for `x` (a color and its alpha, drawn over the art below it): a level - /// that blends takes that art back out by the alpha of what it holds drawn alone. - fn source(&self, x: ([f32; 3], f32)) -> ([f32; 3], f32) { - match self.alone { - None => x, - Some(alone) if alone <= 0.0 => (x.0, 0.0), - Some(alone) => { - let b = self.backdrop; - (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone) - } + /// What the level draws for color and alpha `x`, drawn over the art below it: a level that + /// blends takes that art back out by `alone`, the alpha of what it holds drawn alone. + fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) { + if !self.blends { + return x; } + if alone <= 0.0 { + return (x.0, 0.0); + } + let b = self.backdrop; + (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone) + } + + /// `d` drawn through the level. The level's opacity applies to what it holds, a level that + /// isolates its blending carries out the alpha of what it holds composited on its own, and the + /// art beside it in the level around it adds to the alpha once. + fn draw(&self, (color, alpha, alone): Through) -> Through { + let source = self.source((color, alpha), alone); + let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0); + let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop); + (color, alpha, drawn + self.inner * (1.0 - drawn)) + } + + /// The level with its opacity, the art below it and its alphas passed through `q`. + fn with(&self, q: impl Fn(f32) -> f32) -> Pass { + let (color, alpha) = self.backdrop; + Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() } } } @@ -1053,8 +1075,8 @@ impl Backdrop { /// Display sRGB `shown`, drawn as the measured color is drawn, over the background. pub fn front(&self, shown: [f32; 3]) -> [f32; 3] { - let x = self.passes.iter().fold((shown, 1.0f32), |x, p| composite(p.blend, p.source(x), p.opacity, p.backdrop)); - if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, self.against) } + let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d)); + if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) } } /// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against @@ -1063,6 +1085,20 @@ impl Backdrop { wcag::contrast_ratio(self.front(shown), self.against) } + /// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art + /// below each level, the background, the opacities, and the color and alpha each level gives. + fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 { + let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0; + let painted = |c: [f32; 3]| c.map(eight); + let against = painted(self.against); + let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| { + let (color, alpha, alone) = p.with(eight).draw(d); + (painted(color), eight(alpha), eight(alone)) + }); + let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) }; + wcag::contrast_ratio(painted(front), against) + } + /// The background as `#rrggbb` in working RGB, the form a color param takes. pub fn against_hex(&self) -> String { let [r, g, b] = self.written; @@ -1101,11 +1137,16 @@ fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) /// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum` /// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain -/// included). None when `color` already meets it, or when no lightness of its hue does. +/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8 +/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by +/// [`Backdrop::ratio`], or when no lightness of its hue does. fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64, rich_black: bool) -> Option { let cms = vectorcraft_color::cms::active(); let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c)); - let ratio = |srgb: [f32; 3]| backdrop.ratio(drawn(&in_model_of(&cms, srgb, color))); + let ratio = |srgb: [f32; 3]| { + let shown = drawn(&in_model_of(&cms, srgb, color)); + backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown)) + }; if backdrop.ratio(drawn(color)) >= minimum { return None; } @@ -1249,13 +1290,8 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1, _ => 0.0, }; - let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, alone: blends(step).then_some(alone) }; - let source = pass.source(([0.0; 3], alpha)).1; - // A level that isolates its blending carries out the alpha of what it holds composited on - // its own. - let drawn = if step.isolate { alpha } else { alone } * step.opacity.clamp(0.0, 1.0); - alpha = composite(step.blend, ([0.0; 3], source), step.opacity, backdrop).1; - alone = drawn + inner * (1.0 - drawn); + let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner }; + (_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone)); passes.push(pass); } let stain = if given { None } else { stain_of(s) }; diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 09210d9e6e..e3489bf047 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -758,7 +758,7 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() { let fix = fix_color(&r["fix"]["aa"]); let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated(); let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]); - assert!((4.5..4.51).contains(&got), "{fix:?} draws {drawn:?}: {got}"); + assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}"); } #[test] @@ -877,7 +877,7 @@ fn a_failing_color_answers_the_closest_passing_color_of_its_hue() { assert_eq!(r["for"], "normalText"); let aa = fix_color(&r["fix"]["aa"]); let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap(); - assert!((4.5..4.51).contains(&ratio(&back)), "{back}"); + assert!((4.5..4.57).contains(&ratio(&back)), "{back}"); let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap()); assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa)); assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}"); @@ -885,7 +885,53 @@ fn a_failing_color_answers_the_closest_passing_color_of_its_hue() { assert!(r["fix"]["aaa"].is_null(), "{r}"); let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap(); let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap(); - assert!((4.5..4.51).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}"); + assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}"); +} + +/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too: +/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again, +/// and the fix has to paint as #767676 (4.54:1) or darker. +#[test] +fn a_fix_passes_as_the_canvas_paints_it() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap(); + let fix = fix_color(&r["fix"]["aa"]); + let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0); + let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]); + assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}"); + let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap(); + assert!((4.5..4.57).contains(&ratio(&back)), "{back}"); +} + +/// A translucent fix also meets the minimum with the color, the opacity, the background and the +/// composited pixel rounded to 8 bits per channel. +#[test] +fn a_translucent_fix_passes_at_eight_bits() { + let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0; + let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| { + let (a, b) = (eight(opacity), eight(against)); + let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a))); + vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3]) + }; + let mut s = Session::new(); + // A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at + // 232 / 255 its pixel is #747474 (4.49:1). + let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap(); + let fix = fix_color(&r["fix"]["aa"]); + assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}"); + // #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is + // 4.4965:1. + let bg = 137.51 / 255.0; + let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0}); + let r = s.execute("color.contrast", &p).unwrap(); + let fix = fix_color(&r["fix"]["aa"]); + assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}"); + // Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray + // at that opacity gets a fix. + let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"}); + let r = s.execute("color.contrast", &p).unwrap(); + assert_eq!(r["graphics"]["aa"], false, "{r}"); + assert!(r["fix"]["aa"].is_null(), "{r}"); } #[test] @@ -898,7 +944,7 @@ fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() { let fix = g["fix"].as_object().unwrap(); assert_eq!(fix.keys().collect::>(), ["aa"], "{g}"); let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap(); - assert!((3.0..3.01).contains(&ratio(&back)), "{back}"); + assert!((3.0..3.04).contains(&ratio(&back)), "{back}"); let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap(); assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}"); assert!(!large["fix"]["aaa"].is_null(), "{large}"); @@ -925,7 +971,7 @@ fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() { assert_eq!(r["largeText"]["aa"], false, "{r}"); assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}"); let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap(); - assert!((3.0..3.01).contains(&ratio(&back)), "{back}"); + assert!((3.0..3.04).contains(&ratio(&back)), "{back}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4adc4d2382..94655f6cd7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1228,6 +1228,8 @@ rows below it: there `"below"` reads the art below each such level, and a given Headless MCP answers it too. The answer also has `for` (the category `for` names: `normalText`, the default, `largeText` or `graphics`) and `fix: {aa, aaa}` (no `aaa` for graphics): for each level of that category, the closest color that meets it when drawn the same way, in the model of the measured color, as the Color Wheel stores a pick. The +closest color also meets the level with the color, the background, the art below each group or layer it is drawn +through, and the opacities rounded to 8 bits per channel. The search keeps the color's [OKLCH](https://bottosson.github.io/posts/oklab/) hue, raises or lowers its lightness, whichever takes the smaller step, and lowers its chroma where sRGB cannot show it. A level is `null` when the color already meets it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no color meets 7:1 there). From a46d022ed8c8ee7189ec64b5224899867a8eb75e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:17:42 -0800 Subject: [PATCH 017/104] Color Wheel: contrast lines are found coarsely while a drag changes the field A hue ring or strip drag changes the field on every frame, and a CMYK target separates every sample, so finding the full lines each frame slowed the drag. While a drag changes the field, the lines are found on an 8 by 8 grid without the narrow-band search, and the full lines are found once the drag ends. A drag that keeps the field keeps the full lines. --- crates/ui-egui/src/panels/color_wheel.rs | 40 +++++++++++-------- .../tests_color_wheel_contrast_lines.rs | 19 +++++++++ 2 files changed, 43 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 54934c58e6..87481f1861 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -792,13 +792,16 @@ const BACKDROP: &str = "color-wheel-backdrop"; pub(super) const LINES: &str = "color-wheel-lines"; /// What the contrast lines depend on: what the color is measured against, the category, the field /// (the view, the channel and the component the field holds fixed) with the model a pick there -/// stores, and the color settings. -pub(super) type LinesKey = (Backdrop, Category, String, Under); +/// stores, the color settings, and whether they were found coarsely during a drag. +pub(super) type LinesKey = (Backdrop, Category, String, Under, bool); /// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates. pub(super) type Lines = Vec>>; /// The columns and rows at which [`contrast_lines`] samples a field. const LINE_SAMPLES: usize = 32; +/// The columns and rows at which [`contrast_lines`] samples a field, without the narrow-band +/// search, while a drag changes the field (the hue ring, the box's strip). +const COARSE_LINE_SAMPLES: usize = 8; /// The halvings that place a line on the edge between two samples. const LINE_STEPS: usize = 10; @@ -810,14 +813,15 @@ type FieldPoint = (f32, f32); type Bands = Vec<(f32, FieldPoint, FieldPoint)>; /// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in -/// field coordinates. The field is sampled on a 33 × 33 grid, and each cell whose corners fall on -/// both sides gets a segment between the crossings on its edges, placed by bisection (marching -/// squares; a cell with two opposite corners passing is split by its center). Around a failing -/// sample higher than its neighbors in a column or a row, the highest ratio is looked for, so a -/// passing band narrower than the samples gets its two edges too, joined from column to column or -/// from row to row. Segments that share an end are joined into one polyline. -pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64]) -> Lines { - let n = LINE_SAMPLES; +/// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell +/// whose corners fall on both sides gets a segment between the crossings on its edges, placed by +/// bisection (marching squares; a cell with two opposite corners passing is split by its center). +/// With `bands`, around a failing sample higher than its neighbors in a column or a row, the highest +/// ratio is looked for, so a passing band narrower than the samples gets its two edges too, joined +/// from column to column or from row to row. Segments that share an end are joined into one +/// polyline. +pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64], n: usize, narrow: bool) -> Lines { + let n = n.max(1); let at = |i: usize| i as f32 / n as f32; // `grid[i][j]` is column i (x) and row j (y). let grid: Vec> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect(); @@ -869,7 +873,7 @@ pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64 } } // Bands narrower than the samples, along each column and then each row. - for across in [false, true] { + for across in [false, true].into_iter().filter(|_| narrow) { let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) }; let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) }; let bands: Vec = (0..=n) @@ -949,7 +953,9 @@ fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec> { /// The contrast lines of the wheel's square or the box's field on HSB `hsb`, kept per [`LinesKey`]: /// where a pick there, stored as the wheel stores it in place of `tgt`'s color, meets each minimum -/// of the chosen category against `backdrop`. +/// of the chosen category against `backdrop`. While a drag is live and the field differs from the +/// one the kept lines were found for, the lines are found coarsely ([`COARSE_LINE_SAMPLES`]), and +/// in full once the drag ends. fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, hsb: [f32; 3], cmyk_doc: bool) -> Lines { let set = &app.ui.color_wheel; let (category, view, ch) = (set.contrast_for, set.view, set.channel); @@ -957,9 +963,10 @@ fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, h // The component the field holds fixed: the box's strip value, or the wheel's hue. let fixed = if view == View::Box { box_pos(ch, hsb).0 } else { hsb[0] }; let field = format!("{view:?} {ch:?} {fixed} {:?} {cmyk_doc}", was.map(|c| c.model())); - let key: LinesKey = (backdrop.clone(), category, field, under()); + let dragging = app.session.in_interaction(); + let key = |coarse: bool| -> LinesKey { (backdrop.clone(), category, field.clone(), under(), coarse) }; if let Some((k, lines)) = pstate::>(ui.ctx(), LINES) - && k == key + && (k == key(false) || (dragging && k == key(true))) { return lines; } @@ -968,8 +975,9 @@ fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, h let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc)))); let (aa, aaa) = category.minimums(); let minimums: Vec = std::iter::once(aa).chain(aaa).collect(); - let lines = contrast_lines(&ratio_at, &minimums); - set_pstate(ui.ctx(), LINES, Some((key, lines.clone()))); + let samples = if dragging { COARSE_LINE_SAMPLES } else { LINE_SAMPLES }; + let lines = contrast_lines(&ratio_at, &minimums, samples, !dragging); + set_pstate(ui.ctx(), LINES, Some((key(dragging), lines.clone()))); lines } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs index 1418dc5fd2..d8501b6351 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -165,3 +165,22 @@ fn the_panel_keeps_its_height_when_the_chip_goes() { // #FDC96E fails AA and shows the chip; #FFFFFF passes both levels and hides it. assert_eq!(height("#fdc96e"), height("#ffffff")); } + +/// A drag that changes the field on every frame (here the box's hue) finds the lines coarsely, and +/// in full again once it ends; a drag that leaves the field as it is keeps the full lines. +#[test] +fn a_drag_that_changes_the_field_finds_its_lines_coarsely_until_it_ends() { + let mut h = harness(app("box", "hue")); + let coarse = |h: &Harness<'static, VectorcraftApp>| pstate::>(&h.ctx, LINES).expect("lines were found").0.4; + assert!(!coarse(&h)); + h.state_mut().session.begin_interaction("test").unwrap(); + h.run_steps(2); + assert!(!coarse(&h), "the field is unchanged, so the full lines are kept"); + h.state_mut().run("paint.setFill", json!({"color": "#6efdc9"})).unwrap(); + assert!(h.state().session.in_interaction(), "the new color is part of the drag"); + h.run_steps(2); + assert!(coarse(&h), "another hue during the drag"); + h.state_mut().session.commit_interaction().unwrap(); + h.run_steps(2); + assert!(!coarse(&h), "found in full once the drag ends"); +} From c33376b013653f1dd55b7008c05132739ef7d7fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:17:42 -0800 Subject: [PATCH 018/104] Color Wheel: contrast lines follow the Appearance of Black setting The box's and the wheel's contrast lines measured each field color with the plain display conversion, while color.contrast shows 100 % K alone as black when Appearance of Black is rich. The lines now use the same conversion through Backdrop::shown, and the backdrop the lines are kept against carries the setting, so the lines are found again after the setting changes. --- crates/engine/src/cmd/colorcmds.rs | 24 +++++++++++++++--------- crates/engine/src/tests/colorcontrast.rs | 16 ++++++++++++++++ crates/ui-egui/src/panels/color_wheel.rs | 2 +- 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index c9338e510d..6f8b70bc44 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1013,6 +1013,8 @@ pub struct Backdrop { passes: Vec, /// The color and amount a fill stains the picked object of a dynamic symbol instance with. stain: Option<(Color, f32)>, + /// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black). + rich_black: bool, } /// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color @@ -1073,6 +1075,12 @@ impl Backdrop { } } + /// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through + /// `cms` and the Appearance of Black the backdrop was read with. + pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] { + shown_rgb(cms, self.rich_black, &self.drawn_color(c)) + } + /// Display sRGB `shown`, drawn as the measured color is drawn, over the background. pub fn front(&self, shown: [f32; 3]) -> [f32; 3] { let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d)); @@ -1140,17 +1148,16 @@ fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) /// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8 /// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by /// [`Backdrop::ratio`], or when no lightness of its hue does. -fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64, rich_black: bool) -> Option { +fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option { let cms = vectorcraft_color::cms::active(); - let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c)); let ratio = |srgb: [f32; 3]| { - let shown = drawn(&in_model_of(&cms, srgb, color)); + let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color)); backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown)) }; - if backdrop.ratio(drawn(color)) >= minimum { + if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum { return None; } - let fix = wcag::closest_passing(shown_rgb(&cms, rich_black, color), minimum, &ratio)?; + let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?; Some(in_model_of(&cms, fix, color)) } @@ -1170,8 +1177,7 @@ pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { } }; let (color, backdrop) = contrast_backdrop(s, p)?; - let rich_black = s.prefs.black_on_screen == "rich"; - let ratio = backdrop.ratio(shown_rgb(&vectorcraft_color::cms::active(), rich_black, &backdrop.drawn_color(&color))); + let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color)); let levels = |c: Category| { let (aa, aaa) = c.passes(ratio); match aaa { @@ -1179,7 +1185,7 @@ pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { None => json!({ "aa": aa }), } }; - let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum, rich_black) { + let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) { Some(c) => serde_json::to_value(c).unwrap_or(Value::Null), None => Value::Null, }; @@ -1295,7 +1301,7 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { passes.push(pass); } let stain = if given { None } else { stain_of(s) }; - Ok((color, Backdrop { against, written, passes, stain })) + Ok((color, Backdrop { against, written, passes, stain, rich_black })) } /// An object around the proxy's object: one in the document, or a group of the picked object's diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index e3489bf047..6b43325d74 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -903,6 +903,22 @@ fn a_fix_passes_as_the_canvas_paints_it() { assert!((4.5..4.57).contains(&ratio(&back)), "{back}"); } +/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black, +/// so the Color Wheel's contrast lines use the same color. +#[test] +fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() { + let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0); + let cms = vectorcraft_color::cms::active(); + let mut s = Session::new(); + let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"}); + let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap(); + assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]); + s.prefs.black_on_screen = "rich".into(); + let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap(); + assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]); + assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}"); +} + /// A translucent fix also meets the minimum with the color, the opacity, the background and the /// composited pixel rounded to 8 bits per channel. #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 87481f1861..c7627e68a5 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -972,7 +972,7 @@ fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, h } let cms = cms::active(); let at = |x: f32, y: f32| if view == View::Box { box_pick(ch, fixed, x, y, hsb) } else { [hsb[0], x, 1.0 - y] }; - let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc)))); + let ratio_at = |x: f32, y: f32| backdrop.ratio(backdrop.shown(&cms, &stored(&cms, at(x, y), was.as_ref(), cmyk_doc))); let (aa, aaa) = category.minimums(); let minimums: Vec = std::iter::once(aa).chain(aaa).collect(); let samples = if dragging { COARSE_LINE_SAMPLES } else { LINE_SAMPLES }; From 767c0798a931fec86a8418e0432db70b1b2a32ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:57:36 -0800 Subject: [PATCH 019/104] Color Wheel: a contrast fix keeps the largest chroma sRGB shows at its lightness The fix search lowered an out-of-gamut chroma by bisection, which stops at the first gamut boundary. Near blue the chromas sRGB holds at one lightness come in two stretches, so a blue that needed a little more contrast lost much of its chroma (blue on #B8B8B8 got a fix of chroma 0.25 against blue's 0.31). The search now uses oklab::from_oklch, which takes the largest chroma below the asked one that fits. --- crates/color/src/wcag.rs | 42 +++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index d63e07c952..16b34bb166 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -96,26 +96,6 @@ const LIGHTNESS_STEPS: usize = 32; /// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples, /// which leave it within 1e-7 of the step. const PEAK_STEPS: usize = 32; -/// The halvings [`closest_passing`] makes of the chroma when sRGB cannot show it. -const CHROMA_STEPS: usize = 24; - -/// The display sRGB of OKLCH lightness `l`, chroma `c` and the hue whose sine and cosine are `sc`, -/// with the chroma lowered until the color fits in sRGB. -fn oklch_in_gamut(l: f64, c: f64, (sin, cos): (f64, f64)) -> [f32; 3] { - let at = |c: f64| crate::libraries::oklab_to_srgb(l, c * cos, c * sin); - let fits = |rgb: &[f64; 3]| rgb.iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(v)); - let mut rgb = at(c); - if !fits(&rgb) { - let (mut lo, mut hi) = (0.0, c); - for _ in 0..CHROMA_STEPS { - let mid = (lo + hi) / 2.0; - if fits(&at(mid)) { lo = mid } else { hi = mid } - } - rgb = at(lo); - } - rgb.map(|v| v.clamp(0.0, 1.0) as f32) -} - /// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a /// single peak between them. `f` is called 34 times. pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { @@ -138,7 +118,8 @@ pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { /// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue /// () with the lightness raised or lowered, whichever -/// takes the smaller step, and the chroma lowered where sRGB cannot show it. Each side is tested at +/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma +/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at /// 16 even steps up to white or black, and the step before the first that passes is narrowed down. /// When no step passes, the highest ratio between the neighbors of the highest step is looked for, /// so a color that passes only in a narrow band between white and black (as under a Difference @@ -150,11 +131,10 @@ pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> if passes(srgb) { return Some(srgb); } - let [l, a, b] = crate::libraries::srgb_to_oklab(srgb); - let (c, sc) = (a.hypot(b), b.atan2(a).sin_cos()); + let [l, c, h] = crate::oklab::to_oklch(srgb); let mut best: Option<(f64, [f32; 3])> = None; for end in [1.0, 0.0] { - let at = |t: f64| oklch_in_gamut(l + (end - l) * t, c, sc); + let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0; let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64; let ratios: Vec = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect(); // `lo` fails and `hi` passes, the step before the first sample that passes. @@ -280,6 +260,20 @@ mod tests { assert!((3.0..3.01).contains(&r), "{fix:?}: {r}"); } + /// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a + /// blue that needs a little more contrast keeps nearly all of its chroma. + #[test] + fn a_blue_that_darkens_a_little_keeps_its_chroma() { + let gray = hex("b8b8b8"); + let ratio = |c: [f32; 3]| contrast_ratio(c, gray); + let blue = [0.0, 0.0, 1.0]; + assert!(ratio(blue) < 4.5, "{}", ratio(blue)); + let fix = closest_passing(blue, 4.5, &ratio).unwrap(); + let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue)); + assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}"); + assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}"); + } + #[test] fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() { let white = [1.0; 3]; From 86f148989527a4773e8a8cf55ae44bdbc3330ad4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:57:36 -0800 Subject: [PATCH 020/104] Color Wheel: the contrast row's chips show the focus outline of the color fields The fix chip drew no focus indicator, and the background chip recolored its own border. Both now draw the outline a focused color field draws around itself (widgets::focus_outline). --- crates/ui-egui/src/panels/color_wheel.rs | 5 ++--- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/color.rs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c7627e68a5..3181a5a903 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -1106,9 +1106,7 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option widgets::swatch_tile(ui, rect, &Paint::solid(c), false, false), None => widgets::swatch_tile(ui, rect, &Paint::None, false, false), } - if chip_resp.has_focus() { - ui.painter().rect_stroke(rect, 0.0, ui.visuals().selection.stroke, StrokeKind::Inside); - } + widgets::focus_outline(ui, &chip_resp, rect); let enabled = ui.is_enabled(); let value = chip.map(|c| hex(bytes(cms::active().display_rgb(&c)))); chip_resp.widget_info(|| egui::WidgetInfo { @@ -1163,6 +1161,7 @@ fn fix_chip(ui: &mut Ui, answer: Option<&Value>, aa: bool, aaa: Option) -> }; let (rect, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::click()); widgets::swatch_tile(ui, rect, &Paint::solid(color), false, false); + widgets::focus_outline(ui, &resp, rect); let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &label)); let resp = resp.on_hover_text(&label); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b67df13c7f..38b1beca0f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -42,7 +42,7 @@ pub use color::{ color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, ring_markers, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, }; -pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, focus_outline, hex_text, pointer_phase}; #[cfg(test)] pub(crate) use color::{SHADE, shade_cells, shade_edges}; pub use drag::{ diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 8f5ec8b2d9..4bd2846018 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -383,7 +383,7 @@ fn arrow_steps(ui: &Ui, id: egui::Id, horizontal: bool, vertical: bool) -> (f32, } /// The focus outline of a focused color control. -fn focus_outline(ui: &Ui, resp: &Response, rect: Rect) { +pub(crate) fn focus_outline(ui: &Ui, resp: &Response, rect: Rect) { if ui.memory(|m| m.has_focus(resp.id)) { let t = Tokens::get(ui.ctx()); ui.painter().rect_stroke(rect.expand(2.0), 0.0, Stroke::new(1.0, t.accent), StrokeKind::Outside); From 6be0bafa7299fb75667bcb86fee8260d80d906ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:28:18 -0800 Subject: [PATCH 021/104] Color Wheel: color.contrast's params text describes the 8-bit check on a fix The params text now says what docs/mcp.md says: a fix also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel. docs/mcp.md names the rounded color and alpha of each level too. --- crates/engine/src/cmd/colorcmds.rs | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 6f8b70bc44..f3f250dba1 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it; null when the color already meets the level, or when no lightness of its hue does}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel; null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), diff --git a/docs/mcp.md b/docs/mcp.md index 94655f6cd7..8246023baa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1229,7 +1229,7 @@ Headless MCP answers it too. The answer also has `for` (the category `for` names `largeText` or `graphics`) and `fix: {aa, aaa}` (no `aaa` for graphics): for each level of that category, the closest color that meets it when drawn the same way, in the model of the measured color, as the Color Wheel stores a pick. The closest color also meets the level with the color, the background, the art below each group or layer it is drawn -through, and the opacities rounded to 8 bits per channel. The +through, the opacities, and the color and alpha each level gives rounded to 8 bits per channel. The search keeps the color's [OKLCH](https://bottosson.github.io/posts/oklab/) hue, raises or lowers its lightness, whichever takes the smaller step, and lowers its chroma where sRGB cannot show it. A level is `null` when the color already meets it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no color meets 7:1 there). From 463bdbcac709d7f3517014428ede3631c177cea9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:21:45 -0800 Subject: [PATCH 022/104] Color Wheel: the contrast fix test checks that the fix is the closest gray The test of the #777777 fix now also checks that the gray one 8-bit step lighter than the fix fails AA, so a search that lands on a darker gray fails it. The doc comment of `contrast_lines` names its `narrow` parameter, and `docs/mcp.md` says that Enter applies the focused fix chip, as a click does. --- crates/engine/src/tests/colorcontrast.rs | 3 +++ crates/ui-egui/src/panels/color_wheel.rs | 2 +- docs/mcp.md | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 6b43325d74..8a8c203488 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -899,6 +899,9 @@ fn a_fix_passes_as_the_canvas_paints_it() { let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0); let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]); assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}"); + // The fix is the closest one: the gray one 8-bit step lighter fails. + let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0)); + assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}"); let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap(); assert!((4.5..4.57).contains(&ratio(&back)), "{back}"); } diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 3181a5a903..ee1469a833 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -816,7 +816,7 @@ type Bands = Vec<(f32, FieldPoint, FieldPoint)>; /// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell /// whose corners fall on both sides gets a segment between the crossings on its edges, placed by /// bisection (marching squares; a cell with two opposite corners passing is split by its center). -/// With `bands`, around a failing sample higher than its neighbors in a column or a row, the highest +/// With `narrow`, around a failing sample higher than its neighbors in a column or a row, the highest /// ratio is looked for, so a passing band narrower than the samples gets its two edges too, joined /// from column to column or from row to row. Segments that share an end are joined into one /// polyline. diff --git a/docs/mcp.md b/docs/mcp.md index 8246023baa..b884e3e6b7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -698,7 +698,7 @@ box, `contrastFor` (`normalText`, `largeText` or `graphics`, which has AA only) `contrastBackground` (a color, or `null` for the color behind the selection) pins the background it measures against, as `color.contrast` below answers it. With the row shown, the wheel's square and the box's field draw lines where the color picked there meets AA (solid) and AAA (dashed) for the category, and when the color fails a level, a chip at the -end of the row shows `color.contrast`'s `fix` for the first level it fails; a click applies it. +end of the row shows `color.contrast`'s `fix` for the first level it fails; a click, or Enter while the chip has the focus, applies it. `{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel or the box. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences. From 3ef896191383d4201f17da9b9925f4b237aa1d48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:34:22 -0800 Subject: [PATCH 023/104] Scripts: app.doScript plays an action of the Actions panel A script can play an action by name with app.doScript(action, set, dialogs?), the DoScript method of the scripting reference. script.run takes a new `actions` param, and the app fills it with the Actions panel's actions and their included steps; a recorded command.batch step gives its own steps. - The action and its set are matched by their exact names. A name that matches no action or more than one, an action with no included step, a stop, and a step a script may not run or the engine does not have (a View menu step, or one that plays an action or runs a script) throw before any step runs, so an action cannot play itself. - Each step runs as vc.run runs a command: it joins the run's one undo step for each changed document, counts as a host call, and reads and writes files only where the script may. A failed step is put back and its error gives the step's place, the action and the command. - A step that acts on the active artboard (paste in place, in front and in back, Align, Distribute Objects and Distribute Spacing to the artboard, All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and names no artboard gets the active document's active artboard, as the Actions panel's playback gives it. The index is the one the artboard had as the run started, clamped to the last artboard after a step deletes artboards. While the Artboard tool has several artboards selected, a paste step gets none and Fit to Artwork Bounds gets those artboards. - dialogs must be true or false (default false). app.loadAction and app.unloadAction throw an error that says they are not available yet. - `actions` is checked before the script starts: at most 4,096 actions, 10,000 steps an action, 100,000 in all and 16 MiB. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/script/actions.rs | 304 +++++++++++++++++++++ crates/engine/src/script/dom.rs | 5 +- crates/engine/src/script/mod.rs | 10 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_actions.rs | 319 ++++++++++++++++++++++ crates/engine/src/tests/script_folder.rs | 1 + crates/ui-egui/src/app/commands.rs | 2 + crates/ui-egui/src/panels/actions.rs | 117 ++++++++ docs/mcp.md | 21 ++ docs/target-app-parity.md | 1 + 12 files changed, 783 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/script/actions.rs create mode 100644 crates/engine/src/tests/script_actions.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..e838b53ebc 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -848,7 +848,7 @@ pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..9bc8c427ca 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -171,6 +171,7 @@ fn run(s: &mut Session, p: &Value) -> Result { if s.script_frames && !answers.is_empty() { return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog")); } + let actions = script::actions::parse(p.get("actions")).map_err(param)?; let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; let mut checked_real = None; @@ -217,6 +218,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, + actions, }; let name = s.script_start(request)?; if s.script_frames { diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs new file mode 100644 index 0000000000..16c072cebd --- /dev/null +++ b/crates/engine/src/script/actions.rs @@ -0,0 +1,304 @@ +//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's +//! run, as the VBScript reference's `DoScript` method of the Application object describes it +//! (). +//! +//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps +//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app +//! they are the Actions panel's. +//! +//! VectorCraft's own rules, which the reference does not state: +//! - The action and its set are matched by their exact names; a name that matches no action, or +//! more than one, throws before any step runs. +//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins +//! the run's transaction and its one undo step for each changed document, it is counted as a host +//! call, it reads and writes files only where the script may, and a step that fails is put back +//! and throws an error that names the step and the action, while the steps before it stay done. +//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine +//! does not have (a View menu step, or one that plays an action), and a stop throw before any step +//! runs. An action cannot play another action, so it cannot play itself. +//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it +//! changes nothing. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Host, Link, command, current, refused_to_scripts}; + +/// The most actions a run's request may carry. +pub const MAX_ACTIONS: usize = 4096; +/// The most steps one action may have, after a `command.batch` step gives its own steps. +pub const MAX_ACTION_STEPS: usize = 10_000; +/// The most steps the actions of one request may have in all. +pub const MAX_ALL_STEPS: usize = 100_000; +/// The most bytes of the request's actions, as JSON. +pub const MAX_ACTIONS_BYTES: usize = 16 << 20; +/// The longest name of an action or a set, in bytes. +pub const MAX_NAME_BYTES: usize = 1024; +/// The longest command id of a step, in bytes. +const MAX_ID_BYTES: usize = 256; +/// The command id of a stop, which waits for the person in the Actions panel. +pub const STOP_STEP: &str = "action.stop"; + +/// An action a run can play: its set's name, its name and the steps playback runs. +#[derive(Clone, Debug)] +pub struct Playable { + set: String, + name: String, + steps: Vec, +} + +/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a +/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and +/// their size as JSON. +#[derive(Clone, Debug)] +struct Step { + place: String, + id: String, + params: Value, + bytes: u64, +} + +/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the +/// step's place in the action (1 for the first; default its place in the list), within the limits +/// above. A `command.batch` step gives its own steps, each at the batch's place and its own. +pub fn parse(v: Option<&Value>) -> Result, String> { + let Some(v) = v else { return Ok(Vec::new()) }; + let Value::Array(list) = v else { return Err("`actions` must be a list".into()) }; + if list.len() > MAX_ACTIONS { + return Err(format!("`actions` holds more than {MAX_ACTIONS} actions")); + } + if let Some(place) = super::too_deep(v) { + return Err(format!("`actions{place}` is nested more than 64 levels deep")); + } + if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) { + return Err("`actions` is larger than 16 MiB".into()); + } + let mut all = 0usize; + let mut out = Vec::with_capacity(list.len()); + for (i, a) in list.iter().enumerate() { + let at = format!("`actions[{i}]`"); + let Value::Object(a) = a else { return Err(format!("{at} must be an object")) }; + only_keys(a, &["set", "name", "steps"], &at)?; + let set = name_of(a, "set", &at)?; + let name = name_of(a, "name", &at)?; + let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) }; + let mut steps = Vec::new(); + for (j, s) in given.iter().enumerate() { + let at = format!("{at}.steps[{j}]"); + let Value::Object(s) = s else { return Err(format!("{at} must be an object")) }; + only_keys(s, &["command", "params", "step"], &at)?; + let place = match s.get("step") { + None => (j + 1).to_string(), + Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) { + Some(n) => n.to_string(), + None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")), + }, + }; + let (id, params) = command_of(s, &at)?; + match params.get("commands") { + Some(Value::Array(inner)) if id == "command.batch" => { + for (k, c) in inner.iter().enumerate() { + let at = format!("{at}.params.commands[{k}]"); + let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; + let (id, params) = command_of(c, &at)?; + if id == "command.batch" { + return Err(format!("{at} is a command.batch inside a command.batch")); + } + steps.push(step(format!("{place}.{}", k + 1), id, params)); + } + } + _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), + _ => steps.push(step(place, id, params)), + } + if steps.len() > MAX_ACTION_STEPS { + return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); + } + } + all += steps.len(); + if all > MAX_ALL_STEPS { + return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all")); + } + out.push(Playable { set, name, steps }); + } + Ok(out) +} + +impl Playable { + /// The steps the action runs. + pub fn len(&self) -> usize { + self.steps.len() + } + + /// Whether the action runs no step. + pub fn is_empty(&self) -> bool { + self.steps.is_empty() + } +} + +fn only_keys(o: &Map, keys: &[&str], at: &str) -> Result<(), String> { + match o.keys().find(|k| !keys.contains(&k.as_str())) { + Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))), + None => Ok(()), + } +} + +fn name_of(o: &Map, key: &str, at: &str) -> Result { + match o.get(key) { + Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()), + Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")), + _ => Err(format!("{at}.{key} must be a string")), + } +} + +/// A step's `command` and `params` (default `{}`). +fn command_of(o: &Map, at: &str) -> Result<(String, Value), String> { + let id = match o.get("command") { + Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(), + _ => return Err(format!("{at}.command must be a command id")), + }; + let params = match o.get("params") { + None => json!({}), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(format!("{at}.params must be an object")), + }; + Ok((id, params)) +} + +fn step(place: String, id: String, params: Value) -> Step { + let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); + Step { place, id, params, bytes } +} + +/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters +/// as U+FFFD. +fn shown(text: &str) -> String { + const MAX: usize = 80; + let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect(); + if text.chars().nth(MAX).is_some() { + out.push('…'); + } + out +} + +/// The members of `app` this module adds. +pub(super) fn app_members(link: &Link) -> Vec<(String, HostMember)> { + let l = link.clone(); + let play = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + do_script(&h, &a) + }); + let mut members = vec![("doScript".to_string(), HostMember::Method(play))]; + members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name))); + members +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// `app.doScript(action, set, dialogs?)`, its arguments after `this`. +fn do_script(h: &Host, a: &[Data]) -> std::result::Result { + if a.len() > 4 { + return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into())); + } + let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else { + return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into())); + }; + if action.is_empty() || set.is_empty() { + return Err(HostError::Error("doScript needs the action's name and its set's name".into())); + } + if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES { + return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes"))); + } + if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) { + return Err(HostError::Type("doScript's dialogs must be true or false".into())); + } + let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); + let p = match found.as_slice() { + [p] => *p, + [] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), + [] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))), + _ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))), + }; + if p.steps.is_empty() { + return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); + } + // Every step is checked before the first runs, so a step that cannot run leaves the documents as + // they were. + for s in &p.steps { + let refused = s.id == STOP_STEP || refused_to_scripts(&s.id) || crate::find_command(&s.id).is_none(); + if refused { + let (place, name, id) = (&s.place, shown(&p.name), shown(&s.id)); + return Err(HostError::Error(if s.id == STOP_STEP { + format!("step {place} of “{name}” is a stop, which a script cannot wait at") + } else { + format!("step {place} of “{name}” runs `{id}`, which a script cannot run") + })); + } + } + for s in &p.steps { + // A run asked to stop runs no further step; the realm ends it at its next instruction and + // puts the documents back. + if h.session.borrow().script_stop.is_set() { + break; + } + h.charge_call(16 + s.id.len() as u64 + s.bytes)?; + // Saved steps run as they run in the Actions panel: keys their commands no longer read are + // passed over. + let params = on_active_artboard(&h.session.borrow(), &h.active_artboards, &s.id, &s.params); + let outer = h.session.borrow_mut().set_replaying(true); + let r = command(h, &s.id, ¶ms); + h.session.borrow_mut().set_replaying(outer); + if let Err(e) = r { + let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id)); + return Err(match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)), + other => other, + }); + } + } + Ok(Data::Undefined) +} + +/// `params` of step `id`, with the active artboard of the active document added as a +/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for +/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to +/// Selected Art. The active artboard is the index `start` gives for the document (its index as the +/// run started, which the view keeps), past the last artboard the last one, as the view shows it +/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While +/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its +/// `indices` instead, and a paste step gets none (it pastes on them). A paste step in a document +/// without artboards, or one that names `artboards`, and a Fit to Artwork Bounds step that names +/// `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: &str, params: &Value) -> Value { + let mut params = params.clone(); + let Some(st) = s.active() else { return params }; + let n = st.doc.artboards.len(); + let active = match start.iter().find(|(uid, _)| *uid == st.uid) { + Some((_, i)) => (*i).min(n.saturating_sub(1)), + None => super::dom::active_artboard(st), + }; + let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); + let fit_art = id == "artboard.fitToArt"; + let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) { + "artboard" + } else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) { + "index" + } else { + return params; + }; + let Some(p) = params.as_object_mut() else { return params }; + if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) { + return params; + } + let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; + if picks.is_empty() { + p.insert(key.into(), json!(active)); + } else if fit_art { + p.insert("indices".into(), json!(picks)); + } + params +} diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..7d66e3cbc2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -152,7 +152,7 @@ fn method(link: &Link, f: Member) -> HostMember { /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document or page item `this` is still there. -fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { +pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -397,7 +397,7 @@ struct Frame { } /// The index of the active artboard of `st`, as the view keeps it. -fn active_artboard(st: &DocState) -> usize { +pub(super) fn active_artboard(st: &DocState) -> usize { let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) } @@ -1721,6 +1721,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(super::actions::app_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..770934ce98 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -48,6 +48,7 @@ //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +pub mod actions; pub mod console; pub mod dialogs; pub mod dollar; @@ -202,6 +203,8 @@ pub(crate) struct Request { pub locale: String, /// The answers to the dialogs of a run with nobody to ask, in order. pub answers: Vec, + /// The actions `app.doScript` can play. + pub actions: Vec, } thread_local! { @@ -802,6 +805,11 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// The actions `app.doScript` can play. + actions: Vec, + /// The index of each open document's active artboard as the run starts, by document uid. The + /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. + active_artboards: Vec<(u64, usize)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -2065,6 +2073,8 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::default(), + actions: request.actions, + active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..db1b95966b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -169,6 +169,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_actions; mod script_console; mod script_dialogs; mod script_dollar; diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs new file mode 100644 index 0000000000..02ee9f5957 --- /dev/null +++ b/crates/engine/src/tests/script_actions.rs @@ -0,0 +1,319 @@ +//! `app.doScript`: a script plays an action of `script.run`'s `actions`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})) +} + +fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec { + let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The error message a `try` around `call` logs, or `"ok"`. +fn caught(s: &mut Session, call: &str, actions: &Value) -> String { + let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}"); + log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string() +} + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn objects(s: &Session) -> usize { + s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn undo_labels(s: &Session) -> Vec { + s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn rect(x: i64) -> Value { + json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}}) +} + +/// One set, `Set`, with the actions given as (name, steps). +fn set(actions: &[(&str, Vec)]) -> Value { + Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect()) +} + +#[test] +fn do_script_plays_every_step_as_one_undo_step_with_the_script() { + let mut s = doc(); + let before = undo_labels(&s); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions); + assert_eq!(out, vec![Value::Null], "doScript returns undefined"); + assert_eq!(objects(&s), 3); + let after = undo_labels(&s); + assert_eq!(after.len(), before.len() + 1, "{after:?}"); + assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL)); + // The steps of a recorded `command.batch` run one by one, each counted as a host call. + let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]); + let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap(); + assert_eq!(objects(&s), 6); + let r0 = run_with(&mut s, "1;", &batch).unwrap(); + assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}"); +} + +#[test] +fn a_later_throw_puts_back_what_the_action_did() { + let mut s = doc(); + let before = (objects(&s), undo_labels(&s)); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string(); + assert!(e.contains("late"), "{e}"); + assert_eq!((objects(&s), undo_labels(&s)), before); +} + +#[test] +fn a_failed_step_is_put_back_and_the_steps_before_it_stay() { + let mut s = doc(); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]); + let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions); + assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}"); + assert_eq!(objects(&s), 1, "the first step stays done and the third never runs"); +} + +#[test] +fn names_are_matched_exactly_and_must_be_one_action() { + let mut s = doc(); + let actions = json!([ + {"set": "Set", "name": "One", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Empty", "steps": []}, + ]); + assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”"); + assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”"); + assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”"); + assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps"); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”"); + assert_eq!(objects(&s), 0); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok"); + assert_eq!(objects(&s), 1); + assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet"); + assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet"); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let mut s = doc(); + let actions = set(&[("One", vec![rect(0)])]); + for (call, want) in [ + ("app.doScript()", "TypeError"), + ("app.doScript(1, 'Set')", "TypeError"), + ("app.doScript('One', {})", "TypeError"), + ("app.doScript('One', 'Set', 'yes')", "TypeError"), + ("app.doScript('One', 'Set', 1)", "TypeError"), + ("app.doScript('One', 'Set', false, 4)", "TypeError"), + ("app.doScript('', 'Set')", "Error"), + ("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"), + ] { + let m = caught(&mut s, call, &actions); + assert!(m.starts_with(&format!("{want}:")), "{call}: {m}"); + } + assert_eq!(objects(&s), 0); +} + +#[test] +fn steps_a_script_may_not_run_stop_the_action_before_any_step() { + let mut s = doc(); + s.prefs.show_external_script_warning = true; + let steps = [ + (json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"), + (json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"), + (json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"), + (json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"), + (json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"), + (json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"), + ]; + for (bad, want) in steps { + let actions = set(&[("Loop", vec![rect(0), bad.clone()])]); + let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions); + assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}"); + assert_eq!(objects(&s), 0, "{bad}: no step ran"); + } + assert!(s.prefs.show_external_script_warning); + // A refused command inside a recorded batch is refused too. + let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]); + let m = caught(&mut s, "app.doScript('B', 'Set')", &batch); + assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}"); + assert_eq!(objects(&s), 0); +} + +#[test] +fn an_action_step_keeps_the_scripts_file_gate() { + let mut s = doc(); + let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}}); + let actions = set(&[("Export", vec![export])]); + let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions); + assert!(m.contains("Script file access denied"), "{m}"); + assert!(!path.exists()); +} + +#[test] +fn a_long_action_is_held_to_the_host_call_limit() { + let mut s = doc(); + // Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the + // steps of one call cannot pass the limit. + let calls = |s: &mut Session, steps: usize| { + let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]); + run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap() + }; + let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001)); + assert!(many >= one + 2000, "{one} {many}"); +} + +#[test] +fn bad_action_lists_are_refused_before_the_script_runs() { + let mut s = doc(); + let step = || json!({"command": "select.none"}); + let cases = [ + (json!({}), "`actions` must be a list"), + (json!([1]), "`actions[0]` must be an object"), + (json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"), + (json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"), + (json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"), + (json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"), + ( + json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]), + "a command.batch inside a command.batch", + ), + (json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"), + (Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"), + (json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"), + ]; + for (actions, want) in cases { + let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string(); + assert!(e.contains(want), "{want}: {e}"); + } + let many: Vec = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect(); + let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string(); + assert!(e.contains("more than 100000 steps in all"), "{e}"); + assert_eq!(objects(&s), 0, "no run started"); +} + +#[test] +fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() { + let mut s = doc(); + let first = set(&[("One", vec![rect(0)])]); + log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first); + assert_eq!(objects(&s), 0); + // The next run has no actions: the function kept from the first run finds none. + let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }"; + assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]); + let two = set(&[("One", vec![rect(0), rect(30)])]); + assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]); + assert_eq!(objects(&s), 2); +} + +/// Makes artboard `index` of the active document the view's active one, as the app does before each +/// command. +fn make_active(s: &mut Session, index: usize) { + let id = s.active().unwrap().doc.artboards[index].id; + s.doc_mut().unwrap().active_artboard = Some(id); +} + +/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected +/// Art, acts on the active artboard's index as the run started; after the script deletes that +/// artboard, the last one. A step that names its artboard keeps it. +#[test] +fn steps_act_on_the_artboard_active_as_they_run() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 2); + let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}}); + let mut first = align(json!(0)); + first["params"].as_object_mut().unwrap().remove("artboard"); + let actions = set(&[ + ("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]), + ("Align 1", vec![align(json!(0))]), + ("Fit", vec![json!({"command": "artboard.fitToSelection"})]), + ]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions); + let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was"); + assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other"); + log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); +} + +/// The active artboard a step gets is the index it had as the run started: after a step deletes an +/// artboard before it, the artboard now at that index, as the view shows it. +#[test] +fn steps_keep_the_active_artboards_index() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let uid = s.active().unwrap().uid; + let add = |s: &Session| script::actions::on_active_artboard(s, &[(uid, 1)], "object.align", &json!({})); + assert_eq!(add(&s), json!({"artboard": 1})); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one"); +} + +/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its +/// `indices` fits those. +#[test] +fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + let actions = set(&[ + ("Fit", vec![json!({"command": "artboard.fitToArt"})]), + ("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]), + ]); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art"); + log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions); + assert_eq!(boards(&s), art, "the step's own indices"); +} + +/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it +/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps +/// still get the active one. +#[test] +fn paste_and_fit_steps_keep_the_artboard_tools_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + make_active(&mut s, 1); + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &[], id, &json!({})); + assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + assert_eq!(add(&s, id), json!({}), "{id}"); + } + assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); + assert_eq!(add(&s, "shape.rectangle"), json!({})); +} diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..11b2fe1360 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -359,6 +359,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() { fuel: script::DEFAULT_FUEL, locale: "en_US".into(), answers: Vec::new(), + actions: Vec::new(), }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..02a9f756ea 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -156,6 +156,8 @@ impl VectorcraftApp { } let mut params = params; self.add_active_artboard(id, &mut params); + // A script's `app.doScript` plays the Actions panel's actions. + panels::actions::add_script_actions(self, id, &mut params); // Edit Symbol from the Symbols panel in a document without artboards centers the symbol's // art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit // steps too. diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 12fc7c395e..9c0563b849 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -585,6 +585,64 @@ pub(crate) fn has_stop(commands: &[Value]) -> bool { commands.iter().any(is_stop) } +/// For command `id` `script.run`: gives its `params` the panel's actions as `actions`, which the +/// script's `app.doScript` plays, unless the caller gave them: every action of every set, in panel +/// order, with its steps as playback runs them ([`Action::playback_steps`]) and each step's place in +/// the action. An action that `actions` cannot hold (a step that is not a command, a name that is +/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out. +pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { + use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, parse}; + let Some(p) = params.as_object_mut().filter(|_| id == "script.run") else { return }; + if p.contains_key("actions") { + return; + } + let (mut list, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); + for (set, a) in app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))) { + if list.len() >= MAX_ACTIONS { + break; + } + // The commands of a recorded `command.batch` step go back into one batch step, so that an + // error names a failing command by the batch's place and its own (`3.2`). + let mut played: Vec = Vec::new(); + for s in a.playback_steps() { + let params = match s.command.get("params") { + None | Some(Value::Null) => json!({}), + Some(p) => p.clone(), + }; + let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params}); + let place = s.row + 1; + if a.steps.get(s.row).is_none_or(|(id, _)| id != "command.batch") { + let mut one = one; + one["step"] = json!(place); + played.push(one); + continue; + } + match played.last_mut() { + Some(last) if last["command"] == "command.batch" && last["step"] == place => { + if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") { + inner.push(one); + } + } + _ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})), + } + } + let entry = json!({"set": set.name, "name": a.name, "steps": played}); + let one = Value::Array(vec![entry]); + let Ok(parsed) = parse(Some(&one)) else { continue }; + let count = parsed.first().map_or(0, vectorcraft_engine::script::actions::Playable::len); + let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len()); + if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES { + continue; + } + steps += count; + bytes += size; + if let Value::Array(mut one) = one { + list.append(&mut one); + } + } + p.insert("actions".into(), Value::Array(list)); +} + /// The message and Allow Continue setting in a stop's params; each may be left out. A saved stop /// with no params reads as null here. A value of another type, or params that are neither null /// nor an object, is an error. @@ -7449,6 +7507,65 @@ mod tests { panic!("the script did not end"); } + /// A script's `app.doScript` plays the panel's actions with their included steps; an action whose + /// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept. + #[test] + fn a_script_plays_the_panels_actions() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let rect = |x: i64| ("shape.rectangle".to_string(), json!({"x": x, "y": 10, "width": 10, "height": 10})); + let mut draw = Action::new("Draw", vec![rect(0), rect(20), rect(40)]); + draw.excluded_steps.insert(1); + let odd = Action::new("Odd", vec![rect(0), ("select.none".to_string(), json!(5))]); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let batch = ("command.batch".to_string(), json!({"commands": [{"command": "select.none"}, bad]})); + let batched = Action::new("Batched", vec![("select.none".to_string(), json!({})), batch]); + app.ui.action_sets.push(ActionSet::new("Mine", vec![draw, odd, batched])); + let objects = + |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::()); + let undo = app.session.active().map_or(0, |d| d.history.undo.len()); + app.session.script_frames = false; + let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"])); + assert_eq!(objects(&app), 2, "the excluded step does not run"); + assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1); + // A failing command of a recorded batch is named by the batch's place and its own. + let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + let m = r["log"][0].as_str().unwrap_or_default(); + assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}"); + let r = app + .run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})) + .unwrap(); + assert_eq!(r["log"], json!(["there is no action set “Mine”"])); + assert_eq!(objects(&app), 2); + } + + /// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's + /// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. + #[test] + fn a_script_plays_the_actions_on_the_active_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let batch = ("command.batch".to_string(), json!({"commands": [align]})); + let fit = ("artboard.fitToSelection".to_string(), json!({})); + app.ui.action_sets.push(ActionSet::new("Mine", vec![Action::new("Align", vec![batch]), Action::new("Fit", vec![fit])])); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&app); + app.view_mut().unwrap().artboard = 1; + app.session.script_frames = false; + let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');"; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one"); + assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1"); + } + /// Begin Recording with `filler` steps already recorded. fn recording_with(app: &mut VectorcraftApp, filler: usize) { app.run(START_RECORDING, json!({})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..cda10102c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,27 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method + of the scripting reference + https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf + describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the + app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own + steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and + Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to + Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run + started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one + past the end. While the Artboard tool has several artboards selected, a paste step and a Fit to Artwork Bounds step + act on those instead, as in the panel's playback. VectorCraft's own rules: the action and its set are matched by + their exact names, and a name that matches no action or more than one throws an error before any step runs, as does + an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any + step runs, so an action cannot play itself. + Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts + as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an + error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an + uncaught error later puts them back with the rest of the run. `dialogs` must be `true` or `false` (default + `false`); no step opens a dialog, so it changes nothing. `app.loadAction` and `app.unloadAction` throw an error + that says they are not available yet when they are read or assigned. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..3b035c722c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 7c9b2a85a24397622a49b0137f0eadad7a095b58 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:27:56 -0800 Subject: [PATCH 024/104] Scripts: text frames, text ranges and fonts for scripts document.textFrames lists the document's type and makes point type, area type and type on a path. A TextFrame gives its kind, contents, text range, characters, words and paragraphs, outlines, and point and area conversion. A TextRange gives its contents, offsets, sub-collections, character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after). app.textFonts lists the fonts. Offsets count UTF-16 code units. A range follows edits made through these objects and throws Stale text range after the frame's text changes another way. Each change runs an existing text command inside the run's transaction, and a value a range already has runs no command. --- crates/engine/src/script/dom.rs | 18 +- crates/engine/src/script/dom/text.rs | 1557 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_text.rs | 394 +++++ .../tests/it/script_host_vs_scriptcheck.rs | 61 +- docs/mcp.md | 46 + docs/target-app-parity.md | 3 +- 7 files changed, 2072 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/text.rs create mode 100644 crates/engine/src/tests/script_text.rs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..d467345a2c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; use crate::{DocState, Document, NodeId, NodeKind, Session}; +mod text; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -92,6 +94,7 @@ pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + text: text::TextState, } impl State { @@ -151,7 +154,7 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member the help pages list that is not available yet: reading or assigning it throws, after -/// the check that a document or page item `this` is still there. +/// the check that a document, page item or text range `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); @@ -162,9 +165,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "TextFrame" => { item_of(&h, arg(&a, 0))?; } + "TextRange" => { + text::check_range(&h, arg(&a, 0))?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -1707,6 +1713,7 @@ const ENUMS: &[(&str, &[&str])] = &[ /// Adds `app`, its classes and the enumerations to `realm`; their members act for the run `link` /// holds. pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> { + text::install_enums(realm)?; for (name, members) in ENUMS { let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); realm.define_host_object(name, items)?; @@ -1720,6 +1727,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), ]); + application.push(("textFonts".into(), text::app_text_fonts(l))); application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); @@ -1758,10 +1766,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), + ("textFrames", text::doc_text_frames(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); @@ -1828,7 +1837,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), .map(|m| later(l, "PageItem", m)), ); classes.push(class("PageItem", None, page_item, None)); - classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(ITEM_CLASSES.iter().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), Vec::new(), None))); + classes.extend(text::classes(l)); classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None)); realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))]) } diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs new file mode 100644 index 0000000000..fb2bd54daa --- /dev/null +++ b/crates/engine/src/script/dom/text.rs @@ -0,0 +1,1557 @@ +//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its +//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and +//! `paragraphAttributes`, and `app.textFonts`, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so +//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves +//! out to the whole character. One item of `characters` is one code point. +//! - `contents` gives each paragraph break as `\r` and each forced line break as `\u0003`; written +//! text may use `\r`, `\n` or `\r\n` for a paragraph break. +//! - A word is a run of characters that are not white space. A paragraph ends after its break, and +//! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. +//! - A range keeps its place while the script edits the frame through the object model: an edit +//! before it moves it, an edit over it shrinks it to the edit, and an insertion at one of its +//! ends joins it. When the frame's text changes in any other way (`vc.run`, an undo), every +//! range made before is stale and throws `Stale text range`. +//! - A character attribute read on a range whose characters differ gives the first character's +//! value; set on an empty range it changes nothing. A paragraph attribute reads the first +//! paragraph the range touches and sets every one of them. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref}; + +use super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item, editable, float, + frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property, text, typename_of, + whole, with_doc, +}; +use crate::{DocState, Document, NodeId, NodeKind}; + +/// The error of a text range, or of a collection of one, whose frame's text changed other than +/// through the object model. +pub const STALE_RANGE: &str = "Stale text range"; +/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit +/// is stale. +const MAX_EDITS: usize = 100_000; + +/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units. +pub(super) struct Index { + text: String, + /// The UTF-16 offset of each character's start, and the text's length last. + chars: Vec, + /// The byte offset of each character's start, and the text's length in bytes last. + bytes: Vec, + words: Vec<(usize, usize)>, + paras: Vec<(usize, usize)>, +} + +impl Index { + fn new(text: String) -> Self { + let mut chars = Vec::with_capacity(text.len() + 1); + let mut bytes = Vec::with_capacity(text.len() + 1); + let (mut words, mut paras) = (Vec::new(), Vec::new()); + let (mut u, mut word, mut para) = (0, None, 0); + for (b, c) in text.char_indices() { + chars.push(u); + bytes.push(b); + if c.is_whitespace() { + if let Some(w) = word.take() { + words.push((w, u)); + } + } else if word.is_none() { + word = Some(u); + } + u += c.len_utf16(); + if c == '\n' { + paras.push((para, u)); + para = u; + } + } + if let Some(w) = word { + words.push((w, u)); + } + paras.push((para, u)); + chars.push(u); + bytes.push(text.len()); + Self { text, chars, bytes, words, paras } + } + + fn len(&self) -> usize { + self.chars.last().copied().unwrap_or(0) + } + + /// The byte offset of UTF-16 offset `u`; inside a surrogate pair, the start of its character, + /// or with `up` the end of it. + fn byte(&self, u: usize, up: bool) -> usize { + let i = self.chars.partition_point(|&c| c < u); + match self.chars.get(i) { + Some(&c) if c == u || up => self.bytes.get(i).copied().unwrap_or(self.text.len()), + _ => i.checked_sub(1).and_then(|i| self.bytes.get(i)).copied().unwrap_or(0), + } + } + + /// The characters whose start is in `s..e`, each as a UTF-16 span. + fn chars_in(&self, s: usize, e: usize) -> std::ops::Range { + let count = self.chars.len().saturating_sub(1); + let a = self.chars[..count].partition_point(|&c| c < s); + let b = self.chars[..count].partition_point(|&c| c < e); + a..b.max(a) + } + + fn char_span(&self, i: usize) -> Option<(usize, usize)> { + Some((*self.chars.get(i)?, *self.chars.get(i + 1)?)) + } +} + +/// The words or paragraphs of `spans` that `s..e` touches: those it overlaps, or, for an empty +/// range, the one with a character at it, or the last one when it ends there. Only an empty range +/// touches the empty paragraph after a break at the end of the text. +fn touched(spans: &[(usize, usize)], s: usize, e: usize) -> std::ops::Range { + if s == e { + let i = spans.partition_point(|&(_, y)| y <= s); + if spans.get(i).is_some_and(|&(x, _)| x <= s) { + return i..i + 1; + } + return match spans.last() { + Some(&(_, y)) if i == spans.len() && y == s => i - 1..i, + _ => i..i, + }; + } + let a = spans.partition_point(|&(_, y)| y <= s); + let b = spans.partition_point(|&(x, _)| x < e); + a..b.max(a) +} + +#[derive(Clone, Copy)] +struct Edit { + stamp: u64, + at: usize, + removed: usize, + inserted: usize, +} + +/// What the object model knows of one frame's text: the document it was read from, the text, the +/// edits made through the model, and the oldest range generation still valid. +struct Log { + doc: Weak, + index: Rc, + stamp: u64, + floor: u64, + edits: Vec, +} + +/// A document's uid, the document, and the ids of its type objects then. +type FrameList = (u64, Weak, Rc>); + +/// Word or paragraph spans, in UTF-16 units. +type Spans = [(usize, usize)]; + +/// The text state of one run. +#[derive(Default)] +pub(in crate::script) struct TextState { + frames: RefCell>, + /// A document's uid, the document, and the ids of its type objects in paint order. + list: RefCell>, + /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character + /// names that is not installed is added at the end. + fonts: RefCell>>, +} + +fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { + match &st.doc.node(id)?.kind { + NodeKind::Text(t) => Some(t), + _ => None, + } +} + +fn same_text(t: &TextObject, s: &str) -> bool { + let mut rest = s; + for r in &t.runs { + match rest.strip_prefix(r.text.as_str()) { + Some(after) => rest = after, + None => return false, + } + } + rest.is_empty() +} + +/// The frame's index and its generation now, read again when its document changed. +fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { + let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut frames = h.dom.text.frames.borrow_mut(); + let key = (st.uid, id.0); + let now = Arc::as_ptr(&st.doc); + match frames.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) => {} + Some(l) => { + if !same_text(t, &l.index.text) { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(t.plain_text())); + } + l.doc = Arc::downgrade(&st.doc); + } + None => { + let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: Vec::new() }; + frames.insert(key, l); + } + } + let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A text range: its frame, its span in UTF-16 units and the generation it was made at. +#[derive(Clone, Copy)] +struct Span { + item: Item, + start: usize, + end: usize, + stamp: u64, +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.item.doc, |_, st| { + let (index, stamp) = observe(h, st, r.item.id)?; + let frames = h.dom.text.frames.borrow(); + let l = frames.get(&(st.uid, r.item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in &l.edits[from..] { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + e = if e < x.at { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + }; + } + let len = index.len(); + let e = e.min(len); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. +fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let now = t.plain_text(); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let mut frames = h.dom.text.frames.borrow_mut(); + let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + l.stamp += 1; + if expected { + l.edits.push(Edit { stamp: l.stamp, at, removed, inserted: inserted.encode_utf16().count() }); + if l.edits.len() > MAX_EDITS { + let keep = l.edits.split_off(MAX_EDITS / 2); + l.floor = keep.first().map_or(l.stamp, |x| x.stamp - 1); + l.edits = keep; + } + } else { + l.floor = l.stamp; + l.edits.clear(); + } + l.index = Rc::new(Index::new(now)); + l.doc = Arc::downgrade(&st.doc); + Ok(()) + }) +} + +// ---- handles ---- + +fn usize_of(n: f64) -> Option { + whole(n).and_then(|v| usize::try_from(v).ok()) +} + +fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(item.id); + host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) +} + +/// The span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; + Ok(Span { item: frame, start, end, stamp }) +} + +/// The text frame `this` names. +fn this_frame(h: &Host, a: &[Data]) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_none() { + return Err(HostError::Type("this is not a TextFrame".into())); + } + item_of(h, arg(a, 0)) +} + +/// The whole text of the frame as a span. +fn whole_span(h: &Host, item: Item) -> std::result::Result<(Rc, Span), HostError> { + with_doc(h, item.doc, |_, st| { + let (index, stamp) = observe(h, st, item.id)?; + let len = index.len(); + Ok((index, Span { item, start: 0, end: len, stamp })) + }) +} + +fn this_range(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["TextRange"]) +} + +/// Fails when `d` is not a text range, or is a stale one. +pub(super) fn check_range(h: &Host, d: &Data) -> std::result::Result<(), HostError> { + resolve(h, span_of(h, d, &["TextRange"])?).map(|_| ()) +} + +/// The span of `this`: a text range, or a text frame's whole text. +fn this_text(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, arg(a, 0))?)?.1); + } + span_of(h, arg(a, 0), &[class]) +} + +// ---- contents ---- + +/// The model's text as `contents` gives it. +fn to_script(s: &str) -> String { + s.chars() + .map(|c| match c { + '\n' => '\r', + '\u{2028}' => '\u{3}', + c => c, + }) + .collect() +} + +/// Text a script wrote, as the model keeps it. +fn from_script(s: &str) -> String { + s.replace("\r\n", "\n") + .chars() + .map(|c| match c { + '\r' => '\n', + '\u{3}' => '\u{2028}', + c => c, + }) + .collect() +} + +fn read_contents(h: &Host, r: Span) -> Answer { + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[a..b]))) +} + +/// Replaces the text of `r` with `value`, as one `text.editRange`. +fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { + let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; + let insert = from_script(v); + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?; + record(h, r.item, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn frame_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + read_contents(h, r) +} + +fn frame_set_contents(h: &Host, a: &[Data]) -> Answer { + let (_, r) = whole_span(h, this_frame(h, a)?)?; + write_contents(h, r, arg(a, 1)) +} + +fn range_contents(h: &Host, a: &[Data]) -> Answer { + read_contents(h, this_range(h, a)?) +} + +fn range_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, arg(a, 1)) +} + +// ---- TextFrame ---- + +fn frame_kind(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(match t.kind { + TextKind::Point => "TextType.POINTTEXT", + TextKind::Area { .. } => "TextType.AREATEXT", + TextKind::OnPath { .. } => "TextType.PATHTEXT", + })) + }) +} + +fn frame_orientation(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let t = text_of(st, item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(text(if t.vertical { "TextOrientation.VERTICAL" } else { "TextOrientation.HORIZONTAL" })) + }) +} + +fn frame_range(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let (_, r) = whole_span(h, item)?; + Ok(range_ref(h, item, r.start, r.end, r.stamp, "TextRange")) +} + +fn sub(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_text(h, a, "TextRange")?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, class)) +} + +fn characters(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Characters") +} + +fn words(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Words") +} + +fn paragraphs(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "Paragraphs") +} + +fn character_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "CharacterAttributes") +} + +fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + sub(h, a, "ParagraphAttributes") +} + +/// The id a command's result gives under `ids` (the first) or `id`. +fn result_id(d: &Data) -> Option { + let Data::Object(o) = d else { return None }; + let n = |v: &Data| if let Data::Number(n) = v { whole(*n) } else { None }; + o.iter() + .find_map(|(k, v)| match (k.as_str(), v) { + ("ids", Data::Array(ids)) => ids.first().and_then(n), + ("id", v) => n(v), + _ => None, + }) + .map(NodeId) +} + +fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { + let id = id.ok_or_else(|| HostError::Error("the command made no object".into()))?; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(item_ref(h, st, id)) +} + +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines. +fn frame_outline(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + let r = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + command(h, "type.createOutlines", &json!({})) + })?; + new_ref(h, item.doc, result_id(&r)) +} + +/// Converts area type to point type (`area` false) or point type to area type. +fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { + let item = this_frame(h, a)?; + let kind_ok = with_doc(h, item.doc, |_, st| { + text_of(st, item.id).map(|t| if to_area { matches!(t.kind, TextKind::Point) } else { matches!(t.kind, TextKind::Area { .. }) }) + }); + match kind_ok { + None => return Err(HostError::Error(STALE_ITEM.into())), + Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))), + Some(true) => {} + } + let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; + let r = edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + new_ref(h, item.doc, result_id(&r).or(Some(item.id))) +} + +fn frame_to_point(h: &Host, a: &[Data]) -> Answer { + convert(h, a, false) +} + +fn frame_to_area(h: &Host, a: &[Data]) -> Answer { + convert(h, a, true) +} + +// ---- TextRange ---- + +fn range_parent(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + resolve(h, r)?; + Ok(with_doc(h, r.item.doc, |_, st| item_ref(h, st, r.item.id))) +} + +fn range_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn range_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn range_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_range(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +/// `remove()`: deletes the range's text. +fn range_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_range(h, a)?, &text("")) +} + +/// `getParagraphLength()`: the length of the first paragraph the range touches, its break included. +fn range_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_range(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +/// `getTextRunLength()`: the length from the range's start to the end of the run of characters +/// with one style it starts in, within the range. +fn range_run_length(h: &Host, a: &[Data]) -> Answer { + let r = this_range(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + let b = index.byte(s, false); + let run_end = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let mut at = 0; + for run in &t.runs { + at += run.text.len(); + if at > b { + return Ok(at); + } + } + Ok(at) + })?; + let u = index.text[..run_end.min(index.text.len())].encode_utf16().count(); + Ok(num(float((u.min(e).max(s) - s) as u64))) +} + +// ---- collections of a range ---- + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Part { + Characters, + Words, + Paragraphs, +} + +const PARTS: [(&str, Part); 3] = [("Characters", Part::Characters), ("Words", Part::Words), ("Paragraphs", Part::Paragraphs)]; + +fn part_of(d: &Data) -> Option { + PARTS.iter().find(|(c, _)| handle_of(d, c).is_some()).map(|(_, p)| *p) +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(Span, Part), HostError> { + let part = part_of(arg(a, 0)).ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &["Characters", "Words", "Paragraphs"])?, part)) +} + +/// The spans of a collection, as a range of item numbers and the spans to look them up in. +fn part_spans(index: &Index, part: Part, s: usize, e: usize) -> (std::ops::Range, Option<&Spans>) { + match part { + Part::Characters => (index.chars_in(s, e), None), + Part::Words => (touched(&index.words, s, e), Some(&index.words)), + Part::Paragraphs => (touched(&index.paras, s, e), Some(&index.paras)), + } +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) +} + +// ---- character attributes ---- + +#[derive(Clone, Copy)] +enum Attr { + Size, + Leading, + AutoLeading, + Tracking, + BaselineShift, + HorizontalScale, + VerticalScale, + Rotation, + Underline, + StrikeThrough, + TextFont, +} + +const ATTRS: [(&str, Attr); 11] = [ + ("size", Attr::Size), + ("leading", Attr::Leading), + ("autoLeading", Attr::AutoLeading), + ("tracking", Attr::Tracking), + ("baselineShift", Attr::BaselineShift), + ("horizontalScale", Attr::HorizontalScale), + ("verticalScale", Attr::VerticalScale), + ("rotation", Attr::Rotation), + ("underline", Attr::Underline), + ("strikeThrough", Attr::StrikeThrough), + ("textFont", Attr::TextFont), +]; + +/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with +/// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty +/// range, the style of the character before it, or of the first one. +fn styles_in(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out = Vec::new(); + let (mut at, mut para) = (0, 0); + let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + let breaks = |from: usize, to: usize| bytes.get(from - at..to - at).map_or(0, |s| s.iter().filter(|&&c| c == b'\n').count()); + if a == b && at < a.max(1) && a <= end { + let lo = a.saturating_sub(1).max(at); + out.push((effective(&run.style)?, para + breaks(at, lo))); + break; + } + if a < end && at < b { + let (lo, hi) = (a.max(at), b.min(end)); + let style = effective(&run.style)?; + let mut p = para + breaks(at, lo); + out.push((style.clone(), p)); + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + p += 1; + if lo + k + 1 < hi { + out.push((style.clone(), p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + if out.is_empty() + && let Some(r) = t.runs.first() + { + out.push((effective(&r.style)?, 0)); + } + Ok(out) +} + +/// The bytes in `a..b` whose characters have auto leading, each stretch with the leading its +/// characters' auto leading sets them with, in document points; touching stretches with the same +/// leading are one. +fn auto_leading_spans(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { + let mut out: Vec<(usize, usize, f64)> = Vec::new(); + let mut push = |from: usize, to: usize, leading: f64| match out.last_mut() { + Some(last) if last.1 == from && same(&num(last.2), &num(leading)) => last.1 = to, + _ => out.push((from, to, leading)), + }; + let (mut at, mut para) = (0, 0); + for run in &t.runs { + let end = at + run.text.len(); + let bytes = run.text.as_bytes(); + if a < end && at < b { + let style = t.effective_char_style(&run.style).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into()))?; + if style.leading.is_none() { + let (lo, hi) = (a.max(at), b.min(end)); + let auto = |p: usize| t.para_at(p).justification.auto_leading_for(style.size); + let mut p = para + bytes.get(..lo - at).unwrap_or_default().iter().filter(|&&c| c == b'\n').count(); + let mut from = lo; + for (k, _) in bytes.get(lo - at..hi - at).unwrap_or_default().iter().enumerate().filter(|&(_, &c)| c == b'\n') { + let to = lo + k + 1; + push(from, to, auto(p)); + p += 1; + from = to; + } + if from < hi { + push(from, hi, auto(p)); + } + } + } + para += bytes.iter().filter(|&&c| c == b'\n').count(); + at = end; + } + Ok(out) +} + +fn same(a: &Data, b: &Data) -> bool { + match (a, b) { + (Data::Number(x), Data::Number(y)) => (x - y).abs() < 1e-9, + _ => a == b, + } +} + +fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize) -> Data { + match attr { + Attr::Size => num(s.size), + Attr::Leading => num(s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size))), + Attr::AutoLeading => Data::Bool(s.leading.is_none()), + Attr::Tracking => num(s.tracking), + Attr::BaselineShift => num(s.baseline_shift), + Attr::HorizontalScale => num(s.h_scale), + Attr::VerticalScale => num(s.v_scale), + Attr::Rotation => num(s.rotation), + Attr::Underline => Data::Bool(s.underline), + Attr::StrikeThrough => Data::Bool(s.strikethrough), + Attr::TextFont => font_ref(h, &s.font_family, &s.font_style), + } +} + +/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after. +fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> { + let finite = || number(v, name); + Ok(match attr { + Attr::Size => { + let n = finite()?; + if !(0.1..=1296.0).contains(&n) { + return Err(HostError::Range("size must be from 0.1 to 1296 points".into())); + } + (json!({"size": n}), num(n)) + } + Attr::Leading => { + let n = finite()?; + if !(0.1..=5000.0).contains(&n) { + return Err(HostError::Range("leading must be from 0.1 to 5000 points".into())); + } + (json!({"leading": n}), num(n)) + } + Attr::AutoLeading => { + if boolean(v, name)? { + (json!({"leading": "auto"}), Data::Bool(true)) + } else { + let (t, s, para) = first; + let n = s.leading.unwrap_or_else(|| t.para_at(para).justification.auto_leading_for(s.size)); + (json!({"leading": n}), Data::Bool(false)) + } + } + Attr::Tracking => { + let n = finite()?; + if !(-1000.0..=10_000.0).contains(&n) { + return Err(HostError::Range("tracking must be from -1000 to 10000".into())); + } + (json!({"tracking": n}), num(n)) + } + Attr::BaselineShift => { + let n = finite()?; + if n.abs() > 1296.0 { + return Err(HostError::Range("baselineShift must be from -1296 to 1296 points".into())); + } + (json!({"baselineShift": n}), num(n)) + } + Attr::HorizontalScale | Attr::VerticalScale => { + let n = finite()?; + if !(1.0..=10_000.0).contains(&n) { + return Err(HostError::Range(format!("{name} must be from 1 to 10000 percent"))); + } + let key = if matches!(attr, Attr::HorizontalScale) { "hScale" } else { "vScale" }; + (json!({ key: n }), num(n)) + } + Attr::Rotation => { + let n = finite()?; + if n.abs() > 360.0 { + return Err(HostError::Range("rotation must be from -360 to 360 degrees".into())); + } + (json!({"rotation": n}), num(n)) + } + Attr::Underline => { + let b = boolean(v, name)?; + (json!({"underline": b}), Data::Bool(b)) + } + Attr::StrikeThrough => { + let b = boolean(v, name)?; + (json!({"strikethrough": b}), Data::Bool(b)) + } + Attr::TextFont => { + let (family, style) = font_of(h, v)?; + (json!({"font": family, "style": style}), font_ref(h, &family, &style)) + } + }) +} + +/// The span of `this` for a character or paragraph attribute: a text range, its +/// `characterAttributes` or `paragraphAttributes`, or a text frame's whole text. +fn attr_span(h: &Host, a: &[Data], class: &str) -> std::result::Result { + if handle_of(arg(a, 0), "TextRange").is_some() { + return this_range(h, a); + } + this_text(h, a, class) +} + +fn read_attr(h: &Host, a: &[Data], attr: Attr) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(styles_in(t, ba, bb)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + }) +} + +fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let r = attr_span(h, a, "CharacterAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (ba, bb) = (index.byte(s, false), index.byte(e, true)); + let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let styles = styles_in(t, ba, bb)?; + let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); + let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; + let unchanged = ba == bb || styles.iter().all(|(st, p)| same(&attr_value(h, attr, t, st, *p), &wants)); + let fixed = match (attr, &wants) { + (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), + _ => None, + }; + if let Some(bad) = fixed.iter().flatten().map(|(_, _, l)| *l).find(|l| !(0.1..=5000.0).contains(l)) { + return Err(HostError::Range(format!("autoLeading cannot be turned off: the auto leading here is {bad} points, outside 0.1 to 5000"))); + } + Ok::<_, HostError>((param, unchanged, fixed)) + })?; + if unchanged { + return Ok(Data::Undefined); + } + if let Some(spans) = fixed { + // Each character with auto leading keeps the leading it is set with now. + super::atomically(h, |h| { + for (start, end, leading) in &spans { + let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading}); + edit_item(h, r.item, "text.setRangeStyle", &p)?; + } + Ok(()) + })?; + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?; + if let Attr::TextFont = attr { + let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?; + } + Ok(Data::Undefined) +} + +/// Fails, after the font is set, when `text.setRangeStyle` warned that the font is not available +/// or when characters in bytes `a..b` kept another font because Missing Glyph Protection is on. +fn font_applied(h: &Host, item: Item, (a, b): (usize, usize), (family, style): (&str, &str), answer: &Data) -> std::result::Result<(), HostError> { + if let Data::Object(o) = answer + && let Some((_, Data::String(w))) = o.iter().find(|(k, _)| k == "warning") + { + return Err(HostError::Error(format!("textFont: {w}"))); + } + let kept = with_doc(h, item.doc, |_, st| { + let Some(t) = text_of(st, item.id) else { return 0 }; + let mut at = 0; + let mut kept = 0; + for run in &t.runs { + let end = at + run.text.len(); + let other = !run.style.font_family.eq_ignore_ascii_case(family) || !run.style.font_style.eq_ignore_ascii_case(style); + if other && a < end && at < b { + kept += run.text.get(a.max(at) - at..b.min(end) - at).map_or(0, |s| s.chars().count()); + } + at = end; + } + kept + }); + if kept > 0 { + let noun = if kept == 1 { "character, which keeps its" } else { "characters, which keep their" }; + return Err(HostError::Error(format!("textFont: the font has no glyph for {kept} {noun} font because Missing Glyph Protection is on"))); + } + Ok(()) +} + +// ---- paragraph attributes ---- + +#[derive(Clone, Copy)] +enum ParaAttr { + Justification, + FirstLineIndent, + LeftIndent, + RightIndent, + SpaceBefore, + SpaceAfter, +} + +const PARA_ATTRS: [(&str, ParaAttr); 6] = [ + ("justification", ParaAttr::Justification), + ("firstLineIndent", ParaAttr::FirstLineIndent), + ("leftIndent", ParaAttr::LeftIndent), + ("rightIndent", ParaAttr::RightIndent), + ("spaceBefore", ParaAttr::SpaceBefore), + ("spaceAfter", ParaAttr::SpaceAfter), +]; + +const JUSTIFICATIONS: [(&str, &str); 7] = [ + ("LEFT", "left"), + ("CENTER", "center"), + ("RIGHT", "right"), + ("FULLJUSTIFYLASTLINELEFT", "justifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "justifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "justifyRight"), + ("FULLJUSTIFY", "justifyAll"), +]; + +/// The text of paragraph `i` of `index`, its break included. +fn para_text(index: &Index, i: usize) -> &str { + index.paras.get(i).and_then(|&(x, y)| index.text.get(index.byte(x, false)..index.byte(y, false))).unwrap_or_default() +} + +/// The value of `attr` in paragraph `i` of `t`, whose text `index` holds. Auto alignment reads as +/// the side it aligns to: right in a right-to-left paragraph, left otherwise. +fn para_value(attr: ParaAttr, t: &TextObject, index: &Index, i: usize) -> Data { + let p = t.para_at(i); + match attr { + ParaAttr::Justification => text(format!( + "Justification.{}", + match p.justify { + Justify::Auto if vectorcraft_text::paragraph_is_rtl(para_text(index, i), p.direction) => "RIGHT", + Justify::Auto | Justify::Left => "LEFT", + Justify::Center => "CENTER", + Justify::Right => "RIGHT", + Justify::JustifyLeft => "FULLJUSTIFYLASTLINELEFT", + Justify::JustifyCenter => "FULLJUSTIFYLASTLINECENTER", + Justify::JustifyRight => "FULLJUSTIFYLASTLINERIGHT", + Justify::JustifyAll => "FULLJUSTIFY", + } + )), + ParaAttr::FirstLineIndent => num(p.first_line_indent), + ParaAttr::LeftIndent => num(p.left_indent), + ParaAttr::RightIndent => num(p.right_indent), + ParaAttr::SpaceBefore => num(p.space_before), + ParaAttr::SpaceAfter => num(p.space_after), + } +} + +/// The command and parameter that set `attr` to `v`, and the value it reads as after. +fn para_param(attr: ParaAttr, name: &str, v: &Data) -> std::result::Result<(&'static str, Value, Data), HostError> { + if let ParaAttr::Justification = attr { + let found = match v { + Data::String(s) => s.strip_prefix("Justification.").and_then(|m| JUSTIFICATIONS.iter().find(|(k, _)| *k == m)), + _ => None, + }; + let (_, value) = found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?; + return Ok(("text.setStyle", json!({"justify": value}), v.clone())); + } + let n = number(v, name)?; + if n.abs() > 1296.0 { + return Err(HostError::Range(format!("{name} must be from -1296 to 1296 points"))); + } + let key = match attr { + ParaAttr::FirstLineIndent => "firstLineIndent", + ParaAttr::LeftIndent => "leftIndent", + ParaAttr::RightIndent => "rightIndent", + ParaAttr::SpaceBefore => "spaceBefore", + _ => "spaceAfter", + }; + Ok(("text.setFormat", json!({ key: n }), num(n))) +} + +/// The paragraphs a range touches, by number, and the bytes from the first one's start to the last +/// one's start, which select exactly those paragraphs for `text.setFormat` and `text.setStyle`. +fn para_range(index: &Index, s: usize, e: usize) -> (std::ops::Range, usize, usize) { + let paras = touched(&index.paras, s, e); + let start = |i: usize| index.paras.get(i).map_or(index.text.len(), |&(x, _)| index.byte(x, false)); + let (ba, bb) = (start(paras.start), start(paras.end.saturating_sub(1).max(paras.start))); + (paras, ba, bb) +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, _, _) = para_range(&index, s, e); + with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + Ok(para_value(attr, t, &index, paras.start)) + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let r = attr_span(h, a, "ParagraphAttributes")?; + let (id, param, wants) = para_param(attr, name, arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let (paras, ba, bb) = para_range(&index, s, e); + let unchanged = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + // An explicit alignment replaces Auto even where Auto aligns to the same side. + let auto = |i: usize| matches!(attr, ParaAttr::Justification) && t.para_at(i).justify == Justify::Auto; + Ok::<_, HostError>(paras.clone().all(|i| !auto(i) && same(¶_value(attr, t, &index, i), &wants))) + })?; + if unchanged { + return Ok(Data::Undefined); + } + let mut p = param; + if let Some(o) = p.as_object_mut() { + o.insert("id".into(), json!(r.item.id.0)); + o.insert("start".into(), json!(ba)); + o.insert("end".into(), json!(bb)); + } + edit_item(h, r.item, id, &p)?; + Ok(Data::Undefined) +} + +// ---- TextFrames ---- + +fn doc_text_frames_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("TextFrames", &[float(h.run), float(doc.uid)])) +} + +/// `document.textFrames`. +pub(super) fn doc_text_frames(link: &Link) -> HostMember { + get(link, doc_text_frames_impl) +} + +/// The ids of the document's type objects in paint order, kept while the document is unchanged. +fn frame_ids(h: &Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.text.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return ids.clone(); + } + let ids: Vec = page_items(h, st).iter().copied().filter(|i| text_of(st, *i).is_some()).collect(); + let ids = Rc::new(ids); + *h.dom.text.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), ids.clone())); + ids +} + +fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "TextFrames") +} + +fn frames_length(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).len()) as u64))) +} + +fn frames_parent(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn frames_at(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + Ok(with_doc(h, doc, |_, st| frame_ids(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +fn frames_by_name(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64)?; + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn frames_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => frames_by_name(h, a), + Data::Number(_) => match frames_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `TextOrientation` as `text.create`'s `vertical`, `undefined` horizontal. +fn vertical_of(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(false), + Data::String(s) if s == "TextOrientation.HORIZONTAL" => Ok(false), + Data::String(s) if s == "TextOrientation.VERTICAL" => Ok(true), + _ => Err(HostError::Type("orientation must be a TextOrientation value".into())), + } +} + +/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. +fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { + let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; + let r = on_doc(h, doc.uid, true, |h| command(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `add()`: empty point type at the origin. +fn frames_add(h: &Host, a: &[Data]) -> Answer { + point_text(h, frames_doc(h, a)?, None, false) +} + +/// `pointText(anchor, orientation?)`. +fn frames_point_text(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let anchor = point(arg(a, 1), "anchor")?; + point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?) +} + +/// Turns the path `d` names into area type or type on a path with `text.createInPath`. +fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { + let doc = frames_doc(h, a)?; + if handle_of(arg(a, 1), "PathItem").is_none() { + return Err(HostError::Type("textPath must be a PathItem".into())); + } + let path = item_of(h, arg(a, 1))?; + if path.doc.uid != doc.uid { + return Err(HostError::Error(super::CROSS_DOCUMENT.into())); + } + if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { + return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); + } + let orientation = if on_path { 4 } else { 2 }; + let vertical = vertical_of(arg(a, orientation))?; + let mode = if on_path { "onPath" } else { "area" }; + let r = + on_doc(h, doc.uid, true, |h| command(h, "text.createInPath", &json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical})))?; + new_ref(h, doc, result_id(&r)) +} + +/// `areaText(textPath, orientation?, baseFrame?, postFix?)`. +fn frames_area_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, false, &[3, 4]) +} + +/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. +fn frames_path_text(h: &Host, a: &[Data]) -> Answer { + in_path(h, a, true, &[2, 3, 5, 6]) +} + +/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { + let doc = frames_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = frame_ids(h, st); + let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); + let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); + (ids, refused) + }); + if !refused.is_empty() { + let list = refused.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); + } + if !ids.is_empty() { + on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + } + Ok(Data::Undefined) +} + +// ---- fonts ---- + +/// The run's font list, read once. +fn with_fonts(h: &Host, f: impl FnOnce(&mut Vec<(String, String)>) -> T) -> T { + let mut fonts = h.dom.text.fonts.borrow_mut(); + let list = fonts.get_or_insert_with(|| { + let db = vectorcraft_text::FontDb::global(); + let mut v = Vec::new(); + for family in db.menu_family_list().iter() { + for style in db.styles(family) { + v.push((family.clone(), style)); + } + } + v + }); + f(list) +} + +/// A `TextFont` for `family` and `style`, added to the run's list when it is not there. +fn font_ref(h: &Host, family: &str, style: &str) -> Data { + let i = with_fonts(h, |list| match list.iter().position(|(f, s)| f.eq_ignore_ascii_case(family) && s.eq_ignore_ascii_case(style)) { + Some(i) => i, + None => { + list.push((family.to_string(), style.to_string())); + list.len() - 1 + } + }); + host_ref("TextFont", &[float(h.run), float(i as u64)]) +} + +/// The family and style of the `TextFont` `d`. +fn font_of(h: &Host, d: &Data) -> std::result::Result<(String, String), HostError> { + let Some(&[run, i]) = handle_of(d, "TextFont").as_deref() else { return Err(HostError::Type("textFont must be a TextFont".into())) }; + if whole(run) != Some(h.run) { + return Err(HostError::Error("Stale text font".into())); + } + usize_of(i).and_then(|i| with_fonts(h, |list| list.get(i).cloned())).ok_or_else(|| HostError::Error("Stale text font".into())) +} + +fn fonts_length(h: &Host, _: &[Data]) -> Answer { + Ok(num(float(with_fonts(h, |l| l.len()) as u64))) +} + +fn fonts_at(h: &Host, a: &[Data]) -> Answer { + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = with_fonts(h, |l| i < l.len()); + Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) +} + +/// `textFonts.getByName(name)`: the PostScript name, then the family and style with a space. +fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let named = vectorcraft_text::FontDb::global().by_postscript_name(name); + let i = with_fonts(h, |l| { + h.charge_call(l.len() as u64)?; + let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); + Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) + })?; + i.map(|i| host_ref("TextFont", &[float(h.run), float(i as u64)])).ok_or_else(|| HostError::Error(NOT_FOUND.into())) +} + +fn fonts_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => fonts_by_name(h, a), + Data::Number(_) => match fonts_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +fn font_family(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.0)) +} + +fn font_style(h: &Host, a: &[Data]) -> Answer { + Ok(text(font_of(h, arg(a, 0))?.1)) +} + +/// The font's PostScript name, or its family and style joined by a hyphen when the font is not +/// installed. +fn font_name(h: &Host, a: &[Data]) -> Answer { + let (family, style) = font_of(h, arg(a, 0))?; + let face = vectorcraft_text::FontDb::global().face(&family, &style); + Ok(text(face.map_or_else(|| format!("{family}-{style}").replace(' ', ""), |f| f.postscript_name()))) +} + +fn app_text_fonts_impl(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("TextFonts", &[])) +} + +/// `app.textFonts`. +pub(super) fn app_text_fonts(link: &Link) -> HostMember { + get(link, app_text_fonts_impl) +} + +fn app_ref(_: &Host, _: &[Data]) -> Answer { + Ok(host_ref("Application", &[])) +} + +/// A font's `parent`, `app`, once the font is checked. +fn font_parent(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(host_ref("Application", &[])) +} + +// ---- classes ---- + +/// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the +/// read's own checks of `this`. +fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { + let message = format!("{class}.{name} cannot be set yet"); + let get = function(link, g); + let read = get.clone(); + HostMember::Property { + get, + set: Rc::new(move |a: Vec| { + read(a.into_iter().take(1).collect())?; + Err(HostError::Error(message.clone())) + }), + } +} + +fn attr_members(link: &Link) -> Vec<(String, HostMember)> { + let mut out = Vec::new(); + for (name, attr) in ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_attr(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_attr(&h, &a, attr, name) + }); + out.push((name.to_string(), HostMember::Property { get: g, set: s })); + } + out +} + +fn para_members(link: &Link) -> Vec<(String, HostMember)> { + let mut out = Vec::new(); + for (name, attr) in PARA_ATTRS { + let l = link.clone(); + let g: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + read_para(&h, &a, attr) + }); + let l = link.clone(); + let s: HostFunction = Rc::new(move |a: Vec| { + let h = super::current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + write_para(&h, &a, attr, name) + }); + out.push((name.to_string(), HostMember::Property { get: g, set: s })); + } + out +} + +/// The enumerations type uses. +const ENUMS: &[(&str, &[&str])] = &[ + ("TextType", &["AREATEXT", "PATHTEXT", "POINTTEXT"]), + ("TextOrientation", &["HORIZONTAL", "VERTICAL"]), + ( + "Justification", + &["CENTER", "FULLJUSTIFY", "FULLJUSTIFYLASTLINECENTER", "FULLJUSTIFYLASTLINELEFT", "FULLJUSTIFYLASTLINERIGHT", "LEFT", "RIGHT"], + ), +]; + +/// Adds the enumerations type uses to `realm`. +pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> { + for (name, members) in ENUMS { + let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +/// The classes of type, `TextFrame` among them, which inherits from `PageItem`. +pub(super) fn classes(l: &Link) -> Vec { + let mut frame = named(vec![ + ("kind", get(l, frame_kind)), + ("contents", property(l, frame_contents, frame_set_contents)), + ("textRange", get(l, frame_range)), + ("characters", get(l, characters)), + ("words", get(l, words)), + ("paragraphs", get(l, paragraphs)), + ("orientation", read_only(l, frame_orientation, "TextFrame", "orientation")), + ("createOutline", method(l, frame_outline)), + ("convertAreaObjectToPointObject", method(l, frame_to_point)), + ("convertPointObjectToAreaObject", method(l, frame_to_area)), + ]); + frame.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "nextFrame", + "previousFrame", + "textPath", + "anchor", + "antialias", + "columnCount", + "columnGutter", + "rowCount", + "rowGutter", + "startTValue", + "endTValue", + "opticalAlignment", + "matrix", + "textSelection", + ] + .into_iter() + .map(|m| super::later(l, "TextFrame", m)), + ); + let mut range = named(vec![ + ("typename", typename_of("TextRange")), + ("parent", get(l, range_parent)), + ("contents", property(l, range_contents, range_set_contents)), + ("start", read_only(l, range_start, "TextRange", "start")), + ("end", read_only(l, range_end, "TextRange", "end")), + ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset")), + ("length", read_only(l, range_length, "TextRange", "length")), + ("characters", get(l, characters)), + ("words", get(l, words)), + ("paragraphs", get(l, paragraphs)), + ("characterAttributes", get(l, character_attributes)), + ("paragraphAttributes", get(l, paragraph_attributes)), + ("getParagraphLength", method(l, range_paragraph_length)), + ("getTextRunLength", method(l, range_run_length)), + ("remove", method(l, range_remove)), + ]); + range.extend(attr_members(l)); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "story", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .map(|m| super::later(l, "TextRange", m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![("typename", typename_of(name)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + Some(function(l, part_at)), + ) + }; + let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + chars.extend(attr_members(l)); + let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + paras.extend(para_members(l)); + vec![ + class("TextFrame", Some("PageItem"), frame, None), + class("TextRange", None, range, None), + part("Characters"), + part("Words"), + part("Paragraphs"), + class("CharacterAttributes", None, chars, None), + class("ParagraphAttributes", None, paras, None), + class( + "TextFrames", + None, + named(vec![ + ("typename", typename_of("TextFrames")), + ("length", get(l, frames_length)), + ("parent", get(l, frames_parent)), + ("index", method(l, frames_index)), + ("getByName", method(l, frames_by_name)), + ("add", method(l, frames_add)), + ("pointText", method(l, frames_point_text)), + ("areaText", method(l, frames_area_text)), + ("pathText", method(l, frames_path_text)), + ("removeAll", method(l, frames_remove_all)), + ]), + Some(function(l, frames_at)), + ), + class( + "TextFonts", + None, + named(vec![ + ("typename", typename_of("TextFonts")), + ("length", get(l, fonts_length)), + ("parent", get(l, app_ref)), + ("index", method(l, fonts_index)), + ("getByName", method(l, fonts_by_name)), + ]), + Some(function(l, fonts_at)), + ), + class( + "TextFont", + None, + named(vec![ + ("typename", typename_of("TextFont")), + ("name", get(l, font_name)), + ("family", get(l, font_family)), + ("style", get(l, font_style)), + ("parent", get(l, font_parent)), + ]), + None, + ), + ] +} + +#[cfg(test)] +mod tests { + use super::{Index, touched}; + + #[test] + fn index_counts_utf16_units_and_splits_words_and_paragraphs() { + let i = Index::new("a\u{1F600}b c\nd".into()); + assert_eq!(i.len(), 8); + assert_eq!(i.chars, vec![0, 1, 3, 4, 5, 6, 7, 8]); + assert_eq!(i.byte(2, false), 1); + assert_eq!(i.byte(2, true), 5); + assert_eq!(i.words, vec![(0, 4), (5, 6), (7, 8)]); + assert_eq!(i.paras, vec![(0, 7), (7, 8)]); + assert_eq!(i.chars_in(1, 4), 1..3); + } + + #[test] + fn only_an_empty_range_touches_the_empty_paragraph_at_the_end() { + let i = Index::new("a\n".into()); + assert_eq!(i.paras, vec![(0, 2), (2, 2)]); + assert_eq!(touched(&i.paras, 0, 2), 0..1); + assert_eq!(touched(&i.paras, 0, 1), 0..1); + assert_eq!(touched(&i.paras, 2, 2), 1..2); + assert_eq!(touched(&i.paras, 1, 1), 0..1); + let e = Index::new(String::new()); + assert_eq!(touched(&e.paras, 0, 0), 0..1); + assert_eq!(touched(&e.words, 0, 0), 0..0); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..cd2a81daeb 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_text; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs new file mode 100644 index 0000000000..6d9f6614f1 --- /dev/null +++ b/crates/engine/src/tests/script_text.rs @@ -0,0 +1,394 @@ +//! Type in the script object model: `textFrames`, text ranges, their attributes and `textFonts`. + +use serde_json::{Value, json}; +use vectorcraft_doc::Justify; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.size)).collect(), + _ => panic!("not text"), + } +} + +#[test] +fn text_frames_add_point_area_and_path_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 200, "height": 100})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems;\ + var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var pt = d.textFrames.add(); pt.contents = 'Point';\ + var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ + vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ + vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ + vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", + ); + assert_eq!(out[0], json!(4)); + assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); + assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("At"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); + assert_eq!(undo_steps(&s), before + 1); + // A path of another kind, or no path, is refused. + assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1]);").contains("anchor")); + assert!(failure(&mut s, "app.activeDocument.textFrames.pointText([1, 2], 'up');").contains("TextOrientation")); + assert_eq!(undo_steps(&s), before + 1); + // pathText takes its orientation fourth, after the start and end positions it does not take yet. + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 250}, {"x": 300, "y": 260}], "closed": false})).unwrap(); + let find = "var d = app.activeDocument, p = d.pageItems, q; for (var i = 0; i < p.length; i++) if (p[i].typename == 'PathItem') q = p[i];"; + assert!(failure(&mut s, &format!("{find} d.textFrames.pathText(q, 0.5);")).contains("not available yet")); + let out = log(&mut s, &format!("{find} vc.log(d.textFrames.pathText(q, undefined, undefined, TextOrientation.VERTICAL).orientation);")); + assert_eq!(out, vec![json!("TextOrientation.VERTICAL")]); +} + +#[test] +fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { + let (mut s, id) = doc_with("x"); + let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); + assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); + assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = 5;").contains("contents must be a string")); +} + +#[test] +fn offsets_count_utf16_units_and_keep_surrogate_pairs_whole() { + let (mut s, _) = doc_with("a\u{1F600}b cd"); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].textRange, c = r.characters;\ + vc.log([r.length, r.start, r.end, c.length]);\ + vc.log([c[1].start, c[1].length, c[2].start, c[2].contents]);\ + vc.log([r.words.length, r.words[1].contents, r.words[0].characters.length]);\ + vc.log(app.activeDocument.textFrames[0].contents.length === r.length);", + ); + assert_eq!(out, vec![json!([7, 0, 7, 6]), json!([1, 2, 3, "b"]), json!([2, "cd", 3]), json!(true)]); +} + +#[test] +fn the_first_character_of_each_word_grows_in_one_undo_step() { + let (mut s, id) = doc_with("one two"); + let before = undo_steps(&s); + log( + &mut s, + "var text = app.activeDocument.textFrames[0].textRange;\ + for (var j = 0; j < text.words.length; j++) { var f = text.words[j].characters[0]; f.size = f.size * 1.5; }", + ); + assert_eq!(sizes(&s, id), vec![("o".into(), 18.0), ("ne ".into(), 12.0), ("t".into(), 18.0), ("wo".into(), 12.0)]); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn ranges_follow_model_edits_and_go_stale_after_other_edits() { + let (mut s, id) = doc_with("one two three"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], w = t.words, second = w[1], third = w[2];\ + w[0].contents = 'first'; vc.log([second.contents, second.start, third.contents]);\ + second.contents = ''; vc.log([second.length, third.contents, t.contents]);", + ); + assert_eq!(out, vec![json!(["two", 6, "three"]), json!([0, "three", "first three"])]); + let source = format!("var r = app.activeDocument.textFrames[0].words[0]; vc.run('text.setText', {{id: {}, text: 'other'}}); r.contents;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0], r = t.textRange; t.remove(); r.contents;"); + assert!(e.contains("Stale text range"), "{e}"); + // A change reversed before the range is read leaves the text the range knew. + let (mut s, id) = doc_with("one two"); + let source = format!( + "var r = app.activeDocument.textFrames[0].words[1]; vc.run('text.setText', {{id: {0}, text: 'other'}});\ + vc.run('text.setText', {{id: {0}, text: 'one two'}}); vc.log([r.contents, r.start]);", + id.0 + ); + assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); +} + +#[test] +fn bad_attribute_values_are_refused_without_a_change() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + for (src, want) in [ + ("r.size = 0;", "size must be from 0.1"), + ("r.size = 'big';", "size must be a finite number"), + ("r.size = NaN;", "not a finite number"), + ("r.leading = 0;", "leading must be from 0.1"), + ("r.characterAttributes.tracking = 1e9;", "tracking"), + ("r.underline = 1;", "underline must be true or false"), + ("r.textFont = 'Arial';", "textFont must be a TextFont"), + ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), + ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), + ("r.length = 1;", "cannot be set yet"), + ] { + let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); + assert!(e.contains(want), "{src}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(sizes(&s, id), vec![("abc".into(), 12.0)]); +} + +#[test] +fn setting_the_value_a_range_has_records_no_undo_step() { + let (mut s, _) = doc_with("abc"); + let before = undo_steps(&s); + log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.size = r.size; r.underline = false;\ + t.contents = t.contents; r.paragraphAttributes.leftIndent = 0; r.characters[0].characterAttributes.size = 12;", + ); + assert_eq!(undo_steps(&s), before); +} + +#[test] +fn paragraph_attributes_set_the_paragraphs_a_range_touches() { + let (mut s, _) = doc_with("first\nsecond"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs;\ + vc.log([p.length, p[0].contents, p[1].contents]);\ + p[1].paragraphAttributes.justification = Justification.CENTER; p[1].paragraphAttributes.leftIndent = 9;\ + vc.log([p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.leftIndent, p[1].paragraphAttributes.leftIndent, p[1].getParagraphLength()]);", + ); + assert_eq!(out[0], json!([2, "first\r", "second"])); + assert_eq!(out[1], json!(["Justification.LEFT", "Justification.CENTER"])); + assert_eq!(out[2], json!([0, 9, 6])); + // A paragraph whose range ends after its break sets only itself. + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ + p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p[0].justification === undefined, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([true, "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + // The empty paragraph after a final break belongs only to an empty range at the end. + let (mut s, id) = doc_with("a\n"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], p = t.paragraphs; p[0].paragraphAttributes.spaceAfter = 4;\ + vc.log([p.length, p[0].paragraphs.length, p[0].paragraphAttributes.spaceAfter]);", + ); + assert_eq!(out, vec![json!([1, 1, 4])]); + let after: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..2).map(|i| t.para_at(i).space_after).collect(), + _ => panic!("not text"), + }; + assert_eq!(after, vec![4.0, 0.0]); +} + +#[test] +fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() { + let (mut s, id) = doc_with("first\nsecond"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 6, "end": 6, "autoLeading": 200})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; vc.log([p[0].leading, p[1].leading, p[1].characters[0].leading]);\ + p[1].autoLeading = false; vc.log([p[0].autoLeading, p[1].autoLeading, p[1].leading]);", + ); + assert_eq!(out, vec![json!([14.4, 24, 24]), json!([true, false, 24])]); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading)).collect(), + _ => panic!("not text"), + }; + assert_eq!(leadings, vec![("first\n".into(), None), ("second".into(), Some(24.0))]); +} + +#[test] +fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() { + let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}'); + let db = vectorcraft_text::FontDb::global(); + let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c)); + if !covers(from) || covers(to) { + return; // Installed fonts of these names cover other characters. + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 50, "text": "a\u{180}c", "font": from})).unwrap(); + let pick = format!("var r = app.activeDocument.textFrames[0].textRange, f = app.textFonts.getByName('{to} Regular');"); + let e = failure(&mut s, &format!("{pick} r.textFont = f;")); + assert!(e.contains("textFont: the font has no glyph for 1 character, which keeps its font"), "{e}"); + // Characters the font can draw take it without an error. + let out = log(&mut s, &format!("{pick} r.characters[0].textFont = f; vc.log(r.characters[0].textFont.family);")); + assert_eq!(out, vec![json!(to)]); +} + +#[test] +fn turning_auto_leading_off_keeps_each_characters_leading() { + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 200})).unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id.0, "start": 1, "end": 2, "size": 24})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.autoLeading = false; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); + let leadings: Vec<(String, Option)> = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.leading.map(|l| (l * 1000.0).round() as i64))).collect(), + _ => panic!("not text"), + }; + let want = [("a", 14_400), ("b", 28_800), ("\n", 14_400), ("cd", 24_000)]; + assert_eq!(leadings, want.iter().map(|(t, l)| (t.to_string(), Some(*l))).collect::>()); + // Paragraphs and runs with the same leading take one command. + let (mut s, _) = doc_with("one\ntwo\nthree"); + let r = run(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;").unwrap(); + let calls: Vec<(Value, Value)> = r["slowestCommands"].as_array().unwrap().iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect(); + assert_eq!(calls, vec![(json!("text.setRangeStyle"), json!(1))]); + // Auto leading that a fixed leading cannot hold is refused before anything changes. + let (mut s, id) = doc_with("ab\ncd"); + s.execute("text.setFormat", &json!({"id": id.0, "start": 3, "end": 3, "autoLeading": 0})).unwrap(); + let before = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.autoLeading = false;"); + assert!(e.contains("autoLeading cannot be turned off"), "{e}"); + assert_eq!(undo_steps(&s), before); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_none())), + _ => panic!("not text"), + } +} + +#[test] +fn an_explicit_alignment_replaces_auto_alignment() { + let justify = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.para_at(0).justify, + _ => panic!("not text"), + }; + for (text, reads) in [("abc", "Justification.LEFT"), ("\u{5e9}\u{5dc}\u{5d5}\u{5dd}", "Justification.RIGHT")] { + let (mut s, id) = doc_with(text); + assert_eq!(justify(&s, id), Justify::Auto); + let before = undo_steps(&s); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.paragraphAttributes; vc.log(a.justification);\ + a.justification = Justification.LEFT; vc.log(a.justification);", + ); + assert_eq!(out, vec![json!(reads), json!("Justification.LEFT")], "{text}"); + assert_eq!(justify(&s, id), Justify::Left, "{text}"); + assert_eq!(undo_steps(&s), before + 1, "{text}"); + } + // Each paragraph on Auto reads by its own text. + let (mut s, _) = doc_with("abc\n\u{5e9}\u{5dc}\u{5d5}\u{5dd}\nd"); + let out = log( + &mut s, + "var p = app.activeDocument.textFrames[0].paragraphs; var j = function (i) { return p[i].paragraphAttributes.justification; }; vc.log([j(0), j(1), j(2)]);", + ); + assert_eq!(out, vec![json!(["Justification.LEFT", "Justification.RIGHT", "Justification.LEFT"])]); +} + +#[test] +fn a_stale_range_has_no_parent() { + let (mut s, id) = doc_with("abc"); + let source = format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'x'}}); r.parent;", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{e}"); +} + +#[test] +fn members_not_built_yet_throw_after_the_stale_check() { + let (mut s, id) = doc_with("abc"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].lines;"); + assert!(e.contains("TextFrame.lines is not available yet"), "{e}"); + let e = failure(&mut s, "var t = app.activeDocument.textFrames[0]; t.remove(); t.lines;"); + assert!(e.contains("Stale page item"), "{e}"); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.lines;"); + assert!(e.contains("TextRange.lines is not available yet"), "{e}"); + for member in ["r.lines", "r.start = 1"] { + let source = + format!("var r = app.activeDocument.textFrames[0].textRange; vc.run('text.setText', {{id: {}, text: 'other'}}); {member};", id.0); + let e = failure(&mut s, &source); + assert!(e.contains("Stale text range"), "{member}: {e}"); + } +} + +#[test] +fn text_fonts_list_and_assign_fonts_by_name() { + let (mut s, id) = doc_with("abc"); + let out = log( + &mut s, + "var f = app.textFonts, m = '';\ + try { f.getByName('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ + try { f.index('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[f.length - 1];\ + r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);", + ); + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!(true), json!(true), json!(true)]); + let family = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs[0].style.font_family.clone(), + _ => panic!("not text"), + }; + let listed = log(&mut s, "var f = app.textFonts; vc.log(f[f.length - 1].family);"); + assert_eq!(listed, vec![json!(family)]); +} + +#[test] +fn create_outline_and_conversions_return_the_new_objects() { + let (mut s, id) = doc_with("Hi"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], m = '';\ + try { t.convertAreaObjectToPointObject(); } catch (e) { m = e.message; } vc.log(m);\ + var a = t.convertPointObjectToAreaObject(); vc.log(a.kind);\ + var p = a.convertAreaObjectToPointObject(); vc.log(p.kind); vc.log(p.contents);\ + var g = p.createOutline(); vc.log(g.typename); vc.log(app.activeDocument.textFrames.length);", + ); + assert_eq!(out[0], json!("the text frame is not area type")); + assert_eq!(out[1..], [json!("TextType.AREATEXT"), json!("TextType.POINTTEXT"), json!("Hi"), json!("GroupItem"), json!(0)]); + assert!(s.active().unwrap().doc.node(id).is_none()); +} + +#[test] +fn text_members_refuse_objects_of_other_classes() { + let (mut s, _) = doc_with("abc"); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + assert!(e.contains("this is not a TextFrame"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); + assert!(e.contains("this is not a TextRange"), "{e}"); + let e = failure(&mut s, "var f = {}; f['\\u0000hostRef'] = ['TextFont', 0, 0]; app.activeDocument.textFrames[0].textRange.textFont = f;"); + assert!(e.contains("not plain data"), "{e}"); + // A font from an earlier run of a named engine is stale. + run(&mut s, "#targetengine keepfont\nvar held = app.textFonts[0];").unwrap(); + for member in ["held.family", "held.parent"] { + let e = failure(&mut s, &format!("#targetengine keepfont\n{member};")); + assert!(e.contains("Stale text font"), "{member}: {e}"); + } +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..c7e7000f13 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -81,7 +81,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection textFonts typename", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), @@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ + rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames typename \ views views= width", ), ("Layer.", "prototype"), @@ -121,12 +121,67 @@ const INSIDE: &[(&str, &str)] = &[ ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), + ( + "", + "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ + TextOrientation TextRange TextType Words", + ), + ("TextFrames.", "prototype"), + ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), + ("TextFrame.", "prototype"), + ( + "TextFrame.prototype.", + "anchor anchor= antialias antialias= characters columnCount columnCount= columnGutter columnGutter= constructor \ + contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ + insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ + opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ + rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \ + textSelection= words", + ), + ("TextRange.", "prototype"), + ( + "TextRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ + characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ + getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ + insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ + paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ + story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ + tracking tracking= typename underline underline= verticalScale verticalScale= words", + ), + ("Characters.", "prototype"), + ("Characters.prototype.", "constructor length parent typename"), + ("Words.", "prototype"), + ("Words.prototype.", "constructor length parent typename"), + ("Paragraphs.", "prototype"), + ("Paragraphs.prototype.", "constructor length parent typename"), + ("CharacterAttributes.", "prototype"), + ( + "CharacterAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphAttributes.", "prototype"), + ( + "ParagraphAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), + ("TextFonts.", "prototype"), + ("TextFonts.prototype.", "constructor getByName index length parent typename"), + ("TextFont.", "prototype"), + ("TextFont.prototype.", "constructor family name parent style typename"), + ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), + ("TextOrientation.", "HORIZONTAL VERTICAL"), + ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` /// and the page item types. const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ - PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; + PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's /// own API, and what `vc.run` does depends on the command it runs. diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..aedf2b0a74 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,52 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `Document.textFrames` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/) lists the document's type + objects in paint order, those inside groups included, with `length`, `[i]`, `index(key)`, `getByName(name)` and + `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both + with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn + a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` + value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not + available yet. A `TextFrame` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, + `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, + `createOutline()` (Type › Create Outlines, giving the group of outlines), `convertPointObjectToAreaObject()` and + `convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has + `contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`, + `words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and + `remove()`, and the character attributes themselves. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to + 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and + `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, + set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, + or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, + `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/) lists every style of every family in the font menu, with + `length`, `[i]`, `index(key)` and `getByName(name)`, which takes a PostScript name or the family and style joined by a + space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`, + `TextOrientation` and `Justification` hold strings such as `"Justification.CENTER"`. + VectorCraft's own rules: offsets and lengths count UTF-16 code units, as a JavaScript string does, and an offset + inside a surrogate pair takes in its whole character; one item of `characters` is one code point. `contents` gives a + paragraph break as `\r` and a forced line break as `\u0003`, and takes `\r`, `\n` or `\r\n` for a paragraph break. A + word is a run of characters that are not white space; a range's `words` and `paragraphs` are the whole words and + paragraphs it touches, a paragraph's break belonging to it; the empty paragraph after a break at the end of the text + belongs only to an empty range there. A range keeps its place while the script edits the frame + through these objects: an edit before it moves it, an edit over it shrinks it, and an insertion at one of its ends + joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` + or an undo changed it, a range made before throws `Stale text range`; a change that was reversed before that read + leaves the text as the range knew it, and the range keeps working. A range made before the frame's last 100,000 + edits through these objects throws `Stale text range` too. A character attribute + read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting + `autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its + own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters + that take the same leading; when one of those values is outside 0.1 to 5000 pt, it throws + and changes nothing. A paragraph attribute reads the first paragraph the range touches and sets every one of them. A value a range already + has runs no command. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws + when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the + font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws + `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and + `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and + `orientation` cannot be set yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..f6a957cad0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From efe9c3430446a89323439000f8f9933ab5b302ee Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:11:55 -0800 Subject: [PATCH 025/104] Docs: text ranges keep up to 100,000 edits and drop the older half past that docs/mcp.md said a range made before the frame's last 100,000 edits goes stale. The record keeps up to 100,000 edits and, when it grows past that, drops the older half, so a range goes stale only when it was made before the newest dropped edit (text.rs MAX_EDITS and record). --- docs/mcp.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index aedf2b0a74..ea5b9028af 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2713,8 +2713,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot through these objects: an edit before it moves it, an edit over it shrinks it, and an insertion at one of its ends joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` or an undo changed it, a range made before throws `Stale text range`; a change that was reversed before that read - leaves the text as the range knew it, and the range keeps working. A range made before the frame's last 100,000 - edits through these objects throws `Stale text range` too. A character attribute + leaves the text as the range knew it, and the range keeps working. These objects keep a record of up to 100,000 of the + frame's edits; when it grows past that, they drop the older half of it, and a range made before the newest dropped + edit throws `Stale text range` too. A character attribute read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting `autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters From 59facefcd2b5037610cbace1bb8c06e443bb9dd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:25:31 -0800 Subject: [PATCH 026/104] Scripts: doScript checks a Batch step's commands before any step runs An action step that runs action.batch plays its own list of commands on each file. app.doScript now checks those commands with the action's steps, so a stop, a command a script may not run or a command the engine does not have among them throws an error naming the step (as 2.2) before any step of the action runs. --- crates/engine/src/script/actions.rs | 31 ++++++++++++++++++----- crates/engine/src/tests/script_actions.rs | 6 +++++ docs/mcp.md | 3 ++- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 16c072cebd..a0fabf2103 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -15,7 +15,8 @@ //! and throws an error that names the step and the action, while the steps before it stay done. //! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine //! does not have (a View menu step, or one that plays an action), and a stop throw before any step -//! runs. An action cannot play another action, so it cannot play itself. +//! runs, as does such a command among those an `action.batch` step plays. An action cannot play +//! another action, so it cannot play itself. //! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it //! changes nothing. @@ -229,13 +230,12 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Every step is checked before the first runs, so a step that cannot run leaves the documents as // they were. for s in &p.steps { - let refused = s.id == STOP_STEP || refused_to_scripts(&s.id) || crate::find_command(&s.id).is_none(); - if refused { - let (place, name, id) = (&s.place, shown(&p.name), shown(&s.id)); - return Err(HostError::Error(if s.id == STOP_STEP { + if let Some((place, id)) = refused_step(s) { + let name = shown(&p.name); + return Err(HostError::Error(if id == STOP_STEP { format!("step {place} of “{name}” is a stop, which a script cannot wait at") } else { - format!("step {place} of “{name}” runs `{id}`, which a script cannot run") + format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id)) })); } } @@ -263,6 +263,25 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { Ok(Data::Undefined) } +/// The place and command of the first command step `s` would run that a script may not run: the +/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the +/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the +/// engine does not have are refused. +fn refused_step(s: &Step) -> Option<(String, String)> { + let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none(); + if refused(&s.id) { + return Some((s.place.clone(), s.id.clone())); + } + if s.id != "action.batch" { + return None; + } + let commands = s.params.get("commands").and_then(Value::as_array)?; + commands.iter().enumerate().find_map(|(k, c)| { + let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned())) + }) +} + /// `params` of step `id`, with the active artboard of the active document added as a /// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for /// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 02ee9f5957..4fbcd55751 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -146,6 +146,12 @@ fn steps_a_script_may_not_run_stop_the_action_before_any_step() { let m = caught(&mut s, "app.doScript('B', 'Set')", &batch); assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}"); assert_eq!(objects(&s), 0); + // So is one among the commands a Batch step plays on each file, before the steps ahead of it run. + let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}}); + let batch = set(&[("F", vec![rect(0), files])]); + let m = caught(&mut s, "app.doScript('F', 'Set')", &batch); + assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}"); + assert_eq!(objects(&s), 0); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index cda10102c0..6b507eab99 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2694,7 +2694,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot their exact names, and a name that matches no action or more than one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any - step runs, so an action cannot play itself. + step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an + action cannot play itself. Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an From c691279f722897fc18c241729e7584bddeee9148 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:50:30 -0800 Subject: [PATCH 027/104] Scripts: covered text ranges hold the new text, and text members report stale ranges - An edit over the end of a text range takes that end to the end of the edit's new text, so a range the edit covers holds the new text instead of becoming empty. - The edit record keeps the frame's last 100,000 edits and drops only the oldest one past that. - A numeric leading set on characters with auto leading turns auto leading off even when it equals the auto value. - typename of a stale text range, its collections and attribute objects throws Stale text range, as the other members do; TextFrames and TextFont check their document and run first. - createOutline() gives null when the type has nothing to outline, instead of throwing after the command removed the frame. - New frames, outlines and conversions read the new id from the command's JSON result, so ids above 2^53 stay exact. - Character attribute reads look up only the first style of the range. - The font assignment test picks a font that draws "abc". Docs: docs/mcp.md, docs/gaps.md (G6). --- crates/engine/src/script/dom/text.rs | 160 +++++++++++++++++-------- crates/engine/src/tests/script_text.rs | 100 ++++++++++++++-- docs/gaps.md | 7 +- docs/mcp.md | 19 +-- 4 files changed, 217 insertions(+), 69 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index fb2bd54daa..a6dacdce55 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -15,15 +15,19 @@ //! - A word is a run of characters that are not white space. A paragraph ends after its break, and //! a range's `words` and `paragraphs` are the whole words and paragraphs it touches. //! - A range keeps its place while the script edits the frame through the object model: an edit -//! before it moves it, an edit over it shrinks it to the edit, and an insertion at one of its -//! ends joins it. When the frame's text changes in any other way (`vc.run`, an undo), every -//! range made before is stale and throws `Stale text range`. +//! before it moves it, an edit over one of its ends takes that end to the edge of the edit's new +//! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins +//! it. When a member finds the frame's text different from the text the model last saw, because +//! `vc.run` or an undo changed it, every range made before is stale and throws +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. +//! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no +//! longer kept is stale. //! - A character attribute read on a range whose characters differ gives the first character's //! value; set on an empty range it changes nothing. A paragraph attribute reads the first //! paragraph the range touches and sets every one of them. use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use std::sync::{Arc, Weak}; @@ -148,7 +152,21 @@ struct Log { index: Rc, stamp: u64, floor: u64, - edits: Vec, + edits: VecDeque, +} + +impl Log { + /// Records an edit the model made: `removed` units at `at` replaced by `inserted` units. Past + /// [`MAX_EDITS`] the oldest edit is dropped, and ranges made before it go stale. + fn push(&mut self, at: usize, removed: usize, inserted: usize) { + self.stamp += 1; + self.edits.push_back(Edit { stamp: self.stamp, at, removed, inserted }); + if self.edits.len() > MAX_EDITS + && let Some(dropped) = self.edits.pop_front() + { + self.floor = dropped.stamp; + } + } } /// A document's uid, the document, and the ids of its type objects then. @@ -204,7 +222,7 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc { - let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: Vec::new() }; + let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: VecDeque::new() }; frames.insert(key, l); } } @@ -232,7 +250,7 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } let (mut s, mut e) = (r.start, r.end); let from = l.edits.partition_point(|x| x.stamp <= r.stamp); - for x in &l.edits[from..] { + for x in l.edits.range(from..) { let moved = |v: usize| v - x.removed + x.inserted; s = if s <= x.at { s @@ -241,12 +259,13 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc, usize, usize, u } else { x.at }; - e = if e < x.at { + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { e } else if e >= x.at + x.removed { moved(e) } else { - x.at + x.at + x.inserted }; } let len = index.len(); @@ -268,15 +287,10 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser && now.get(a..a + inserted.len()) == Some(inserted); let mut frames = h.dom.text.frames.borrow_mut(); let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; - l.stamp += 1; if expected { - l.edits.push(Edit { stamp: l.stamp, at, removed, inserted: inserted.encode_utf16().count() }); - if l.edits.len() > MAX_EDITS { - let keep = l.edits.split_off(MAX_EDITS / 2); - l.floor = keep.first().map_or(l.stamp, |x| x.stamp - 1); - l.edits = keep; - } + l.push(at, removed, inserted.encode_utf16().count()); } else { + l.stamp += 1; l.floor = l.stamp; l.edits.clear(); } @@ -460,17 +474,10 @@ fn paragraph_attributes(h: &Host, a: &[Data]) -> Answer { sub(h, a, "ParagraphAttributes") } -/// The id a command's result gives under `ids` (the first) or `id`. -fn result_id(d: &Data) -> Option { - let Data::Object(o) = d else { return None }; - let n = |v: &Data| if let Data::Number(n) = v { whole(*n) } else { None }; - o.iter() - .find_map(|(k, v)| match (k.as_str(), v) { - ("ids", Data::Array(ids)) => ids.first().and_then(n), - ("id", v) => n(v), - _ => None, - }) - .map(NodeId) +/// The id a command's result, as the command gave it, holds under `ids` (the first) or `id`. It is +/// read from the JSON, where an id above 2^53 is still exact. +fn result_id(v: &Value) -> Option { + v.get("ids").and_then(|ids| ids.get(0)).or_else(|| v.get("id")).and_then(Value::as_u64).map(NodeId) } fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { @@ -480,14 +487,18 @@ fn new_ref(h: &Host, doc: Doc, id: Option) -> Answer { Ok(item_ref(h, st, id)) } -/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines. +/// `createOutline()`: Type › Create Outlines for the frame alone. → the group of outlines, or +/// `null` when the type has nothing to outline and the command removed it. fn frame_outline(h: &Host, a: &[Data]) -> Answer { let item = this_frame(h, a)?; - let r = on_doc(h, item.doc.uid, true, |h| { + let (_, r) = on_doc(h, item.doc.uid, true, |h| { command(h, "select.set", &json!({"ids": [item.id.0]}))?; - command(h, "type.createOutlines", &json!({})) + super::command_value(h, "type.createOutlines", &json!({})) })?; - new_ref(h, item.doc, result_id(&r)) + match result_id(&r) { + Some(id) => new_ref(h, item.doc, Some(id)), + None => Ok(Data::Null), + } } /// Converts area type to point type (`area` false) or point type to area type. @@ -502,7 +513,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer { Some(true) => {} } let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" }; - let r = edit_item(h, item, id, &json!({"ids": [item.id.0]}))?; + let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?; new_ref(h, item.doc, result_id(&r).or(Some(item.id))) } @@ -658,8 +669,9 @@ const ATTRS: [(&str, Attr); 11] = [ /// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with /// the paragraph they are in: one entry for each run and paragraph the range covers. For an empty -/// range, the style of the character before it, or of the first one. -fn styles_in(t: &TextObject, a: usize, b: usize) -> std::result::Result, HostError> { +/// range, the style of the character before it, or of the first one. With `first`, only the first +/// entry. +fn styles_in(t: &TextObject, a: usize, b: usize, first: bool) -> std::result::Result, HostError> { let mut out = Vec::new(); let (mut at, mut para) = (0, 0); let effective = |s: &CharStyle| t.effective_char_style(s).ok_or_else(|| HostError::Error("the text's transform cannot be measured".into())); @@ -677,6 +689,9 @@ fn styles_in(t: &TextObject, a: usize, b: usize) -> std::result::Result Answer { let (ba, bb) = (index.byte(s, false), index.byte(e, true)); with_doc(h, r.item.doc, |_, st| { let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - Ok(styles_in(t, ba, bb)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) + Ok(styles_in(t, ba, bb, true)?.first().map_or(Data::Undefined, |(st, p)| attr_value(h, attr, t, st, *p))) }) } @@ -851,10 +866,12 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { let (ba, bb) = (index.byte(s, false), index.byte(e, true)); let (param, unchanged, fixed) = with_doc(h, r.item.doc, |_, st| { let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let styles = styles_in(t, ba, bb)?; + let styles = styles_in(t, ba, bb, false)?; let first = styles.first().map(|(s, p)| (s.clone(), *p)).unwrap_or_else(|| (CharStyle::default(), 0)); let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?; - let unchanged = ba == bb || styles.iter().all(|(st, p)| same(&attr_value(h, attr, t, st, *p), &wants)); + // A leading set on characters with auto leading fixes it even where auto gives that value. + let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants); + let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p)); let fixed = match (attr, &wants) { (Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?), _ => None, @@ -1132,7 +1149,8 @@ fn vertical_of(d: &Data) -> std::result::Result { /// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`. fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer { let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?; - let r = on_doc(h, doc.uid, true, |h| command(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; + let (_, r) = + on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?; new_ref(h, doc, result_id(&r)) } @@ -1164,8 +1182,8 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { let orientation = if on_path { 4 } else { 2 }; let vertical = vertical_of(arg(a, orientation))?; let mode = if on_path { "onPath" } else { "area" }; - let r = - on_doc(h, doc.uid, true, |h| command(h, "text.createInPath", &json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical})))?; + let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); + let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; new_ref(h, doc, result_id(&r)) } @@ -1311,6 +1329,37 @@ fn font_parent(h: &Host, a: &[Data]) -> Answer { // ---- classes ---- +fn range_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_range(h, a)?)?; + Ok(text("TextRange")) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(PARTS.iter().find(|(_, p)| *p == part).map_or("Characters", |(c, _)| c))) +} + +fn char_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["CharacterAttributes"])?)?; + Ok(text("CharacterAttributes")) +} + +fn para_attrs_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, span_of(h, arg(a, 0), &["ParagraphAttributes"])?)?; + Ok(text("ParagraphAttributes")) +} + +fn frames_typename(h: &Host, a: &[Data]) -> Answer { + frames_doc(h, a)?; + Ok(text("TextFrames")) +} + +fn font_typename(h: &Host, a: &[Data]) -> Answer { + font_of(h, arg(a, 0))?; + Ok(text("TextFont")) +} + /// A member listed on the help pages that a script cannot set yet. Assigning it throws, after the /// read's own checks of `this`. fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static str) -> HostMember { @@ -1424,7 +1473,7 @@ pub(super) fn classes(l: &Link) -> Vec { .map(|m| super::later(l, "TextFrame", m)), ); let mut range = named(vec![ - ("typename", typename_of("TextRange")), + ("typename", get(l, range_typename)), ("parent", get(l, range_parent)), ("contents", property(l, range_contents, range_set_contents)), ("start", read_only(l, range_start, "TextRange", "start")), @@ -1466,13 +1515,13 @@ pub(super) fn classes(l: &Link) -> Vec { class( name, None, - named(vec![("typename", typename_of(name)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), Some(function(l, part_at)), ) }; - let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + let mut chars = named(vec![("typename", get(l, char_attrs_typename))]); chars.extend(attr_members(l)); - let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); vec![ class("TextFrame", Some("PageItem"), frame, None), @@ -1486,7 +1535,7 @@ pub(super) fn classes(l: &Link) -> Vec { "TextFrames", None, named(vec![ - ("typename", typename_of("TextFrames")), + ("typename", get(l, frames_typename)), ("length", get(l, frames_length)), ("parent", get(l, frames_parent)), ("index", method(l, frames_index)), @@ -1515,7 +1564,7 @@ pub(super) fn classes(l: &Link) -> Vec { "TextFont", None, named(vec![ - ("typename", typename_of("TextFont")), + ("typename", get(l, font_typename)), ("name", get(l, font_name)), ("family", get(l, font_family)), ("style", get(l, font_style)), @@ -1528,7 +1577,24 @@ pub(super) fn classes(l: &Link) -> Vec { #[cfg(test)] mod tests { - use super::{Index, touched}; + use std::collections::VecDeque; + use std::rc::Rc; + use std::sync::Weak; + + use super::{Index, Log, MAX_EDITS, touched}; + + #[test] + fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { + let mut l = Log { doc: Weak::new(), index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + for _ in 0..MAX_EDITS { + l.push(0, 0, 1); + } + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 0)); + l.push(0, 0, 1); + // Only the first edit is dropped: a range made after it still moves through every later edit. + assert_eq!((l.edits.len(), l.floor), (MAX_EDITS, 1)); + assert_eq!(l.edits.front().map(|x| x.stamp), Some(2)); + } #[test] fn index_counts_utf16_units_and_splits_words_and_paragraphs() { diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 6d9f6614f1..10f3d2f3f1 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -143,6 +143,19 @@ fn ranges_follow_model_edits_and_go_stale_after_other_edits() { assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); } +#[test] +fn a_range_an_edit_covers_holds_the_edits_new_text() { + let (mut s, _) = doc_with("abc"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], first = t.characters[0], r = t.characters[1];\ + t.characters[2].contents = 'ZZ'; vc.log([first.contents, r.contents]);\ + t.contents = 'XY'; vc.log([r.contents, r.start, r.length, first.contents]);", + ); + // A range that ends where an edit starts keeps its end; one inside the edit takes the new text. + assert_eq!(out, vec![json!(["a", "b"]), json!(["XY", 0, 2, "XY"])]); +} + #[test] fn bad_attribute_values_are_refused_without_a_change() { let (mut s, id) = doc_with("abc"); @@ -178,6 +191,23 @@ fn setting_the_value_a_range_has_records_no_undo_step() { assert_eq!(undo_steps(&s), before); } +#[test] +fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() { + let (mut s, id) = doc_with("abc"); + let before = undo_steps(&s); + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = r.leading; vc.log([r.autoLeading, r.leading]);"); + assert_eq!(out, vec![json!([false, 14.4])]); + assert_eq!(undo_steps(&s), before + 1); + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => assert!(t.runs.iter().all(|r| r.style.leading.is_some_and(|l| (l - 14.4).abs() < 1e-9)), "{:?}", t.runs), + _ => panic!("not text"), + } + // A fixed leading set to its own value is still no change. + let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.leading = 14.4; vc.log(r.autoLeading);"); + assert_eq!(out, vec![json!(false)]); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn paragraph_attributes_set_the_paragraphs_a_range_touches() { let (mut s, _) = doc_with("first\nsecond"); @@ -321,6 +351,21 @@ fn a_stale_range_has_no_parent() { assert!(e.contains("Stale text range"), "{e}"); } +#[test] +fn a_stale_range_and_its_collections_have_no_typename() { + let (mut s, id) = doc_with("abc"); + let source = format!( + "var r = app.activeDocument.textFrames[0].textRange, all = [r, r.characters, r.words, r.paragraphs, r.characterAttributes, r.paragraphAttributes];\ + var names = []; for (var i = 0; i < all.length; i++) names.push(all[i].typename); vc.log(names);\ + vc.run('text.setText', {{id: {}, text: 'other'}}); var m = [];\ + for (var i = 0; i < all.length; i++) {{ try {{ m.push(all[i].typename); }} catch (e) {{ m.push(e.message); }} }} vc.log(m);", + id.0 + ); + let out = log(&mut s, &source); + assert_eq!(out[0], json!(["TextRange", "Characters", "Words", "Paragraphs", "CharacterAttributes", "ParagraphAttributes"])); + assert_eq!(out[1], json!(vec!["Stale text range"; 6])); +} + #[test] fn members_not_built_yet_throw_after_the_stale_check() { let (mut s, id) = doc_with("abc"); @@ -340,23 +385,31 @@ fn members_not_built_yet_throw_after_the_stale_check() { #[test] fn text_fonts_list_and_assign_fonts_by_name() { + // The last font in the menu that draws "abc", so Missing Glyph Protection keeps no character. + let db = vectorcraft_text::FontDb::global(); + let listed: Vec<(String, String)> = db.menu_family_list().iter().flat_map(|f| db.styles(f).into_iter().map(move |st| (f.clone(), st))).collect(); + let covers = |(f, st): &&(String, String)| db.face(f, st).is_some_and(|face| "abc".chars().all(|c| face.covers(c))); + let Some((pos, (family, style))) = listed.iter().enumerate().rev().find(|(_, fs)| covers(fs)) else { + return; // No installed font draws "abc". + }; let (mut s, id) = doc_with("abc"); let out = log( &mut s, - "var f = app.textFonts, m = '';\ - try { f.getByName('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ - try { f.index('No Such Font Anywhere'); } catch (e) { m = e.message; } vc.log(m);\ - vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[f.length - 1];\ - r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ - vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);", + &format!( + "var f = app.textFonts, m = '';\ + try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\ + vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\ + vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\ + vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);" + ), ); - assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!(true), json!(true), json!(true)]); - let family = match &s.active().unwrap().doc.node(id).unwrap().kind { - NodeKind::Text(t) => t.runs[0].style.font_family.clone(), + assert_eq!(out, vec![json!("Not found"), json!("Not found"), json!(true), json!([family, style]), json!(true), json!(true), json!(true)]); + let set = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (t.runs[0].style.font_family.clone(), t.runs[0].style.font_style.clone()), _ => panic!("not text"), }; - let listed = log(&mut s, "var f = app.textFonts; vc.log(f[f.length - 1].family);"); - assert_eq!(listed, vec![json!(family)]); + assert_eq!(&set, &(family.clone(), style.clone())); } #[test] @@ -375,6 +428,31 @@ fn create_outline_and_conversions_return_the_new_objects() { assert!(s.active().unwrap().doc.node(id).is_none()); } +#[test] +fn outlining_type_with_nothing_to_outline_gives_null() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = + log(&mut s, "var d = app.activeDocument, t = d.textFrames.add(); var g = t.createOutline(); vc.log([g === null, d.textFrames.length]);"); + assert_eq!(out, vec![json!([true, 0])]); +} + +#[test] +fn type_made_with_a_large_id_is_the_new_type() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log( + &mut s, + "var d = app.activeDocument, a = d.textFrames.add(), b = d.textFrames.pointText([5, 5]); b.contents = 'second';\ + vc.log([a === b, a.contents, b.createOutline().typename]);", + ); + assert_eq!(out, vec![json!([false, "", "GroupItem"])]); + assert_eq!(plain(&s, NodeId(big)), ""); +} + #[test] fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..47a1680f6e 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,9 +807,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the - other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads + of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open + documents, new documents, each document's selection and its page items, its text frames with their text ranges and + character and paragraph attributes, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index ea5b9028af..bd7785031b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2689,7 +2689,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot available yet. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, - `createOutline()` (Type › Create Outlines, giving the group of outlines), `convertPointObjectToAreaObject()` and + `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to + outline and the command removes it), `convertPointObjectToAreaObject()` and `convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has `contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`, `words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and @@ -2710,18 +2711,20 @@ app through the global object `vc`, and writes to the Script Console and runs ot word is a run of characters that are not white space; a range's `words` and `paragraphs` are the whole words and paragraphs it touches, a paragraph's break belonging to it; the empty paragraph after a break at the end of the text belongs only to an empty range there. A range keeps its place while the script edits the frame - through these objects: an edit before it moves it, an edit over it shrinks it, and an insertion at one of its ends - joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` - or an undo changed it, a range made before throws `Stale text range`; a change that was reversed before that read - leaves the text as the range knew it, and the range keeps working. These objects keep a record of up to 100,000 of the - frame's edits; when it grows past that, they drop the older half of it, and a range made before the newest dropped - edit throws `Stale text range` too. A character attribute + through these objects: an edit before it moves it, an edit over one of its ends takes that end to the edge of the + edit's new text, so a range the edit covers holds the new text, and an insertion at one of its ends joins it. When a + member finds the frame's text different from the text these objects last saw, because `vc.run` or an undo changed + it, a range made before throws `Stale text range`, and so does its `typename`; a change that was reversed before + that read leaves the text as the range knew it, and the range keeps working. These objects keep a record of the + frame's last 100,000 edits, and a range made before an edit that is no longer in that record throws + `Stale text range` too. A character attribute read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting `autoLeading` to false gives each character with auto leading the leading it is set with at that moment, from its own size and its paragraph's auto leading percentage, with one `text.setRangeStyle` for each stretch of characters that take the same leading; when one of those values is outside 0.1 to 5000 pt, it throws and changes nothing. A paragraph attribute reads the first paragraph the range touches and sets every one of them. A value a range already - has runs no command. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws + has runs no command; a `leading` set on characters with auto leading turns their auto leading off even when it equals + the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and From b7893282bad1d8e003249f2d49bf606b6e61f3a1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:28:30 -0800 Subject: [PATCH 028/104] Scripts: text ranges made before File > Revert go stale A text range kept working after file.revert when the file read back held the same text, because the frame's record compared only the text. The record now keeps the document's revert count, and a range made before a revert throws Stale text range. --- crates/engine/src/script/dom/text.rs | 32 ++++++++++++++++++-------- crates/engine/src/tests/script_text.rs | 19 +++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 44 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index a6dacdce55..c3ca9d1dbe 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -19,7 +19,9 @@ //! text, so a range the edit covers holds the new text, and an insertion at one of its ends joins //! it. When a member finds the frame's text different from the text the model last saw, because //! `vc.run` or an undo changed it, every range made before is stale and throws -//! `Stale text range`; a change reversed before that read leaves the ranges as they were. +//! `Stale text range`; a change reversed before that read leaves the ranges as they were. After +//! File › Revert every range made before is stale, even when the file read back holds the same +//! text. //! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no //! longer kept is stale. //! - A character attribute read on a range whose characters differ gives the first character's @@ -145,10 +147,12 @@ struct Edit { inserted: usize, } -/// What the object model knows of one frame's text: the document it was read from, the text, the -/// edits made through the model, and the oldest range generation still valid. +/// What the object model knows of one frame's text: the document it was read from and its revert +/// count then, the text, the edits made through the model, and the oldest range generation still +/// valid. struct Log { doc: Weak, + reverts: u64, index: Rc, stamp: u64, floor: u64, @@ -204,25 +208,34 @@ fn same_text(t: &TextObject, s: &str) -> bool { rest.is_empty() } -/// The frame's index and its generation now, read again when its document changed. +/// The frame's index and its generation now, read again when its document changed. After File › +/// Revert every earlier range goes stale, even when the file read back holds the same text. fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc, u64), HostError> { let t = text_of(st, id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let mut frames = h.dom.text.frames.borrow_mut(); let key = (st.uid, id.0); let now = Arc::as_ptr(&st.doc); match frames.get_mut(&key) { - Some(l) if std::ptr::eq(l.doc.as_ptr(), now) => {} + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} Some(l) => { - if !same_text(t, &l.index.text) { + if l.reverts != st.reverts || !same_text(t, &l.index.text) { l.stamp += 1; l.floor = l.stamp; l.edits.clear(); l.index = Rc::new(Index::new(t.plain_text())); } l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; } None => { - let l = Log { doc: Arc::downgrade(&st.doc), index: Rc::new(Index::new(t.plain_text())), stamp: 0, floor: 0, edits: VecDeque::new() }; + let l = Log { + doc: Arc::downgrade(&st.doc), + reverts: st.reverts, + index: Rc::new(Index::new(t.plain_text())), + stamp: 0, + floor: 0, + edits: VecDeque::new(), + }; frames.insert(key, l); } } @@ -287,7 +300,7 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser && now.get(a..a + inserted.len()) == Some(inserted); let mut frames = h.dom.text.frames.borrow_mut(); let l = frames.get_mut(&(st.uid, item.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; - if expected { + if expected && l.reverts == st.reverts { l.push(at, removed, inserted.encode_utf16().count()); } else { l.stamp += 1; @@ -296,6 +309,7 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser } l.index = Rc::new(Index::new(now)); l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; Ok(()) }) } @@ -1585,7 +1599,7 @@ mod tests { #[test] fn the_edit_log_keeps_the_last_edits_and_drops_only_older_ones() { - let mut l = Log { doc: Weak::new(), index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; + let mut l = Log { doc: Weak::new(), reverts: 0, index: Rc::new(Index::new(String::new())), stamp: 0, floor: 0, edits: VecDeque::new() }; for _ in 0..MAX_EDITS { l.push(0, 0, 1); } diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 10f3d2f3f1..36dff46fa0 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -143,6 +143,25 @@ fn ranges_follow_model_edits_and_go_stale_after_other_edits() { assert_eq!(log(&mut s, &source), vec![json!(["two", 4])]); } +#[test] +fn ranges_made_before_file_revert_go_stale_even_when_the_text_is_the_same() { + let (mut s, _) = doc_with("one two"); + let path = std::env::temp_dir().join(format!("vc-text-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var now = app.activeDocument.textFrames[0];\ + vc.log(now.contents); try { vc.log(r.contents); } catch (e) { vc.log(e.message); }\ + vc.log(now.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!("one two"), "the reverted file holds the same text"); + assert!(out[1].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[2], json!("two"), "a range made after the revert reads the reverted text"); +} + #[test] fn a_range_an_edit_covers_holds_the_edits_new_text() { let (mut s, _) = doc_with("abc"); diff --git a/docs/mcp.md b/docs/mcp.md index bd7785031b..a75c5386f5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2715,7 +2715,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot edit's new text, so a range the edit covers holds the new text, and an insertion at one of its ends joins it. When a member finds the frame's text different from the text these objects last saw, because `vc.run` or an undo changed it, a range made before throws `Stale text range`, and so does its `typename`; a change that was reversed before - that read leaves the text as the range knew it, and the range keeps working. These objects keep a record of the + that read leaves the text as the range knew it, and the range keeps working. After `file.revert`, a range made + before throws `Stale text range` even when the file read back holds the same text. These objects keep a record of the frame's last 100,000 edits, and a range made before an edit that is no longer in that record throws `Stale text range` too. A character attribute read on characters that differ gives the first one's value, and set on an empty range it changes nothing. Setting From fdad498dbc15f22757be41cc64653cff9910a37b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:46:59 -0800 Subject: [PATCH 029/104] Scripts: doScript keeps the run's artboard picks and a batch's artboard - The Artboard tool's selection as script.run starts is kept for the steps app.doScript plays: the run gives the tool fresh state, which dropped it, so a paste or Fit to Artwork Bounds step acted on the active artboard only. - A step of a command.batch step that names its artboard acts on that artboard, past the last one the last, as command.batch gives it. - The app leaves out every action of a set that shares a name with an action it cannot pass, so that name is never one a script can play. - The host name check lists doScript, loadAction and unloadAction. --- crates/engine/src/script/actions.rs | 58 ++++++++++---- crates/engine/src/script/mod.rs | 8 ++ crates/engine/src/tests/script_actions.rs | 75 ++++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/ui-egui/src/panels/actions.rs | 43 ++++++++++- docs/mcp.md | 10 ++- 6 files changed, 174 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index a0fabf2103..b4a7a743a3 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -52,13 +52,14 @@ pub struct Playable { /// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a /// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and -/// their size as JSON. +/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names. #[derive(Clone, Debug)] struct Step { place: String, id: String, params: Value, bytes: u64, + artboard: Option, } /// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the @@ -100,6 +101,9 @@ pub fn parse(v: Option<&Value>) -> Result, String> { let (id, params) = command_of(s, &at)?; match params.get("commands") { Some(Value::Array(inner)) if id == "command.batch" => { + // The batch's `artboard`, for its steps that act on the active artboard, as + // `command.batch` reads it. + let artboard = params.get("artboard").and_then(Value::as_u64); for (k, c) in inner.iter().enumerate() { let at = format!("{at}.params.commands[{k}]"); let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; @@ -107,11 +111,11 @@ pub fn parse(v: Option<&Value>) -> Result, String> { if id == "command.batch" { return Err(format!("{at} is a command.batch inside a command.batch")); } - steps.push(step(format!("{place}.{}", k + 1), id, params)); + steps.push(step(format!("{place}.{}", k + 1), id, params, artboard)); } } _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), - _ => steps.push(step(place, id, params)), + _ => steps.push(step(place, id, params, None)), } if steps.len() > MAX_ACTION_STEPS { return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); @@ -167,9 +171,9 @@ fn command_of(o: &Map, at: &str) -> Result<(String, Value), Strin Ok((id, params)) } -fn step(place: String, id: String, params: Value) -> Step { +fn step(place: String, id: String, params: Value, artboard: Option) -> Step { let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); - Step { place, id, params, bytes } + Step { place, id, params, bytes, artboard } } /// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters @@ -248,7 +252,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { h.charge_call(16 + s.id.len() as u64 + s.bytes)?; // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. - let params = on_active_artboard(&h.session.borrow(), &h.active_artboards, &s.id, &s.params); + let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); h.session.borrow_mut().set_replaying(outer); @@ -289,16 +294,24 @@ fn refused_step(s: &Step) -> Option<(String, String)> { /// run started, which the view keeps), past the last artboard the last one, as the view shows it /// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While /// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its -/// `indices` instead, and a paste step gets none (it pastes on them). A paste step in a document -/// without artboards, or one that names `artboards`, and a Fit to Artwork Bounds step that names -/// `indices`, get none. A key the step gives is kept. -pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: &str, params: &Value) -> Value { +/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh +/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the +/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork +/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the +/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch` +/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past +/// the last artboard the last one, and none in a document without artboards, as `command.batch` +/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit +/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value { let mut params = params.clone(); let Some(st) = s.active() else { return params }; let n = st.doc.artboards.len(); - let active = match start.iter().find(|(uid, _)| *uid == st.uid) { - Some((_, i)) => (*i).min(n.saturating_sub(1)), - None => super::dom::active_artboard(st), + let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) { + (Some(_), _) if n == 0 => return params, + (Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)), + (None, Some((_, i))) => (*i).min(n.saturating_sub(1)), + (None, None) => super::dom::active_artboard(st), }; let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); let fit_art = id == "artboard.fitToArt"; @@ -314,10 +327,27 @@ pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: return params; } let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; - if picks.is_empty() { + let kept: Vec = match start.picks { + Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => { + list.iter().copied().filter(|i| *i < n).collect() + } + _ => Vec::new(), + }; + if kept.len() >= 2 { + p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept)); + } else if picks.is_empty() { p.insert(key.into(), json!(active)); } else if fit_art { p.insert("indices".into(), json!(picks)); } params } + +/// What [`on_active_artboard`] reads besides the session: the index of each open document's active +/// artboard as the run started, by document uid; the Artboard tool's selection as the run started, +/// with its document's uid; and the `artboard` a step's recorded `command.batch` names. +pub(crate) struct Start<'a> { + pub active: &'a [(u64, usize)], + pub picks: Option<&'a (u64, Vec)>, + pub batch: Option, +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 770934ce98..f2eeaa57ee 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -810,6 +810,10 @@ struct Host { /// The index of each open document's active artboard as the run starts, by document uid. The /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, + /// The artboards the Artboard tool had selected in the active document as the run starts (two or + /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the + /// steps `app.doScript` plays read them here. + artboard_picks: Option<(u64, Vec)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1963,6 +1967,9 @@ impl Session { if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); } + // The Artboard tool's selection, which the fresh tool state below drops. + let picks = cmd::artboard_tool_picks(self); + let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); @@ -2075,6 +2082,7 @@ impl Session { dom: dom::State::default(), actions: request.actions, active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), + artboard_picks, }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 4fbcd55751..1432b8671b 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -262,6 +262,31 @@ fn steps_act_on_the_artboard_active_as_they_run() { assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); } +/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, +/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. +#[test] +fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 1); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let mut own = align.clone(); + own["params"]["artboard"] = json!(1); + let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}}); + let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "app.doScript('First', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "the batch's artboard 0"); + log_with(&mut s, "app.doScript('Past', 'Set');", &actions); + assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one"); + log_with(&mut s, "app.doScript('Own', 'Set');", &actions); + assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it"); +} + /// The active artboard a step gets is the index it had as the run started: after a step deletes an /// artboard before it, the artboard now at that index, as the view shows it. #[test] @@ -269,7 +294,8 @@ fn steps_keep_the_active_artboards_index() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); let uid = s.active().unwrap().uid; - let add = |s: &Session| script::actions::on_active_artboard(s, &[(uid, 1)], "object.align", &json!({})); + let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None }; + let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({})); assert_eq!(add(&s), json!({"artboard": 1})); s.execute("artboard.delete", &json!({"index": 0})).unwrap(); assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); @@ -310,7 +336,8 @@ fn paste_and_fit_steps_keep_the_artboard_tools_selection() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); make_active(&mut s, 1); - let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &[], id, &json!({})); + let start = script::actions::Start { active: &[], picks: None, batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); @@ -323,3 +350,47 @@ fn paste_and_fit_steps_keep_the_artboard_tools_selection() { assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); assert_eq!(add(&s, "shape.rectangle"), json!({})); } + +/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays, +/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to +/// Artwork Bounds step fits them. +#[test] +fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { + // Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2. + let setup = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + s.execute("edit.copy", &json!({})).unwrap(); + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + (s, was, art) + }; + let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + let (mut s, ..) = setup(); + let before = objects(&s); + log_with(&mut s, "app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 2, "one copy on each selected artboard"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // A kept artboard past the last one is left out; with fewer than two left, the active one applies. + let (mut s, ..) = setup(); + s.reset_tool(); + let uid = s.active().unwrap().uid; + let kept = (uid, vec![0, 2]); + let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..8bf497bafe 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -80,8 +80,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ + getIsFileOpen loadAction loadAction= selection typename unloadAction unloadAction=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 9c0563b849..e77eb31143 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -589,15 +589,25 @@ pub(crate) fn has_stop(commands: &[Value]) -> bool { /// script's `app.doScript` plays, unless the caller gave them: every action of every set, in panel /// order, with its steps as playback runs them ([`Action::playback_steps`]) and each step's place in /// the action. An action that `actions` cannot hold (a step that is not a command, a name that is -/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out. +/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out, and so +/// is every other action of its set with its name, so that a name two actions share is never one a +/// script can play. pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { + use std::collections::HashMap; use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, parse}; let Some(p) = params.as_object_mut().filter(|_| id == "script.run") else { return }; if p.contains_key("actions") { return; } + let all = || app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))); + // How many actions of the panel have each set's name and action's name, and how many of them + // `actions` holds. + let mut named: HashMap<(&str, &str), (usize, usize)> = HashMap::new(); + for (set, a) in all() { + named.entry((set.name.as_str(), a.name.as_str())).or_default().0 += 1; + } let (mut list, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); - for (set, a) in app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))) { + for (set, a) in all() { if list.len() >= MAX_ACTIONS { break; } @@ -636,10 +646,18 @@ pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Va } steps += count; bytes += size; + if let Some(n) = named.get_mut(&(set.name.as_str(), a.name.as_str())) { + n.1 += 1; + } if let Value::Array(mut one) = one { list.append(&mut one); } } + let partly = |e: &Value| { + let key = (e["set"].as_str().unwrap_or_default(), e["name"].as_str().unwrap_or_default()); + named.get(&key).is_some_and(|(panel, held)| held < panel) + }; + list.retain(|e| !partly(e)); p.insert("actions".into(), Value::Array(list)); } @@ -7542,6 +7560,27 @@ mod tests { assert_eq!(objects(&app), 2); } + /// A name two actions of a set share stays a name a script can't play when `actions` leaves one + /// of them out: the other is left out too. + #[test] + fn a_script_cant_play_a_name_two_actions_share() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let rect = ("shape.rectangle".to_string(), json!({"x": 0, "y": 10, "width": 10, "height": 10})); + let good = Action::new("Twin", vec![rect.clone()]); + let odd = Action::new("Twin", vec![rect.clone(), ("select.none".to_string(), json!(5))]); + app.ui.action_sets.push(ActionSet::new("Mine", vec![good, odd, Action::new("Other", vec![rect])])); + let mut params = json!({}); + add_script_actions(&app, "script.run", &mut params); + let mine: Vec<_> = params["actions"].as_array().into_iter().flatten().filter(|a| a["set"] == "Mine").map(|a| a["name"].clone()).collect(); + assert_eq!(mine, [json!("Other")]); + app.session.script_frames = false; + let source = "try { app.doScript('Twin', 'Mine'); vc.log('ran'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(r["log"], json!(["the set “Mine” has no action “Twin”"])); + assert_eq!(app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::()), 0); + } + /// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's /// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6b507eab99..0062ea6218 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2689,10 +2689,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one - past the end. While the Artboard tool has several artboards selected, a paste step and a Fit to Artwork Bounds step - act on those instead, as in the panel's playback. VectorCraft's own rules: the action and its set are matched by - their exact names, and a name that matches no action or more than one throws an error before any step runs, as does - an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to + Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's + own rules: the action and its set are matched by their exact names, and a name that matches no action or more than + one throws an error before any step runs, as does an action with no included step. When the app leaves an action + out of `actions`, it also leaves out every other action of that set with the same name. A stop, and a step whose command a script may not run or the engine does not have (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an action cannot play itself. From 69448d0c2387ca69d22019ef8cee6eeb8591c5e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:16:56 -0800 Subject: [PATCH 030/104] Scripts: character and paragraph styles for scripts document.characterStyles and document.paragraphStyles list a document's styles, the Normal style first, and add, find and remove them. Each CharacterStyle and ParagraphStyle has a name, its attributes, applyTo with clearingOverrides, and remove; setting an attribute redefines the style through charStyle.setAttrs or paraStyle.setAttrs. A text range's characterStyles and paragraphStyles list the styles its text is in. Style names are trimmed and must have 1 to 256 characters and no control characters, one run names at most 4,096 styles, and a style object throws Stale style once its style is removed or renamed by a command. ParagraphStyle.characterAttributes is not available yet. charStyle.load, paraStyle.load and textStyle.loadAll refuse a file larger than 64 MB without reading it in full. --- crates/engine/src/cmd/textstyles.rs | 12 +- crates/engine/src/cmd/textstyles/tests.rs | 18 + crates/engine/src/script/dom.rs | 6 + crates/engine/src/script/dom/text.rs | 13 +- crates/engine/src/script/dom/text/styles.rs | 715 ++++++++++++++++++++ crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_styles.rs | 331 +++++++++ docs/mcp.md | 27 +- docs/target-app-parity.md | 3 +- 10 files changed, 1121 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/text/styles.rs create mode 100644 crates/engine/src/tests/script_styles.rs diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..3b57c2e067 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -148,8 +148,11 @@ macro_rules! style_cmds { }; } +/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes. +pub const MAX_LOAD_BYTES: usize = 64 << 20; + /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec { let mut v = style_cmds!( @@ -1266,12 +1269,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { _ => "textStyle.loadAll".to_string(), }; let path = str_param(p, "path"); + let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file(path)?, + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?, (None, Some(text), _) => text.as_bytes().to_vec(), + (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; + if bytes.len() > MAX_LOAD_BYTES { + return Err(too_large()); + } let file = str_param(p, "name").or(path).unwrap_or("Styles"); let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?; if src.preview_only { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index e8f57aa14f..1f8511d7ac 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -830,6 +830,24 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } +/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit. +#[test] +fn loading_refuses_a_file_larger_than_64_mb() { + let (mut s, _) = session_with_text("Title"); + let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Big.vectorcraft"); + std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); + let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + assert_eq!(s.doc().unwrap().doc, before); +} + /// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is /// out of the range `charStyle.new` takes is skipped. #[test] diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bef4c60707..87a6310ec3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -581,6 +581,11 @@ fn on_doc( Ok(v) } +/// Marks stale the style objects whose styles a command the run ran removed or renamed. +pub(super) fn after_command(h: &Host) { + text::styles::after_command(h); +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -1868,6 +1873,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("textFrames", text::doc_text_frames(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); + document.extend(text::styles::doc_members(l)); document.extend( ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..0366dec5dd 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -44,6 +44,8 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod styles; + /// The error of a text range, or of a collection of one, whose frame's text changed other than /// through the object model. pub const STALE_RANGE: &str = "Stale text range"; @@ -188,6 +190,8 @@ pub(in crate::script) struct TextState { /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. fonts: RefCell>>, + /// The styles the run's style objects name. + styles: styles::StyleState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1504,6 +1508,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.extend(styles::range_members(l)); range.extend( [ "lines", @@ -1511,8 +1516,6 @@ pub(super) fn classes(l: &Link) -> Vec { "textRanges", "story", "kerning", - "characterStyles", - "paragraphStyles", "textSelection", "changeCaseTo", "select", @@ -1537,7 +1540,7 @@ pub(super) fn classes(l: &Link) -> Vec { chars.extend(attr_members(l)); let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); - vec![ + let mut out = vec![ class("TextFrame", Some("PageItem"), frame, None), class("TextRange", None, range, None), part("Characters"), @@ -1586,7 +1589,9 @@ pub(super) fn classes(l: &Link) -> Vec { ]), None, ), - ] + ]; + out.extend(styles::classes(l)); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs new file mode 100644 index 0000000000..f2e140bd45 --- /dev/null +++ b/crates/engine/src/script/dom/text/styles.rs @@ -0,0 +1,715 @@ +//! Character and paragraph styles in the script object model: `document.characterStyles` and +//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text +//! of a `TextRange` uses, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A document's collection lists its Normal style first, then its other styles in the order the +//! panel lists them. +//! - A style object names its style for the rest of the run, also after the script renames it +//! through `name`. Once the style is removed, or renamed or removed other than through the object +//! model, or its document is closed, every member throws `Stale style`; a style added later under +//! the same name is another style. +//! - A style name is trimmed, and must then be 1 to 256 characters long with no control +//! characters. +//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the +//! style does not set. Setting one redefines the style: text in the style takes the new value +//! where it had the style's old one and keeps its other changes. +//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words +//! or paragraphs of one, in the style's document. A character style styles exactly that text and +//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches. +//! `clearingOverrides` left out is false; true resets the text to the Normal style first. +//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or +//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in +//! no other style. They do not add or remove styles. +//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its +//! look and is in the Normal style after. +//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`, +//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef}; +use vectorcraft_geom::Point; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref}; + +use super::{ + ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref, + function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text, + text_of, this_range, typename_of, usize_of, whole_span, with_doc, +}; +use crate::DocState; +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs}; + +/// The error of a style object whose style is gone. +pub const STALE_STYLE: &str = "Stale style"; +/// The longest style name, in characters, after trimming. +pub const MAX_STYLE_NAME: usize = 256; +/// The most styles one run's style objects name. +pub const MAX_HELD: usize = 4096; + +/// A style that a run's style objects name: its document, its kind and its name now. +struct Slot { + uid: u64, + para: bool, + name: String, + live: bool, +} + +/// A document's uid and its character and paragraph style lists when the slots were last checked. +type Seen = (u64, Shared>, Shared>); + +/// The styles a run's style objects name; an object holds its slot's number. +#[derive(Default)] +pub(super) struct StyleState { + slots: RefCell>, + seen: RefCell>, +} + +/// Marks stale each style object whose style the command just run removed or renamed, so a style +/// removed and made again under its name by later commands is another style. A document whose +/// style lists did not change is not checked again. +pub(in crate::script) fn after_command(h: &Host) { + let mut slots = h.dom.text.styles.slots.borrow_mut(); + if !slots.iter().any(|s| s.live) { + return; + } + let s = h.session.borrow(); + let mut seen = h.dom.text.styles.seen.borrow_mut(); + seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); + for st in s.documents() { + let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles)); + if same { + continue; + } + seen.retain(|(uid, ..)| *uid != st.uid); + seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { + slot.live = has_style(st, slot.para, &slot.name); + } + } + for slot in slots.iter_mut().filter(|x| x.live) { + if !s.documents().iter().any(|d| d.uid == slot.uid) { + slot.live = false; + } + } +} + +fn normal(para: bool) -> &'static str { + if para { NORMAL_PARA } else { NORMAL_CHAR } +} + +fn cmd(para: bool, verb: &str) -> String { + format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" }) +} + +fn style_class(para: bool) -> &'static str { + if para { "ParagraphStyle" } else { "CharacterStyle" } +} + +fn list_class(para: bool) -> &'static str { + if para { "ParagraphStyles" } else { "CharacterStyles" } +} + +fn defs(st: &DocState, para: bool) -> &Vec { + if para { &st.doc.para_styles } else { &st.doc.char_styles } +} + +/// The document's style names of a kind, the Normal style first. +fn names(st: &DocState, para: bool) -> Vec { + let mut out = vec![normal(para).to_string()]; + out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para))); + out +} + +fn has_style(st: &DocState, para: bool, name: &str) -> bool { + name == normal(para) || defs(st, para).iter().any(|d| d.name == name) +} + +fn stale() -> HostError { + HostError::Error(STALE_STYLE.into()) +} + +/// The style object for the style `name` of the document `uid`: the same slot as every other +/// object naming it in this run. +fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) { + Some(i) => i, + None => { + if slots.len() >= MAX_HELD { + return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); + } + slots.push(Slot { uid, para, name: name.to_string(), live: true }); + slots.len() - 1 + } + }; + Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)])) +} + +/// A style a style object names. +struct Style { + doc: Doc, + para: bool, + slot: usize, + name: String, +} + +/// The style `d` names, when it is an object of one of `classes` (with the kind each names). +fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result { + let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para))); + let Some((handle, para)) = found else { + return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0)))); + }; + let [run, uid, slot] = handle.as_slice() else { return Err(stale()) }; + let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?; + let slot = usize_of(*slot).ok_or_else(stale)?; + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; + if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) { + s.live = false; + return Err(stale()); + } + Ok(Style { doc, para, slot, name: s.name.clone() }) +} + +fn this_style(h: &Host, a: &[Data]) -> std::result::Result { + style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)]) +} + +/// Marks the slots of the styles `names` of the document `uid` as removed. +fn forget(h: &Host, uid: u64, para: bool, names: &[String]) { + for s in h.dom.text.styles.slots.borrow_mut().iter_mut() { + if s.uid == uid && s.para == para && names.contains(&s.name) { + s.live = false; + } + } +} + +/// A style name a script gave, trimmed. +fn style_name(v: &Data) -> std::result::Result { + let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) }; + if s.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + let t = s.trim(); + if t.is_empty() { + return Err(HostError::Range("a style name must not be empty".into())); + } + if t.chars().count() > MAX_STYLE_NAME { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + if t.chars().any(char::is_control) { + return Err(HostError::Range("a style name must not hold control characters".into())); + } + Ok(t.to_string()) +} + +/// Runs the style command `verb` of the kind on the document of `doc`. +fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result { + on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params)) +} + +// ---- CharacterStyle and ParagraphStyle ---- + +fn style_name_get(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_style(h, a)?.name)) +} + +/// `name = …`: renames the style; the Normal style keeps its name. +fn style_name_set(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let to = style_name(arg(a, 1))?; + if to == style.name { + return Ok(Data::Undefined); + } + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be renamed", style.name))); + } + if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) { + return Err(HostError::Error(format!("a style named {to} already exists"))); + } + run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?; + forget(h, style.doc.uid, style.para, std::slice::from_ref(&to)); + if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) { + s.name = to; + s.live = true; + } + Ok(Data::Undefined) +} + +fn style_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, this_style(h, a)?.doc.uid)) +} + +fn style_typename(h: &Host, a: &[Data]) -> Answer { + Ok(text(style_class(this_style(h, a)?.para))) +} + +fn attributes(h: &Host, a: &[Data], class: &str) -> Answer { + let style = this_style(h, a)?; + Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)])) +} + +fn style_character_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "CharacterStyleAttributes") +} + +fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "ParagraphStyleAttributes") +} + +/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after. +fn style_remove(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be removed", style.name))); + } + run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?; + forget(h, style.doc.uid, style.para, &[style.name]); + Ok(Data::Undefined) +} + +/// The text a style is applied to: a text range, a text frame, or the characters, words or +/// paragraphs of one. +fn target_span(h: &Host, d: &Data) -> std::result::Result { + if handle_of(d, "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, d)?)?.1); + } + const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"]; + if !TEXT.iter().any(|c| handle_of(d, c).is_some()) { + return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into())); + } + span_of(h, d, &TEXT) +} + +/// `applyTo(textItem, clearingOverrides?)`. +fn style_apply_to(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let target = target_span(h, arg(a, 1))?; + let clear = match arg(a, 2) { + Data::Undefined => false, + Data::Bool(b) => *b, + _ => return Err(HostError::Type("clearingOverrides must be true or false".into())), + }; + if target.item.doc.uid != style.doc.uid { + return Err(HostError::Error("the text is in another document than the style".into())); + } + let (index, s, e, _) = resolve(h, target)?; + h.charge_call(16 + (e - s) as u64)?; + let (start, end) = if style.para { + let (_, ba, bb) = para_range(&index, s, e); + (ba, bb) + } else { + if s == e { + return Ok(Data::Undefined); + } + (index.byte(s, false), index.byte(e, true)) + }; + let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end}); + run(h, style.doc, style.para, "apply", &p)?; + Ok(Data::Undefined) +} + +// ---- the attributes of a style ---- + +/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets. +const CHAR_KEYS: [(&str, &str); 11] = [ + ("size", "size"), + ("leading", "leading"), + ("tracking", "tracking"), + ("baselineShift", "baseline_shift"), + ("hScale", "h_scale"), + ("vScale", "v_scale"), + ("rotation", "rotation"), + ("underline", "underline"), + ("strikethrough", "strikethrough"), + ("font", "font_family"), + ("style", "font_style"), +]; + +/// The script's `Justification` members and the alignments a paragraph style stores. +const JUSTIFY: [(&str, &str); 7] = [ + ("LEFT", "Left"), + ("CENTER", "Center"), + ("RIGHT", "Right"), + ("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"), + ("FULLJUSTIFY", "JustifyAll"), +]; + +/// The style an attributes object belongs to and the attributes it sets. +fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map), HostError> { + let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" }; + let style = style_of(h, arg(a, 0), &[(class, para)])?; + let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?; + Ok((style, attrs)) +} + +fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { + let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num); + let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool); + match attr { + Attr::Size => n("size"), + Attr::Leading => n("leading"), + Attr::AutoLeading => match m.get("leading") { + Some(Value::Null) => Data::Bool(true), + Some(v) if v.is_number() => Data::Bool(false), + _ => Data::Undefined, + }, + Attr::Tracking => n("tracking"), + Attr::BaselineShift => n("baseline_shift"), + Attr::HorizontalScale => n("h_scale"), + Attr::VerticalScale => n("v_scale"), + Attr::Rotation => n("rotation"), + Attr::Underline => b("underline"), + Attr::StrikeThrough => b("strikethrough"), + Attr::TextFont => match m.get("font_family").and_then(Value::as_str) { + Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), + None => Data::Undefined, + }, + } +} + +fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { + let (_, m) = attrs_of(h, a, false)?; + Ok(char_value(h, attr, &m)) +} + +/// Redefines the style with `attrs`, unless they are what it has. +fn redefine(h: &Host, style: &Style, old: &Map, attrs: Map) -> Answer { + if attrs == *old { + return Ok(Data::Undefined); + } + run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?; + Ok(Data::Undefined) +} + +fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, false)?; + // `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph + // with the default justification. + let base = CharStyle::default(); + let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size); + let leading = old.get("leading").and_then(Value::as_f64); + let sample = CharStyle { size, leading, ..base }; + let t = TextObject::point(Point::default(), "", sample.clone()); + let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?; + let mut attrs = old.clone(); + for (k, v) in param.as_object().into_iter().flatten() { + let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue }; + let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() }; + attrs.insert((*key).to_string(), v); + } + redefine(h, &style, &old, attrs) +} + +fn para_key(attr: ParaAttr) -> &'static str { + match attr { + ParaAttr::Justification => "justify", + ParaAttr::FirstLineIndent => "first_line_indent", + ParaAttr::LeftIndent => "left_indent", + ParaAttr::RightIndent => "right_indent", + ParaAttr::SpaceBefore => "space_before", + ParaAttr::SpaceAfter => "space_after", + } +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let (_, m) = attrs_of(h, a, true)?; + let v = m.get(para_key(attr)); + Ok(match attr { + ParaAttr::Justification => match v.and_then(Value::as_str) { + Some("Auto") => text("Justification.LEFT"), + Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))), + None => Data::Undefined, + }, + _ => v.and_then(Value::as_f64).map_or(Data::Undefined, num), + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, true)?; + let (_, _, wants) = para_param(attr, name, arg(a, 1))?; + let value = match (&wants, attr) { + (Data::String(s), ParaAttr::Justification) => { + let m = s.strip_prefix("Justification.").unwrap_or(s); + let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j); + json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?) + } + (Data::Number(n), _) => json!(n), + _ => return Err(HostError::Type(format!("{name} must be a finite number"))), + }; + let mut attrs = old.clone(); + attrs.insert(para_key(attr).to_string(), value); + redefine(h, &style, &old, attrs) +} + +/// The body of a member that captures what it reads or sets. +type Body = Rc Answer>; + +/// Members whose getter and setter each charge the call, as [`function`] does. +fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember { + let wrap = |f: Body| -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = super::super::current(&l)?; + h.charge_call(16 + a.iter().map(super::super::data_size).sum::())?; + f(&h, &a) + }) + }; + HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) } +} + +fn char_members(link: &Link) -> Vec<(String, HostMember)> { + ATTRS + .iter() + .map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)))) + .collect() +} + +fn para_members(link: &Link) -> Vec<(String, HostMember)> { + PARA_ATTRS + .iter() + .map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)))) + .collect() +} + +// ---- CharacterStyles and ParagraphStyles ---- + +/// What a collection of styles lists: a document's styles, or those a text range uses. +enum Of { + Doc(Doc), + Range(Span), +} + +fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> { + let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) { + (Some(_), _) => false, + (_, Some(_)) => true, + _ => return Err(HostError::Type("this is not a CharacterStyles".into())), + }; + let class = list_class(para); + let len = handle_of(d, class).map_or(0, |v| v.len()); + Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para)) +} + +/// The document and the names of the styles a collection lists. +fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec), HostError> { + match of { + Of::Doc(doc) => { + let names = with_doc(h, *doc, |_, st| names(st, para)); + h.charge_call(names.len() as u64)?; + Ok((*doc, names)) + } + Of::Range(r) => { + let (index, s, e, _) = resolve(h, *r)?; + let used = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let used: Vec> = if para { + let (paras, _, _) = para_range(&index, s, e); + paras.map(|i| t.para_at(i).style_name.clone()).collect() + } else { + styles_in(t, index.byte(s, false), index.byte(e, true))?.into_iter().map(|(c, _)| c.style_name).collect() + }; + h.charge_call(used.len() as u64)?; + let mut out: Vec = Vec::new(); + for n in used { + let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string()); + if !out.contains(&n) { + out.push(n); + } + } + if out.is_empty() { + out.push(normal(para).to_string()); + } + Ok::<_, HostError>(out) + })?; + Ok((r.item.doc, used)) + } + } +} + +fn list_length(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + Ok(num(float(listed(h, &of, para)?.1.len() as u64))) +} + +fn list_parent(h: &Host, a: &[Data]) -> Answer { + let (of, _) = list_of(h, arg(a, 0))?; + match of { + Of::Doc(doc) => Ok(doc_ref(h, doc.uid)), + Of::Range(r) => { + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) + } + } +} + +fn list_at(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = match &of { + Of::Doc(doc) => with_doc(h, *doc, |_, st| match i { + 0 => Some(normal(para).to_string()), + _ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(), + }) + .map(|n| (*doc, n)), + Of::Range(_) => { + let (doc, names) = listed(h, &of, para)?; + names.get(i).cloned().map(|n| (doc, n)) + } + }; + match found { + Some((doc, name)) => style_ref(h, doc.uid, para, &name), + None => Ok(Data::Undefined), + } +} + +fn list_by_name(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let (doc, names) = listed(h, &of, para)?; + match names.iter().find(|n| *n == name) { + Some(n) => style_ref(h, doc.uid, para, n), + None => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn list_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a), + Data::Number(_) => match list_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a document's collection; a range's collection cannot be changed. +fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> { + match list_of(h, arg(a, 0))? { + (Of::Doc(doc), para) => Ok((doc, para)), + (Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())), + } +} + +/// `add(name)`: a new style that sets no attributes. +fn list_add(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let name = style_name(arg(a, 1))?; + if with_doc(h, doc, |_, st| has_style(st, para, &name)) { + return Err(HostError::Error(format!("a style named {name} already exists"))); + } + run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; + // An object of a removed style of this name stays stale. + forget(h, doc.uid, para, std::slice::from_ref(&name)); + style_ref(h, doc.uid, para, &name) +} + +/// `removeAll()`: deletes every style but the Normal style, in one command. +fn list_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let gone: Vec = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect(); + if gone.is_empty() { + return Ok(Data::Undefined); + } + run(h, doc, para, "delete", &json!({"names": gone}))?; + forget(h, doc.uid, para, &gone); + Ok(Data::Undefined) +} + +fn doc_char_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)])) +} + +fn doc_para_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)])) +} + +fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer { + let r = this_range(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, list_class(para))) +} + +fn range_char_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, false) +} + +fn range_para_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, true) +} + +/// `document.characterStyles` and `document.paragraphStyles`. +pub(in crate::script) fn doc_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("characterStyles", get(l, doc_char_styles)), ("paragraphStyles", get(l, doc_para_styles))]) +} + +/// `TextRange.characterStyles` and `TextRange.paragraphStyles`. +pub(super) fn range_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("characterStyles", get(l, range_char_styles)), ("paragraphStyles", get(l, range_para_styles))]) +} + +/// The style classes. +pub(super) fn classes(l: &Link) -> Vec { + let style = |para: bool| { + let mut members = named(vec![ + ("typename", get(l, style_typename)), + ("name", property(l, style_name_get, style_name_set)), + ("parent", get(l, style_parent)), + ("applyTo", method(l, style_apply_to)), + ("remove", method(l, style_remove)), + ]); + if para { + members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes))); + members.push(super::super::later(l, "ParagraphStyle", "characterAttributes")); + } else { + members.push(("characterAttributes".into(), get(l, style_character_attributes))); + } + class(style_class(para), None, members, None) + }; + let list = |para: bool| { + let name = list_class(para); + class( + name, + None, + named(vec![ + ("typename", typename_of(name)), + ("length", get(l, list_length)), + ("parent", get(l, list_parent)), + ("index", method(l, list_index)), + ("getByName", method(l, list_by_name)), + ("add", method(l, list_add)), + ("removeAll", method(l, list_remove_all)), + ]), + Some(function(l, list_at)), + ) + }; + let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + chars.extend(char_members(l)); + let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + paras.extend(para_members(l)); + vec![ + style(false), + style(true), + list(false), + list(true), + class("CharacterStyleAttributes", None, chars, None), + class("ParagraphStyleAttributes", None, paras, None), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..00d2c50167 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1317,6 +1317,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) }; + if r.is_ok() { + dom::after_command(host); + } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { let nanos = started.elapsed().as_nanos(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2a81daeb..572caa8cf2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_styles; mod script_text; mod scripts; mod select_effects; diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs new file mode 100644 index 0000000000..085ecfbbb9 --- /dev/null +++ b/crates/engine/src/tests/script_styles.rs @@ -0,0 +1,331 @@ +//! Character and paragraph styles in the script object model. + +use serde_json::{Value, json}; +use vectorcraft_doc::{TextObject, TextStyleDef}; + +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn text_of(s: &Session, id: NodeId) -> TextObject { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each run's text, style name, size and underline. +fn runs(s: &Session, id: NodeId) -> Vec<(String, Option, f64, bool)> { + text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect() +} + +fn char_names(s: &Session) -> Vec { + s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect() +} + +const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];"; + +#[test] +fn style_collections_list_the_normal_style_first_and_add_find_and_remove() { + let (mut s, _) = doc_with("Hello"); + let before = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\ + var b = cs.add('Body'); var p = ps.add('Lead');\ + vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\ + vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\ + cs.add('Other'); cs.removeAll(); ps.removeAll();\ + vc.log([cs.length, ps.length, cs[0].name]);" + ), + ); + assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"])); + assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"])); + assert_eq!(out[2], json!([2, "Lead", true])); + assert_eq!(out[3], json!([1, 1, NORMAL_CHAR])); + assert_eq!(undo_steps(&s), before + 1); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs.getByName('Nope');", "Not found"), + ("cs.index(4);", "Not found"), + ("cs.add('Body'); cs.add('Body');", "already exists"), + ("cs[0].remove();", "cannot be removed"), + ("ps[0].name = 'Mine';", "cannot be renamed"), + ("cs.getByName(5);", "string"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::::new())); +} + +/// Names are trimmed; an empty name, one past 256 characters and one with a control character +/// are refused with nothing changed. +#[test] +fn style_names_are_trimmed_and_checked() { + let (mut s, _) = doc_with("Hello"); + let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256))); + assert_eq!(out, [json!("Lead"), json!(256)]); + let undo = undo_steps(&s); + let long = "x".repeat(257); + for (src, says) in [ + ("cs.add(' ');".to_string(), "empty"), + (format!("cs.add('{long}');"), "256 characters"), + ("cs.add('a\\u0007b');".to_string(), "control characters"), + ("ps.add('tab\\there');".to_string(), "control characters"), + ("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"), + ("cs.add(5);".to_string(), "string"), + (format!("cs.getByName('{}');", "y".repeat(5000)), "too long"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + assert_eq!(char_names(&s).len(), 2); + // Path characters are kept as part of the name; a style name never names a file. + let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);")); + assert_eq!(out, [json!("../a/b\\c:*?")]); + assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?")); +} + +/// A style attribute that is not a finite number in range is refused with nothing changed. +#[test] +fn style_attributes_refuse_values_that_are_not_finite_or_in_range() { + let (mut s, _) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');")); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs[1].characterAttributes.size = NaN;", "finite number"), + ("cs[1].characterAttributes.size = Infinity;", "finite number"), + ("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"), + ("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"), + ("cs[1].characterAttributes.tracking = -1e9;", "tracking"), + ("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"), + ("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + let attrs = |s: &Session| { + s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::() + }; + assert_eq!(attrs(&s), 0); +} + +/// A style object follows its style through a rename made with it; after the style is removed, +/// with the object or with a command, every member throws, and a new style of that name does not +/// bring it back. +#[test] +fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { + let (mut s, id) = doc_with("Hello"); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\ + a.name = 'B'; vc.log(cs.length);" + ), + ); + assert_eq!(out, [json!(["B", "B", true]), json!(2)]); + assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B")); + for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] { + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;")); + assert!(e.contains("Stale style"), "{remove}: {e}"); + } + // A style removed and made again by commands is another style. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // A style renamed by a command is stale too, and its text keeps its look after a removal. + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); + assert!(e.contains("Stale style"), "{e}"); + let e = + failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;")); + assert!(e.contains("Stale style"), "{e}"); + let size = runs(&s, id)[0].2; + log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();")); + assert_eq!(runs(&s, id)[0].1, None); + assert_ne!(runs(&s, id)[0].2, size); + assert_eq!(runs(&s, id)[0].2, 40.0); +} + +/// A character style styles exactly the range; without clearing overrides the range keeps its +/// own underline, and with them it goes back to the Normal style first. +#[test] +fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { + let (mut s, id) = doc_with("Hello world"); + let before = undo_steps(&s); + log( + &mut s, + &format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"), + ); + assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);")); + assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false)); + // A whole frame, and an empty range, which changes nothing. + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);")); + assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); +} + +/// A paragraph style styles every paragraph the text touches, and only those. +#[test] +fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { + let (mut s, id) = doc_with("one\ntwo\nthree"); + let out = log( + &mut s, + &format!( + "{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\ + vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\ + a.justification = Justification.CENTER; a.spaceBefore = 6;\ + vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\ + vc.log(tf.paragraphs[1].paragraphAttributes.justification);" + ), + ); + assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]); + let t = text_of(&s, id); + let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect(); + assert_eq!(names, [None, Some("Centered".to_string()), None]); + assert_eq!(t.para_at(1).space_before, 6.0); + assert_eq!(t.para_at(2).space_before, 0.0); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';")); + assert!(e.contains("Justification"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;")); + assert!(e.contains("1296"), "{e}"); +} + +/// A style's character attributes read `undefined` until set; setting one restyles the text in +/// the style but not a value the text changed itself. +#[test] +fn style_attributes_redefine_the_text_in_the_style() { + let (mut s, id) = doc_with("ab cd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), a = x.characterAttributes;\ + vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\ + a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\ + vc.log([a.size, a.autoLeading, a.underline]);" + ), + ); + assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); + assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); + // Turning auto leading off keeps the leading auto leading gave the style's size. + let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);")); + assert_eq!(out, [json!([false, 288])]); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); + assert!(e.contains("0.1 to 1296"), "{e}"); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';")); + assert!(e.contains("TextFont"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;")); + assert!(e.contains("not available yet"), "{e}"); +} + +/// A range lists each style its text uses once, in order, with the Normal style for unstyled +/// text, and its lists cannot add or remove styles. +#[test] +fn a_range_lists_the_styles_its_text_uses() { + let (mut s, _) = doc_with("aa bb cc\ndd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\ + ps.add('P').applyTo(tf.paragraphs[1]);\ + function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\ + vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\ + vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\ + vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\ + tf.textRange.characterStyles.parent.typename]);" + ), + ); + assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"])); + assert_eq!(out[1], json!(["X"])); + assert_eq!(out[2], json!([NORMAL_PARA, "P"])); + assert_eq!(out[3], json!([NORMAL_PARA])); + assert_eq!(out[4], json!([true, "X", "TextRange"])); + for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}"); + } +} + +/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another +/// document, and a range whose text changed, with nothing changed. +#[test] +fn apply_to_refuses_bad_arguments_with_nothing_changed() { + let (mut s, id) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X');")); + let runs_before = runs(&s, id); + for (src, says) in [ + ("cs[1].applyTo(5);".to_string(), "TextRange"), + ("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"), + ("cs[1].applyTo(cs);".to_string(), "TextRange"), + (format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"), + ( + "var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(), + "another document", + ), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(runs(&s, id), runs_before); +} + +/// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn a_run_names_at_most_4096_styles() { + let (mut s, _) = doc_with("Hello"); + let mut d = (*s.active().unwrap().doc).clone(); + let defs: Vec = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect(); + d.char_styles = defs.into(); + s.doc_mut().unwrap().doc = std::sync::Arc::new(d); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);")); + assert_eq!(out, [json!(false), json!(4101)]); + let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); + assert!(e.contains("4096 styles"), "{e}"); +} + +/// A script loads styles from a file only where it may read files; a file outside that is refused. +#[test] +fn a_script_loads_styles_only_from_a_file_it_may_read() { + let (mut s, _) = doc_with("Hello"); + let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Other.vectorcraft"); + let mut other = Session::new(); + other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap(); + std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap(); + let p = path.to_string_lossy().replace('\\', "/"); + let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});")); + std::fs::remove_dir_all(&dir).ok(); + assert!(e.contains("access denied"), "{e}"); + assert!(char_names(&s).is_empty()); +} diff --git a/docs/mcp.md b/docs/mcp.md index b875fee563..801933b011 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2738,6 +2738,31 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and `orientation` cannot be set yet. +- `Document.characterStyles` and `Document.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, + https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/) list the document's styles with `length`, `[i]`, + `index(key)`, `getByName(name)`, `add(name)` (`charStyle.new` or `paraStyle.new` with no attributes) and + `removeAll()` (`charStyle.delete` or `paraStyle.delete` of every style but the Normal style). A `CharacterStyle` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/) has `name` (`charStyle.rename`), `parent`, + `characterAttributes`, `applyTo(text, clearingOverrides?)` (`charStyle.apply`) and `remove()` (`charStyle.delete`); + a `ParagraphStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/) has the same members with + `paragraphAttributes` and the `paraStyle` commands. A style's attributes are those of a text range's + `characterAttributes` and `paragraphAttributes`, with the same ranges, and setting one runs `charStyle.setAttrs` or + `paraStyle.setAttrs`. `TextRange.characterStyles` and `TextRange.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) list the styles the range's text is in, with `length`, + `[i]`, `index(key)` and `getByName(name)`. A script loads styles from another document with `vc.run` and + `charStyle.load`, `paraStyle.load` or `textStyle.loadAll`, from a file the script may read. + VectorCraft's own rules: a document's list starts with `[Normal Character Style]` or `[Normal Paragraph Style]`, + followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. + An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the + style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the + style's document; a character style on an empty range changes nothing, and a paragraph style styles every + paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order + its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove + styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made + through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`. + One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not + available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -13086,7 +13111,7 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..eedc6224f8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From a2063cea756b84dbefd454384ac569f4643785eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:55:21 -0800 Subject: [PATCH 031/104] Scripts: a style change that is put back keeps its style object A removal or rename whose result cannot reach the script is put back, and style objects now follow a command only once it is kept. A failed atomic object-model call puts style objects back with the documents. --- crates/engine/src/script/dom.rs | 17 +++++++--- crates/engine/src/script/dom/text/styles.rs | 35 +++++++++++++++++++++ crates/engine/src/script/mod.rs | 7 +++-- crates/engine/src/tests/script_styles.rs | 29 ++++++++++++++++- 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 87a6310ec3..c02d65dfbd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -113,15 +113,22 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, + seen: Vec, +} + +/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored. +pub(in crate::script) fn mark(h: &Host) -> Mark { + let styles = &h.dom.text.styles; + let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect(); + Mark { slots, seen: styles.seen.borrow().clone() } +} + +/// Puts the style objects back as they were at `mark`, after the documents were put back to the +/// savepoint taken with it. A slot added since then stays live only while its document has the +/// style and no older live slot names it. +pub(in crate::script) fn put_back(h: &Host, mark: Mark) { + let styles = &h.dom.text.styles; + let mut slots = styles.slots.borrow_mut(); + let kept = mark.slots.len(); + for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) { + slot.name = name; + slot.live = live; + } + let s = h.session.borrow(); + for i in kept..slots.len() { + let (older, newer) = slots.split_at_mut(i); + let Some(slot) = newer.first_mut() else { break }; + let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && has_style(st, slot.para, &slot.name)); + } + *styles.seen.borrow_mut() = mark.seen; +} + fn normal(para: bool) -> &'static str { if para { NORMAL_PARA } else { NORMAL_CHAR } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 00d2c50167..e537ab8ef7 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1317,9 +1317,6 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) }; - if r.is_ok() { - dom::after_command(host); - } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { let nanos = started.elapsed().as_nanos(); @@ -1349,6 +1346,10 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + // Style objects follow only a command that is kept. + if crossed.is_ok() { + dom::after_command(host); + } crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 085ecfbbb9..f30e66a7e6 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{TextObject, TextStyleDef}; use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::script::TEST_RESULT_BYTES; use crate::*; fn run(s: &mut Session, source: &str) -> Result { @@ -177,6 +178,29 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { assert_eq!(runs(&s, id)[0].2, 40.0); } +/// A removal or rename whose result cannot cross to the script is put back, and the style's object +/// still names the style after it. +#[test] +fn a_style_change_that_is_put_back_keeps_the_style_object() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap(); + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\ + try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\ + try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\ + vc.log([a.name, a === cs.getByName('B'), cs.length]);" + ), + ); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}"); + assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s)); +} + /// A character style styles exactly the range; without clearing overrides the range keeps its /// own underline, and with them it goes back to the Normal style first. #[test] @@ -239,7 +263,10 @@ fn style_attributes_redefine_the_text_in_the_style() { assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); // Turning auto leading off keeps the leading auto leading gave the style's size. - let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);")); + let out = log( + &mut s, + &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"), + ); assert_eq!(out, [json!([false, 288])]); let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); assert!(e.contains("0.1 to 1296"), "{e}"); From de11e1e7555d02e6cd2dc513ae6bbc8b6b2a46b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:47:00 -0800 Subject: [PATCH 032/104] Scripts: style objects made before File > Revert go stale A style object kept working after file.revert when the file read back held a style with the same name. Each style object now keeps the document's revert count, as text ranges do, and one made before a revert throws Stale style. The range style lists follow the per-paragraph entries of the text model, and the host name table lists the style classes. --- crates/engine/src/script/dom/text/styles.rs | 21 ++++++---- crates/engine/src/tests/script_styles.rs | 22 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 41 +++++++++++++++---- docs/mcp.md | 3 +- 4 files changed, 69 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index adb71dd6cf..841d006ac6 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -12,8 +12,8 @@ //! panel lists them. //! - A style object names its style for the rest of the run, also after the script renames it //! through `name`. Once the style is removed, or renamed or removed other than through the object -//! model, or its document is closed, every member throws `Stale style`; a style added later under -//! the same name is another style. +//! model, or its document is closed or reverted with File › Revert, every member throws +//! `Stale style`; a style added later under the same name is another style. //! - A style name is trimmed, and must then be 1 to 256 characters long with no control //! characters. //! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the @@ -54,9 +54,11 @@ pub const MAX_STYLE_NAME: usize = 256; /// The most styles one run's style objects name. pub const MAX_HELD: usize = 4096; -/// A style that a run's style objects name: its document, its kind and its name now. +/// A style that a run's style objects name: its document and the document's revert count then, its +/// kind and its name now. struct Slot { uid: u64, + reverts: u64, para: bool, name: String, live: bool, @@ -91,7 +93,7 @@ pub(in crate::script) fn after_command(h: &Host) { seen.retain(|(uid, ..)| *uid != st.uid); seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { - slot.live = has_style(st, slot.para, &slot.name); + slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name); } } for slot in slots.iter_mut().filter(|x| x.live) { @@ -131,7 +133,7 @@ pub(in crate::script) fn put_back(h: &Host, mark: Mark) { let (older, newer) = slots.split_at_mut(i); let Some(slot) = newer.first_mut() else { break }; let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); - slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && has_style(st, slot.para, &slot.name)); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name)); } *styles.seen.borrow_mut() = mark.seen; } @@ -174,14 +176,15 @@ fn stale() -> HostError { /// The style object for the style `name` of the document `uid`: the same slot as every other /// object naming it in this run. fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); let mut slots = h.dom.text.styles.slots.borrow_mut(); - let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) { + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) { Some(i) => i, None => { if slots.len() >= MAX_HELD { return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); } - slots.push(Slot { uid, para, name: name.to_string(), live: true }); + slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); slots.len() - 1 } }; @@ -207,7 +210,7 @@ fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result let slot = usize_of(*slot).ok_or_else(stale)?; let mut slots = h.dom.text.styles.slots.borrow_mut(); let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; - if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) { + if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) { s.live = false; return Err(stale()); } @@ -552,7 +555,7 @@ fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec = Vec::new(); diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index f30e66a7e6..759e41eae1 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -326,6 +326,28 @@ fn apply_to_refuses_bad_arguments_with_nothing_changed() { } /// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap(); + let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\ + var cs2 = app.activeDocument.characterStyles;\ + try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\ + vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);" + ), + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}"); + assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style"); + assert_eq!(out[2], json!(false)); +} + #[test] fn a_run_names_at_most_4096_styles() { let (mut s, _) = doc_with("Hello"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b23788236e..4e066e4831 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -96,10 +96,10 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames typename \ - views views= width", + "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ + documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols \ + symbols= textFrames typename views views= width", ), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name typename"), @@ -131,8 +131,9 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ( "", - "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ - TextOrientation TextRange TextType Words", + "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ + ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \ + TextFrames TextOrientation TextRange TextType Words", ), ("TextFrames.", "prototype"), ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), @@ -150,11 +151,11 @@ const INSIDE: &[(&str, &str)] = &[ ( "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ - characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \ duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ - paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ + paragraphStyles paragraphs parent remove rotation rotation= select select= size size= start start= \ story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ tracking tracking= typename underline underline= verticalScale verticalScale= words", ), @@ -177,6 +178,30 @@ const INSIDE: &[(&str, &str)] = &[ "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", ), + ("CharacterStyles.", "prototype"), + ("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("CharacterStyle.", "prototype"), + ("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"), + ("CharacterStyleAttributes.", "prototype"), + ( + "CharacterStyleAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphStyles.", "prototype"), + ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("ParagraphStyle.", "prototype"), + ( + "ParagraphStyle.prototype.", + "applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename", + ), + ("ParagraphStyleAttributes.", "prototype"), + ( + "ParagraphStyleAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), ("TextFonts.", "prototype"), ("TextFonts.prototype.", "constructor getByName index length parent typename"), ("TextFont.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 801933b011..411ef4ba07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2760,7 +2760,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made - through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`. + through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws + `Stale style`. One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and From d82fe4e8d90b9d6a80632593fc820d009770d973 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:54:45 -0800 Subject: [PATCH 033/104] Scripts: nextFrame, previousFrame, story and document.stories for threaded type Text frames get nextFrame, previousFrame and story, and documents get stories, a Stories collection with one story for each thread and each type object in no thread. Assigning nextFrame or previousFrame links the last frame of one story to the first frame of another, and null breaks the link with each frame keeping its text; loops, links to the frame itself or into the middle of a story, point type, frames of another document and hidden or locked frames are refused with nothing changed. A story of two or more frames reads and writes its text across its frames in UTF-16 units, and areaText and pathText take baseFrame and postFix to thread the new frame to an existing one. The new command text.thread.setNeighbor {id, side, neighbor} links or breaks by id without a selection, for MCP, the CLI and vc.run. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/threads.rs | 115 +++ crates/engine/src/script/dom.rs | 1 + crates/engine/src/script/dom/text.rs | 34 +- crates/engine/src/script/dom/text/threads.rs | 786 ++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_threads.rs | 596 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 34 +- docs/gaps.md | 6 +- docs/mcp.md | 41 +- docs/target-app-parity.md | 1 + 11 files changed, 1598 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/script/dom/text/threads.rs create mode 100644 crates/engine/src/tests/script_threads.rs diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..26514918aa 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -669,6 +669,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.info", "text.thread.releaseSelection", "text.thread.remove", + "text.thread.setNeighbor", "text.touchType", "threeD.addGraphic", "threeD.mapArt", diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index f4f807cb15..1a79fbfbc9 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -59,6 +59,15 @@ pub fn specs() -> Vec { has_doc, break_thread ), + cmd!( + "text.thread.setNeighbor", + "Thread Text", + [], + None, + "{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}", + has_doc, + set_neighbor + ), cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| { Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::>()).collect::>())) }), @@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result { ok() } +/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on +/// a path, each once, or `id` alone when it is in no thread. +fn chain_of(d: &Document, id: NodeId) -> Vec { + let mut frames = story_of(d, id); + let mut seen = Ids::default(); + frames.retain(|f| seen.insert(*f)); + if frames.len() < 2 { vec![id] } else { frames } +} + +fn chain_ids(chains: &[&[NodeId]]) -> Value { + json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::>()).collect::>()) +} + +/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link. +fn set_neighbor(s: &mut Session, p: &Value) -> Result { + const C: &str = "text.thread.setNeighbor"; + let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?; + let next = match p.get("side").and_then(Value::as_str) { + Some("next") => true, + Some("previous") => false, + _ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")), + }; + let neighbor = match p.get("neighbor") { + None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")), + Some(Value::Null) => None, + Some(v) => Some(checked_id(s, v, C)?), + }; + let d = &s.doc()?.doc; + if text_of(d, id).is_none() { + return Err(bad(C, "`id` must be area type or type on a path")); + } + let locked = |frames: &[NodeId]| { + let editable = d.editable(); + frames.iter().any(|f| !editable(*f)) + }; + let chain = chain_of(d, id); + let Some(n) = neighbor else { + // Break the link on that side: the frames before it and the frames after it. + let i = chain.iter().position(|f| *f == id).unwrap_or(0); + let at = if next { i + 1 } else { i }; + if at == 0 || at >= chain.len() { + return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])})); + } + if locked(&chain) { + return Err(bad(C, "a frame of the story is hidden or locked")); + } + let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec()); + let cut: Ids = chain.iter().copied().collect(); + s.edit("Break Thread", |d, _| { + d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f))); + for part in [&head, &tail] { + if part.len() >= 2 { + d.text_threads.push(part.clone()); + } + } + // The first frame after the break starts its story, which flows again on this edit so + // that its numbered paragraphs count from 1. + if let Some(f) = tail.first() { + touch(d, *f); + } + if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind) + && t.first_para_continues + { + t.first_para_continues = false; + refresh_bounds(t); + } + Ok(()) + })?; + return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])})); + }; + if n == id { + return Err(bad(C, "a frame cannot be linked to itself")); + } + if text_of(d, n).is_none() { + return Err(bad(C, "`neighbor` must be area type or type on a path")); + } + // `first` is to flow into `second`. + let (first, second) = if next { (id, n) } else { (n, id) }; + let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) }; + if a.contains(&second) { + if a.windows(2).any(|w| w == [first, second]) { + return Ok(json!({"changed": false, "threads": chain_ids(&[&a])})); + } + return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it")); + } + if a.last() != Some(&first) { + return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0))); + } + if b.first() != Some(&second) { + return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0))); + } + if locked(&a) || locked(&b) { + return Err(bad(C, "a frame of either story is hidden or locked")); + } + let joined: Vec = a.iter().chain(&b).copied().collect(); + let affected: Ids = joined.iter().copied().collect(); + s.edit("Thread Text", |d, _| { + d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f))); + d.text_threads.push(joined.clone()); + // Force a re-flow of the joined story on this edit. + touch(d, first); + Ok(()) + })?; + Ok(json!({"changed": true, "threads": chain_ids(&[&joined])})) +} + #[cfg(test)] mod tests; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d467345a2c..49ae9d1138 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1767,6 +1767,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("textFrames", text::doc_text_frames(l)), + ("stories", text::threads::doc_stories(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..822e34e954 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -44,6 +44,8 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod threads; + /// The error of a text range, or of a collection of one, whose frame's text changed other than /// through the object model. pub const STALE_RANGE: &str = "Stale text range"; @@ -188,6 +190,7 @@ pub(in crate::script) struct TextState { /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. fonts: RefCell>>, + stories: threads::StoryState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1191,24 +1194,32 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer { return Err(HostError::Error(super::CROSS_DOCUMENT.into())); } if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) { - return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into())); + return Err(HostError::Error("TextFrames: path positions are not available yet".into())); } - let orientation = if on_path { 4 } else { 2 }; + let (orientation, base) = if on_path { (4, 5) } else { (2, 3) }; let vertical = vertical_of(arg(a, orientation))?; + let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?; + if base.is_some() { + threads::check_base_path(h, path)?; + } let mode = if on_path { "onPath" } else { "area" }; let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical}); let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?; - new_ref(h, doc, result_id(&r)) + let id = result_id(&r); + if let (Some((base, postfix)), Some(id)) = (base, id) { + threads::thread_new(h, base, id, postfix)?; + } + new_ref(h, doc, id) } /// `areaText(textPath, orientation?, baseFrame?, postFix?)`. fn frames_area_text(h: &Host, a: &[Data]) -> Answer { - in_path(h, a, false, &[3, 4]) + in_path(h, a, false, &[]) } /// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`. fn frames_path_text(h: &Host, a: &[Data]) -> Answer { - in_path(h, a, true, &[2, 3, 5, 6]) + in_path(h, a, true, &[2, 3]) } /// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. @@ -1462,14 +1473,12 @@ pub(super) fn classes(l: &Link) -> Vec { ("convertAreaObjectToPointObject", method(l, frame_to_point)), ("convertPointObjectToAreaObject", method(l, frame_to_area)), ]); + frame.extend(threads::frame_members(l)); frame.extend( [ "lines", "insertionPoints", "textRanges", - "story", - "nextFrame", - "previousFrame", "textPath", "anchor", "antialias", @@ -1504,12 +1513,12 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.push(threads::range_member(l)); range.extend( [ "lines", "insertionPoints", "textRanges", - "story", "kerning", "characterStyles", "paragraphStyles", @@ -1537,7 +1546,8 @@ pub(super) fn classes(l: &Link) -> Vec { chars.extend(attr_members(l)); let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); - vec![ + let stories = threads::classes(l); + let mut out = vec![ class("TextFrame", Some("PageItem"), frame, None), class("TextRange", None, range, None), part("Characters"), @@ -1586,7 +1596,9 @@ pub(super) fn classes(l: &Link) -> Vec { ]), None, ), - ] + ]; + out.extend(stories); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs new file mode 100644 index 0000000000..ee81129944 --- /dev/null +++ b/crates/engine/src/script/dom/text/threads.rs @@ -0,0 +1,786 @@ +//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and +//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story, +//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null` +//! breaks that link, and no text moves across it. Point type, a frame of another +//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden +//! or locked frame in either story are refused with nothing changed. Assigning the frame that is +//! already linked, or `null` where there is no link, changes nothing. +//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the +//! frame is deleted, it throws `Stale story`. +//! - `document.stories` lists one story for each type object in no thread and one for each thread, +//! in the paint order of their first frames. `index` with a string finds the first story whose +//! first frame has that name. +//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep +//! their place through edits made through them, as a frame's ranges do, and are stale after any +//! other change to the story's text and after File › Revert. A story of one frame gives that +//! frame's own ranges. +//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when +//! `postFix` is false; `postFix` is true when it is left out. + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::rc::Rc; +use std::sync::{Arc, Weak}; + +use serde_json::json; +use vectorcraft_doc::TextKind; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref}; + +use super::super::{ + Answer, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, + id_of, id_parts, in_compound, item_of, item_ref, later, method, named, num, property, text, whole, with_doc, +}; +use super::{ + ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched, + usize_of, whole_span, +}; +use crate::cmd::threads::story_of; +use crate::{DocState, Document, NodeId}; + +/// The error of a `Story` whose frame was deleted, or that came from an earlier run. +pub const STALE_STORY: &str = "Stale story"; + +/// A document's uid, the document, and the first frame of each of its stories then. +type StoryList = (u64, Weak, Rc>); + +/// The story state of one run: the text of each story of two or more frames that a range was made +/// of, by document and the frame the `Story` was read from, and the last list of stories. +#[derive(Default)] +pub(in crate::script) struct StoryState { + logs: RefCell>, + list: RefCell>, +} + +/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone. +fn frames_of(st: &DocState, id: NodeId) -> Vec { + let mut frames = story_of(&st.doc, id); + let mut seen = HashSet::new(); + frames.retain(|f| seen.insert(*f)); + if frames.len() < 2 { vec![id] } else { frames } +} + +/// The frames of the story `id` is a frame of, charged to the run. +fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result, HostError> { + h.charge_call(st.doc.text_threads.len() as u64)?; + let frames = frames_of(st, id); + h.charge_call(frames.len() as u64)?; + Ok(frames) +} + +/// Whether type object `id` is area type or type on a path. +fn threadable(st: &DocState, id: NodeId) -> bool { + text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point)) +} + +// ---- nextFrame and previousFrame ---- + +fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer { + let item = this_frame(h, a)?; + with_doc(h, item.doc, |_, st| { + let frames = charged_frames(h, st, item.id)?; + let i = frames.iter().position(|f| *f == item.id); + let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) }); + Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f))) + }) +} + +fn next_frame(h: &Host, a: &[Data]) -> Answer { + neighbor(h, a, true) +} + +fn previous_frame(h: &Host, a: &[Data]) -> Answer { + neighbor(h, a, false) +} + +/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`. +fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer { + let name = if next { "nextFrame" } else { "previousFrame" }; + let item = this_frame(h, a)?; + let other = match arg(a, 1) { + Data::Null => None, + d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?), + _ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))), + }; + if other.is_some_and(|o| o.doc.uid != item.doc.uid) { + return Err(HostError::Error(format!("{name}: the two frames are in different documents"))); + } + let now = with_doc(h, item.doc, |_, st| { + if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) { + return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded"))); + } + let frames = charged_frames(h, st, item.id)?; + let i = frames.iter().position(|f| *f == item.id); + let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) }); + Ok(current.copied()) + })?; + if now == other.map(|o| o.id) { + return Ok(Data::Undefined); + } + let side = if next { "next" } else { "previous" }; + let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)}); + edit_item(h, item, "text.thread.setNeighbor", ¶ms).map_err(|e| match e { + HostError::Error(m) => HostError::Error(format!("{name}: {m}")), + e => e, + })?; + Ok(Data::Undefined) +} + +fn set_next_frame(h: &Host, a: &[Data]) -> Answer { + set_neighbor(h, a, true) +} + +fn set_previous_frame(h: &Host, a: &[Data]) -> Answer { + set_neighbor(h, a, false) +} + +/// `TextFrame.story`. +fn frame_story(h: &Host, a: &[Data]) -> Answer { + let item = this_frame(h, a)?; + Ok(story_ref(h, item)) +} + +/// `TextRange.story`: the story of the range's frame. +fn range_story(h: &Host, a: &[Data]) -> Answer { + let r = super::this_range(h, a)?; + super::resolve(h, r)?; + Ok(story_ref(h, r.item)) +} + +// ---- creating a frame threaded to another ---- + +/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame +/// is made: the frame to thread the new one to, and whether the new one goes after it. +pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result, HostError> { + if matches!(base, Data::Undefined | Data::Null) { + return Ok(None); + } + if handle_of(base, "TextFrame").is_none() { + return Err(HostError::Type("baseFrame must be a TextFrame".into())); + } + let item = item_of(h, base)?; + if item.doc.uid != doc.uid { + return Err(HostError::Error("baseFrame: the frame is in another document".into())); + } + let postfix = match post { + Data::Undefined => true, + d => boolean(d, "postFix")?, + }; + with_doc(h, item.doc, |_, st| { + if !threadable(st, item.id) { + return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into())); + } + let editable = st.doc.editable(); + if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) { + return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into())); + } + Ok(()) + })?; + Ok(Some((item, postfix))) +} + +/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type: +/// `text.thread.add` does not thread type there. +pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> { + if in_compound(h, path) { + return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into())); + } + Ok(()) +} + +/// Threads the new frame `id` after `base`, or before it when `postfix` is false. +pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> { + edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?; + Ok(()) +} + +// ---- Story ---- + +fn story_ref(h: &Host, item: Item) -> Data { + let [high, low] = id_parts(item.id); + host_ref("Story", &[float(h.run), float(item.doc.uid), high, low]) +} + +/// The frame the story `d` was read from, which must still be a type object. +fn story_of_data(h: &Host, d: &Data) -> std::result::Result { + let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) }; + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + match with_doc(h, doc, |_, st| text_of(st, id).is_some()) { + true => Ok(Item { doc, id }), + false => Err(HostError::Error(STALE_STORY.into())), + } +} + +fn this_story(h: &Host, a: &[Data]) -> std::result::Result { + story_of_data(h, arg(a, 0)) +} + +fn story_frames(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect()))) +} + +fn story_parent(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + Ok(doc_ref(h, story.doc.uid)) +} + +/// The story's one frame, or `None` for a story of two or more frames. +fn single(h: &Host, story: Item) -> std::result::Result, HostError> { + with_doc(h, story.doc, |_, st| { + let frames = charged_frames(h, st, story.id)?; + Ok(match frames[..] { + [one] => Some(Item { doc: story.doc, id: one }), + _ => None, + }) + }) +} + +fn story_length(h: &Host, a: &[Data]) -> Answer { + let story = this_story(h, a)?; + let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?; + Ok(num(float(index.len() as u64))) +} + +/// A range or a collection of the whole story, as `frame_class` for a story of one frame and +/// `story_class` for a longer one. +fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer { + let story = this_story(h, a)?; + if let Some(frame) = single(h, story)? { + let (_, r) = whole_span(h, frame)?; + return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class)); + } + let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?; + Ok(span_ref(h, story, 0, index.len(), stamp, story_class)) +} + +fn story_text_range(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "TextRange", "StoryRange") +} + +fn story_characters(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Characters", "StoryCharacters") +} + +fn story_words(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Words", "StoryWords") +} + +fn story_paragraphs(h: &Host, a: &[Data]) -> Answer { + story_whole(h, a, "Paragraphs", "StoryParagraphs") +} + +// ---- the text of a story of two or more frames ---- + +/// The frames of the story and the text of each, in thread order. +fn story_text(st: &DocState, frames: &[NodeId]) -> String { + frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect() +} + +/// The story's index and its generation now, read again when its document changed. +fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc, u64), HostError> { + if text_of(st, anchor).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let mut logs = h.dom.text.stories.logs.borrow_mut(); + let key = (st.uid, anchor.0); + let now = Arc::as_ptr(&st.doc); + match logs.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} + Some(l) => { + let frames = charged_frames(h, st, anchor)?; + let text = story_text(st, &frames); + if l.reverts != st.reverts || text != l.index.text { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(text)); + } + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + let frames = charged_frames(h, st, anchor)?; + let index = Rc::new(Index::new(story_text(st, &frames))); + logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + } + } + let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; + Ok((l.index.clone(), l.stamp)) +} + +/// A range of a story: the frame the story was read from, its span in UTF-16 units and the +/// generation it was made at. +#[derive(Clone, Copy)] +struct StorySpan { + story: Item, + start: usize, + end: usize, + stamp: u64, +} + +const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)]; + +fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { + let [high, low] = id_parts(story.id); + host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) +} + +/// The story span `d` names, when it is an object of one of `classes`. +fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + let handle = classes.iter().find_map(|c| handle_of(d, c)); + let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); + }; + let story = story_of_data(h, &host_ref("Story", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; + let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; + Ok(StorySpan { story, start, end, stamp }) +} + +fn this_span(h: &Host, a: &[Data]) -> std::result::Result { + span_of(h, arg(a, 0), &["StoryRange"]) +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc, usize, usize, u64), HostError> { + with_doc(h, r.story.doc, |_, st| { + let (index, stamp) = observe(h, st, r.story.id)?; + let logs = h.dom.text.stories.logs.borrow(); + let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?; + if r.stamp < l.floor || r.stamp > l.stamp { + return Err(HostError::Error(STALE_RANGE.into())); + } + let (mut s, mut e) = (r.start, r.end); + let from = l.edits.partition_point(|x| x.stamp <= r.stamp); + for x in l.edits.range(from..) { + let moved = |v: usize| v - x.removed + x.inserted; + s = if s <= x.at { + s + } else if s >= x.at + x.removed { + moved(s) + } else { + x.at + }; + // An end inside the removed text goes to the end of the new text. + e = if e < x.at || (e == x.at && x.removed > 0) { + e + } else if e >= x.at + x.removed { + moved(e) + } else { + x.at + x.inserted + }; + } + let e = e.min(index.len()); + Ok((index, s.min(e), e, stamp)) + }) +} + +/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`. +/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the +/// same story read from its other frames record the edit too, when they knew the text before it. +fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> { + with_doc(h, story.doc, |_, st| { + if text_of(st, story.id).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let frames = charged_frames(h, st, story.id)?; + let now = story_text(st, &frames); + let (a, b) = (before.byte(at, false), before.byte(at + removed, true)); + let expected = before.text.len() - (b - a) + inserted.len() == now.len() + && now.as_bytes().starts_with(&before.text.as_bytes()[..a]) + && now.as_bytes().ends_with(&before.text.as_bytes()[b..]) + && now.get(a..a + inserted.len()) == Some(inserted); + let members: HashSet = frames.iter().map(|f| f.0).collect(); + let index = Rc::new(Index::new(now)); + let inserted = inserted.encode_utf16().count(); + let mut logs = h.dom.text.stories.logs.borrow_mut(); + let mut found = false; + for (&(uid, anchor), l) in logs.iter_mut() { + if uid != st.uid || !members.contains(&anchor) { + continue; + } + let own = anchor == story.id.0; + let current = l.reverts == st.reverts; + if !own { + h.charge_call(l.index.text.len() as u64)?; + if !expected || !current || l.index.text != before.text { + continue; + } + } + found |= own; + if expected && current { + l.push(at, removed, inserted); + } else { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = index.clone(); + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) } + }) +} + +/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with +/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in +/// place while the frames after it flow again. +fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> { + loop { + let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| { + if text_of(st, story.id).is_none() { + return Err(HostError::Error(STALE_STORY.into())); + } + let mut at = 0; + let spans = charged_frames(h, st, story.id)? + .into_iter() + .map(|f| { + let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum()); + at += n; + (f, at - n, at) + }) + .collect(); + Ok(spans) + })?; + let target = + if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) }; + let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) }; + let item = Item { doc: story.doc, id: f }; + if x <= a { + edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?; + return Ok(()); + } + edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?; + b = x; + } +} + +fn write_contents(h: &Host, r: StorySpan, value: &Data) -> Answer { + let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; + let insert = from_script(v); + let (index, s, e, _) = resolve(h, r)?; + let (a, b) = (index.byte(s, false), index.byte(e, true)); + if index.text[a..b] == insert { + return Ok(Data::Undefined); + } + let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count()); + replace(h, r.story, a, b, &insert)?; + record(h, r.story, &index, s, e - s, &insert)?; + Ok(Data::Undefined) +} + +fn span_contents(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_span(h, a)?)?; + let (x, y) = (index.byte(s, false), index.byte(e, true)); + Ok(text(to_script(&index.text[x..y]))) +} + +fn span_set_contents(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_span(h, a)?, arg(a, 1)) +} + +fn span_remove(h: &Host, a: &[Data]) -> Answer { + write_contents(h, this_span(h, a)?, &text("")) +} + +fn span_start(h: &Host, a: &[Data]) -> Answer { + let (_, s, _, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float(s as u64))) +} + +fn span_end(h: &Host, a: &[Data]) -> Answer { + let (_, _, e, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float(e as u64))) +} + +fn span_length(h: &Host, a: &[Data]) -> Answer { + let (_, s, e, _) = resolve(h, this_span(h, a)?)?; + Ok(num(float((e - s) as u64))) +} + +fn span_story(h: &Host, a: &[Data]) -> Answer { + let r = this_span(h, a)?; + resolve(h, r)?; + Ok(story_ref(h, r.story)) +} + +fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer { + let (index, s, e, _) = resolve(h, this_span(h, a)?)?; + let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x); + Ok(num(float(p as u64))) +} + +fn span_part(h: &Host, a: &[Data], class: &str) -> Answer { + let r = this_span(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(span_ref(h, r.story, s, e, stamp, class)) +} + +fn span_characters(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryCharacters") +} + +fn span_words(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryWords") +} + +fn span_paragraphs(h: &Host, a: &[Data]) -> Answer { + span_part(h, a, "StoryParagraphs") +} + +fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> { + let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p); + let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?; + Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part)) +} + +fn part_typename(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + resolve(h, r)?; + Ok(text(match part { + Part::Characters => "Characters", + Part::Words => "Words", + Part::Paragraphs => "Paragraphs", + })) +} + +fn span_typename(h: &Host, a: &[Data]) -> Answer { + resolve(h, this_span(h, a)?)?; + Ok(text("TextRange")) +} + +fn story_typename(h: &Host, a: &[Data]) -> Answer { + this_story(h, a)?; + Ok(text("Story")) +} + +fn part_length(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let (index, s, e, _) = resolve(h, r)?; + Ok(num(float(part_spans(&index, part, s, e).0.len() as u64))) +} + +fn part_parent(h: &Host, a: &[Data]) -> Answer { + let (r, _) = this_part(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(span_ref(h, r.story, s, e, stamp, "StoryRange")) +} + +fn part_at(h: &Host, a: &[Data]) -> Answer { + let (r, part) = this_part(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let (index, s, e, stamp) = resolve(h, r)?; + let (items, spans) = part_spans(&index, part, s, e); + let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) }; + let span = match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange"))) +} + +// ---- Stories ---- + +fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("Stories", &[float(h.run), float(doc.uid)])) +} + +/// `document.stories`. +pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember { + get(link, doc_stories_impl) +} + +/// The first frame of each story of the document in paint order, kept while the document is +/// unchanged. +fn heads(h: &Host, st: &DocState) -> std::result::Result>, HostError> { + if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow() + && *uid == st.uid + && std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc)) + { + return Ok(ids.clone()); + } + let ids = frame_ids(h, st); + h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::())?; + // A frame listed by an earlier thread belongs to that one, as `story_of` finds it. + let (mut threaded, mut first) = (HashSet::new(), HashSet::new()); + let mut seen = HashSet::new(); + for thread in &st.doc.text_threads { + let live: Vec = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect(); + if live.len() >= 2 { + first.insert(live[0]); + threaded.extend(live); + } + } + let heads: Vec = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect(); + let heads = Rc::new(heads); + *h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone())); + Ok(heads) +} + +fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Stories") +} + +fn stories_length(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?; + Ok(num(float(n as u64))) +} + +fn stories_typename(h: &Host, a: &[Data]) -> Answer { + stories_doc(h, a)?; + Ok(text("Stories")) +} + +fn stories_parent(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn stories_at(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?; + Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id }))) +} + +/// `stories.index(key)`: by number, or by the name of a story's first frame. +fn stories_index(h: &Host, a: &[Data]) -> Answer { + let doc = stories_doc(h, a)?; + match arg(a, 1) { + Data::Number(_) => match stories_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + Data::String(name) => { + let id = with_doc(h, doc, |_, st| { + let list = heads(h, st)?; + h.charge_call(list.len() as u64)?; + Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str()))) + })?; + id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + } + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +// ---- classes ---- + +/// A member of the range of a story of two or more frames that is not available yet: reading or +/// assigning it throws, after the check that the range is still there. +fn range_later(link: &Link, name: &'static str) -> (String, HostMember) { + let message = format!("TextRange.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + resolve(&h, this_span(&h, &a)?)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +/// The members of `TextFrame` this module adds. +pub(super) fn frame_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("nextFrame", property(l, next_frame, set_next_frame)), + ("previousFrame", property(l, previous_frame, set_previous_frame)), + ("story", get(l, frame_story)), + ]) +} + +/// `TextRange.story`. +pub(super) fn range_member(l: &Link) -> (String, HostMember) { + ("story".into(), get(l, range_story)) +} + +/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames. +pub(super) fn classes(l: &Link) -> Vec { + let mut story = named(vec![ + ("typename", get(l, story_typename)), + ("parent", get(l, story_parent)), + ("length", get(l, story_length)), + ("textFrames", get(l, story_frames)), + ("textRange", get(l, story_text_range)), + ("characters", get(l, story_characters)), + ("words", get(l, story_words)), + ("paragraphs", get(l, story_paragraphs)), + ]); + story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| later(l, "Story", m))); + let mut range = named(vec![ + ("typename", get(l, span_typename)), + ("parent", get(l, span_story)), + ("story", get(l, span_story)), + ("contents", property(l, span_contents, span_set_contents)), + ("start", read_only(l, span_start, "TextRange", "start")), + ("end", read_only(l, span_end, "TextRange", "end")), + ("characterOffset", read_only(l, span_start, "TextRange", "characterOffset")), + ("length", read_only(l, span_length, "TextRange", "length")), + ("characters", get(l, span_characters)), + ("words", get(l, span_words)), + ("paragraphs", get(l, span_paragraphs)), + ("getParagraphLength", method(l, span_paragraph_length)), + ("remove", method(l, span_remove)), + ]); + range.extend( + [ + "lines", + "insertionPoints", + "textRanges", + "characterAttributes", + "paragraphAttributes", + "kerning", + "characterStyles", + "paragraphStyles", + "textSelection", + "changeCaseTo", + "select", + "deSelect", + "duplicate", + "move", + "getTextRunLength", + "getLocalCharOverridesJSON", + "getLocalParaOverridesJSON", + ] + .into_iter() + .chain(ATTRS.iter().map(|(n, _)| *n)) + .map(|m| range_later(l, m)), + ); + let part = |name: &'static str| { + class( + name, + None, + named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + Some(function(l, part_at)), + ) + }; + vec![ + class("Story", None, story, None), + class("StoryRange", None, range, None), + part("StoryCharacters"), + part("StoryWords"), + part("StoryParagraphs"), + class( + "Stories", + None, + named(vec![ + ("typename", get(l, stories_typename)), + ("length", get(l, stories_length)), + ("parent", get(l, stories_parent)), + ("index", method(l, stories_index)), + ]), + Some(function(l, stories_at)), + ), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2a81daeb..c9326a496c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -179,6 +179,7 @@ mod script_include; mod script_io; mod script_run; mod script_text; +mod script_threads; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs new file mode 100644 index 0000000000..6d919a21d9 --- /dev/null +++ b/crates/engine/src/tests/script_threads.rs @@ -0,0 +1,596 @@ +//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`, +//! `document.stories`, and the text of a story of several frames. + +use serde_json::{Value, json}; + +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +fn new_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap(); + s +} + +/// Area type `width` × `height` at `x` holding `text`. +fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId { + let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn plain(s: &Session, id: NodeId) -> String { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.plain_text(), + _ => panic!("not text"), + } +} + +fn threads(s: &Session) -> Vec> { + s.active().unwrap().doc.text_threads.clone() +} + +/// The text of every frame of the document's threads, in thread order. +fn story(s: &Session, frames: &[NodeId]) -> String { + frames.iter().map(|f| plain(s, *f)).collect() +} + +/// Two area frames threaded into one story whose text starts in the first, one line high, and +/// flows on into the second. +fn threaded(text: &str) -> (Session, NodeId, NodeId) { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 90.0, 18.0, text); + let b = area(&mut s, 150.0, 200.0, 200.0, ""); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![vec![a, b]]); + (s, a, b) +} + +const STORY: &str = "alpha beta gamma\ndelta \u{1F600}"; + +#[test] +fn stories_list_one_story_for_each_thread_and_each_frame_in_none() { + let (mut s, _, _) = threaded(STORY); + area(&mut s, 400.0, 120.0, 40.0, "Alone"); + let out = log( + &mut s, + "var d = app.activeDocument, st = d.stories[0];\ + vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\ + vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\ + vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\ + vc.log(d.stories[1].textFrames[0].contents); vc.log(d.stories[1].textFrames.length);\ + d.textFrames.add(); vc.log(d.stories.length);\ + vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\ + vc.log(d.textFrames[2].story.textFrames[0].contents);", + ); + assert_eq!( + out, + vec![ + json!(2), + json!("Story"), + json!(2), + json!(true), + json!(true), + json!("Alone"), + json!(1), + json!(3), + json!("Document"), + json!("Document"), + json!("Stories"), + json!("Alone") + ] + ); +} + +#[test] +fn a_story_range_counts_utf16_units_across_its_frames() { + let (mut s, a, b) = threaded(STORY); + let (first, second) = (plain(&s, a), plain(&s, b)); + assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}"); + assert_eq!(first.clone() + &second, STORY); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, r = st.textRange;\ + vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\ + vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\ + vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\ + vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\ + vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);", + ); + assert_eq!( + out, + vec![ + json!(25), + json!(25), + json!("alpha beta gamma\rdelta \u{1F600}"), + json!("TextRange"), + json!(24), + json!(5), + json!(2), + json!("alpha beta gamma\r"), + json!("\u{1F600}"), + json!(23), + json!(8), + json!(25), + json!(true) + ] + ); +} + +/// The members a long story's range does not have yet throw that they are not available, and +/// first that a range that went stale is stale. +#[test] +fn a_story_range_names_the_members_it_does_not_have_yet() { + let (mut s, _, b) = threaded(STORY); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].story.textRange;\ + try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\ + try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\ + try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }", + ); + assert_eq!( + out, + vec![ + json!("TextRange.characterAttributes is not available yet"), + json!("TextRange.size is not available yet"), + json!("Story.lines is not available yet") + ] + ); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); +} + +/// Ranges of one story read from different frames keep their places through each other's edits. +#[test] +fn story_ranges_read_from_different_frames_follow_each_others_edits() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\ + x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\ + vc.log(t[1].story.textRange.contents);", + ); + assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]); +} + +/// A story range that an edit covers holds the edit's new text, as a frame's range does. +#[test] +fn a_story_range_an_edit_covers_holds_the_new_text() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\ + st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);", + ); + assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]); +} + +#[test] +fn a_story_edit_across_frames_reflows_in_one_undo_step() { + let (mut s, a, b) = threaded(STORY); + let before = undo_steps(&s); + let out = log( + &mut s, + "var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\ + var p = st.paragraphs[0], tail = st.paragraphs[1];\ + p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\ + try { frame.contents; } catch (e) { vc.log(String(e.message)); }\ + st.words[2].remove(); vc.log(st.textRange.contents);", + ); + assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]); + assert_eq!(story(&s, &[a, b]), "X\ndelta "); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(story(&s, &[a, b]), STORY); +} + +#[test] +fn a_story_range_is_stale_after_another_change_to_the_story() { + let (mut s, _, b) = threaded(STORY); + let message = failure( + &mut s, + &format!( + "var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;", + b.0 + ), + ); + assert!(message.contains("Stale text range"), "{message}"); +} + +#[test] +fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() { + let (mut s, _, _) = threaded(STORY); + let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + "var r = app.activeDocument.textFrames[0].story.words[1];\ + vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\ + var st = app.activeDocument.textFrames[0].story;\ + vc.log(st.textFrames.length); vc.log(st.textRange.contents);\ + try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\ + vc.log(st.words[1].contents);", + ); + let _ = std::fs::remove_file(&path); + assert_eq!(out[0], json!(2), "the reverted file keeps the thread"); + assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text"); + assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}"); + assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text"); +} + +#[test] +fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "First story."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Second."); + let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [p.0]})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames; t[0].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[0].story.textRange.contents);\ + t[0].nextFrame = t[1];", + ); + assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]); + assert_eq!(threads(&s), vec![vec![a, b]]); + assert_eq!(story(&s, &[a, b]), "First story.Second."); + assert_eq!(undo_steps(&s), before + 1); + assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]); + // previousFrame links the other way. + s.execute("edit.undo", &json!({})).unwrap(); + assert!(threads(&s).is_empty()); + assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into())); + log(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + assert_eq!(threads(&s), vec![vec![b, a]]); + assert_eq!(story(&s, &[b, a]), "Second.First story."); +} + +#[test] +fn null_breaks_the_link_and_each_frame_keeps_its_text() { + let (mut s, a, b) = threaded(STORY); + let (first, second) = (plain(&s, a), plain(&s, b)); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames, st = t[1].story; t[1].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[0].nextFrame);\ + t[0].nextFrame = null;", + ); + assert_eq!(out, vec![json!(2), json!(1), json!(null)]); + assert!(threads(&s).is_empty()); + assert_eq!((plain(&s, a), plain(&s, b)), (first, second)); + assert_eq!(undo_steps(&s), before + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![vec![a, b]]); +} + +#[test] +fn area_and_path_text_thread_the_new_frame_to_a_base_frame() { + let mut s = new_doc(); + let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it."); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap(); + s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\ + var after = d.textFrames.areaText(p[1], undefined, base);\ + var first = d.textFrames.areaText(p[2], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[3], undefined, undefined, undefined, after, true);\ + vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]); + let t = threads(&s); + assert_eq!(t.len(), 1); + assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn a_bad_base_frame_is_refused_before_a_frame_is_made() { + let mut s = new_doc(); + s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap(); + let count = |s: &Session| s.active().unwrap().doc.node_count(); + let (n, before) = (count(&s), undo_steps(&s)); + let d = "var d = app.activeDocument, p = d.pageItems;"; + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, p[1]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0], 'yes');")).contains("postFix")); + assert_eq!((count(&s), undo_steps(&s)), (n, before)); +} + +/// A base frame given with a path inside a compound path is refused before the path is turned +/// into type, so a script that catches the error finds the path as it was. +#[test] +fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() { + let mut s = new_doc(); + area(&mut s, 10.0, 120.0, 60.0, "Base."); + let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, p = null;\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\ + try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\ + vc.log(p.typename); vc.log(d.textFrames.length);", + ); + assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]); + assert_eq!(undo_steps(&s), before); +} + +/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds +/// now, to check that a refused change left it alone. +fn three() -> (Session, [NodeId; 4]) { + let (mut s, a, b) = threaded(STORY); + let c = area(&mut s, 400.0, 120.0, 40.0, "Third"); + let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap()); + (s, [a, b, c, p]) +} + +fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec>, Vec, usize)) { + assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::>(), undo_steps(s)), *before); +} + +fn state(s: &Session, ids: &[NodeId]) -> (Vec>, Vec, usize) { + (threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s)) +} + +#[test] +fn a_link_to_the_frame_itself_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];"); + assert!(m.contains("nextFrame") && m.contains("itself"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_link_that_makes_a_loop_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + assert!(m.contains("loop"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_link_into_the_middle_of_a_story_is_refused() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); + assert!(m.contains("already has a previous frame"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[0];"); + assert!(m.contains("already has a next frame"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn point_type_and_other_values_cannot_be_linked() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = 5;"); + assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = undefined;"); + assert!(m.contains("TextFrame or null"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_hidden_or_locked_frame_in_either_story_stops_a_link() { + let (mut s, ids) = three(); + log(&mut s, "app.activeDocument.textFrames[1].locked = true;"); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + assert!(m.contains("hidden or locked"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].nextFrame = null;"); + assert!(m.contains("hidden or locked"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_frame_of_another_document_cannot_be_linked() { + let (mut s, ids) = three(); + let before = state(&s, &ids); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); + let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); + assert!(m.contains("different documents"), "{m}"); + let m = failure(&mut s, "app.documents[1].textFrames.areaText(app.documents[1].pageItems[0], undefined, app.documents[0].textFrames[2]);"); + assert!(m.contains("another document") || m.contains("PathItem"), "{m}"); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + unchanged(&s, &ids, &before); +} + +#[test] +fn a_deleted_frame_makes_its_story_and_links_stale() { + let (mut s, _, _) = threaded(STORY); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.length;"); + assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); + assert!(m.contains("Stale page item"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); + assert!(m.contains("Stale text range"), "{m}"); + // A story read from a frame that stays follows it when its link is broken. + let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[1].story; t[0].nextFrame = null; vc.log(st.textFrames.length);"); + assert_eq!(out, vec![json!(1)]); +} + +#[test] +fn stories_refuse_bad_keys_and_huge_numbers() { + let (mut s, _, _) = threaded(STORY); + let out = log( + &mut s, + "var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);", + ); + assert_eq!(out, vec![json!(true), json!(true), json!(true)]); + assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError")); + log(&mut s, "app.activeDocument.textFrames[0].name = 'Lead';"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]); +} + +#[test] +fn a_long_story_walks_to_its_end_and_refuses_a_loop() { + let mut s = new_doc(); + let ids: Vec = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect(); + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(threads(&s), vec![ids.clone()]); + let out = log( + &mut s, + "var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \ + vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(120), json!(120), json!(1)]); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];"); + assert!(m.contains("loop"), "{m}"); + unchanged(&s, &ids, &before); +} + +/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame +/// once, so a walk along `nextFrame` ends. +#[test] +fn a_thread_listing_a_frame_twice_is_walked_once() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]]; + let out = log( + &mut s, + "var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \ + vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);", + ); + assert_eq!(out, vec![json!(2), json!(2), json!(1)]); + let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]})); + assert!(threads(&s).is_empty()); +} + +/// A story and its range keep the exact id of the frame they were read from, also past 2^53. +#[test] +fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() { + let mut s = new_doc(); + // The second frame's id, 2^53 + 1, is not exact as a number. + let big = 1u64 << 53; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + assert_eq!((a.0, b.0), (big, big + 1)); + s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap(); + let out = log( + &mut s, + "var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\ + st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);", + ); + // The whole story flows into the first frame, so the second is empty once the link is broken. + assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]); +} + +#[test] +fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + s.execute("select.none", &json!({})).unwrap(); + let before = undo_steps(&s); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]})); + let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(undo_steps(&s), before + 1); + assert!(s.active().unwrap().selection.objects.is_empty()); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]})); + let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r["changed"], json!(false)); + assert_eq!(undo_steps(&s), before + 2); + for bad in [ + json!({"id": a.0, "side": "up", "neighbor": b.0}), + json!({"id": a.0, "side": "next"}), + json!({"id": a.0, "side": "next", "neighbor": 999_999}), + ] { + assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}"); + } + assert_eq!(undo_steps(&s), before + 2); +} + +/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered +/// paragraphs count from 1, also when that story keeps two frames. +#[test] +fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() { + let mut s = new_doc(); + let items = (1..=12).map(|i| format!("Item {i}")).collect::>().join("\n"); + let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")]; + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "list": "number"})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let numbers = |s: &Session, id: NodeId| { + let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") }; + assert!(!t.first_para_continues, "every frame starts a paragraph"); + vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::>() + }; + let first = numbers(&s, ids[0]); + assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items"); + assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1.")); + let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap(); + assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]})); + let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat(); + let expected: Vec = (1..=later.len()).map(|n| format!("{n}.")).collect(); + assert_eq!(later, expected, "the later story counts from 1"); + assert_eq!(numbers(&s, ids[0]), first); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index c7e7000f13..b638262389 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -90,7 +90,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames typename \ + rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames typename \ views views= width", ), ("Layer.", "prototype"), @@ -135,7 +135,7 @@ const INSIDE: &[(&str, &str)] = &[ contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \ insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \ opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \ - rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \ + rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \ textSelection= words", ), ("TextRange.", "prototype"), @@ -147,7 +147,7 @@ const INSIDE: &[(&str, &str)] = &[ getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ - story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ + story strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ tracking tracking= typename underline underline= verticalScale verticalScale= words", ), ("Characters.", "prototype"), @@ -176,6 +176,34 @@ const INSIDE: &[(&str, &str)] = &[ ("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"), ("TextOrientation.", "HORIZONTAL VERTICAL"), ("TextType.", "AREATEXT PATHTEXT POINTTEXT"), + ("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"), + ("Stories.", "prototype"), + ("Stories.prototype.", "constructor index length parent typename"), + ("Story.", "prototype"), + ( + "Story.prototype.", + "characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \ + textRanges textRanges= textSelection textSelection= typename words", + ), + ("StoryRange.", "prototype"), + ( + "StoryRange.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \ + characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \ + contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \ + getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \ + getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \ + length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \ + paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \ + strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \ + underline underline= verticalScale verticalScale= words", + ), + ("StoryCharacters.", "prototype"), + ("StoryCharacters.prototype.", "constructor length parent typename"), + ("StoryWords.", "prototype"), + ("StoryWords.prototype.", "constructor length parent typename"), + ("StoryParagraphs.", "prototype"), + ("StoryParagraphs.prototype.", "constructor length parent typename"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` diff --git a/docs/gaps.md b/docs/gaps.md index 47a1680f6e..2a6e8005f9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,10 +807,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads - of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open +- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes) + and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and - character and paragraph attributes, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, their links to each other and the stories they form, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index a75c5386f5..2f81d1838d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2728,9 +2728,36 @@ app through the global object `vc`, and writes to the Script Console and runs ot the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws - `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and + `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and `orientation` cannot be set yet. +- Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, + https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a + `TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end), + and `story`; a `TextRange` has `story` too. Assigning `nextFrame` or `previousFrame` runs `text.thread.setNeighbor`: + a frame links the last frame of one story to the first frame of another, whose text flows on after the first story's + text, and `null` breaks that link, no text moving across it. `areaText(path, orientation?, baseFrame?, + postFix?)` and `pathText(path, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)` thread the new frame + after `baseFrame`, or before it when `postFix` is false, with `text.thread.add`; `startTValue` and `endTValue` are + not available yet. `Document.stories` lists the stories with `length`, `[i]` and `index(key)`. A `Story` has + `parent` (its document), `length`, `textFrames` (an array of its frames in thread order), `textRange`, `characters`, + `words` and `paragraphs`; `lines`, `insertionPoints`, `textRanges` and `textSelection` are not available yet. + VectorCraft's own rules: point type, a frame of another document, the frame itself, a frame inside a story, a link + that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the + link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out, + and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type. + `Document.stories` lists one story for each type object in no thread and one for each thread, in the paint order of + their first frames, and `index` with a string finds the first story whose first frame has that name. A frame that + a stored thread lists twice is in its story once. A `Story` is + the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is + deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its + frames' text in thread order, counted in UTF-16 units: its `textRange` reads and writes across the frames, and + writing it edits the frames from the last one it reaches back to the first, inside the run's one undo step, and the + story then flows through its frames again. Such a range has `contents`, `start`, `end`, `characterOffset`, + `length`, `parent` and `story` (its story), `characters`, `words`, `paragraphs`, `getParagraphLength()` and + `remove()`; its character and paragraph attributes and the other members are not available yet. It keeps its place + through edits made through the story's ranges and throws `Stale text range` after any other change to the story's + text and after `file.revert`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -11523,6 +11550,18 @@ after it (`out`). The whole story flows into the frames before the break; the fr threaded with each other when two or more remain, and the first of them starts a paragraph. It refuses an `id` that doesn't exist, a `port` other than `in` or `out`, and a side where no frame of a thread comes before or after `id`. +`text.thread.setNeighbor {id, side: "next" | "previous", neighbor: id | null}` is what a script's `nextFrame` and +`previousFrame` assignments run, and needs no selection. With an id it links area type or type on a path `id` to +`neighbor` after it (`next`) or before it (`previous`): `id` must be the last frame of its story for `next` (the first +for `previous`) and `neighbor` the first (the last) frame of another story, and the second story's text flows on after +the first's (one undo step, Thread Text). With `null` it breaks the link on that side, and the frames on each side +form a story of their own (one undo step, Break Thread): no text moves across the break, and the frames after it flow +their own text again from their first frame, which now starts a paragraph. It refuses point type and +other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a story with a +hidden or locked frame, with nothing changed. A link that is already there, or a break where there is no link, changes +nothing and records no undo step. The selection is kept. It returns `{changed, threads}`, `threads` listing the +stories of the frames involved after the change, a story of one frame as `[id]`. + `select.same.linkBlockSeries` (Select › Same › Link Block Series) selects every frame of the threads that the selected type objects, and the type inside selected groups, are in, in thread order, and returns `{count}`. Type in no thread selects itself, and other selected objects are left out. With frames of several threads selected, it selects the frames diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..355a11543a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From c7671c615b5df2ad0f607368fd36d06b8b36a6f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:02:47 -0800 Subject: [PATCH 034/104] Scripts: style objects see a style a batch removes and adds again - A style object goes stale when the steps of one `command.batch` remove its style and add another under the same name, as it does when separate `vc.run` calls do. The session notes each batch step's style lists while a script runs, and the style objects check each of them. - `add(name)` with all 4,096 style slots of the run taken throws before it adds the style; with one slot left it adds it. - `typename` of a removed style's `characterAttributes` or `paragraphAttributes` throws `Stale style`, as its other members do. - The style load commands refuse `data` over 64 MB without copying it. - docs/mcp.md states the 64 MB limit for `data` and decoded `dataBase64`; docs/gaps.md G6 and the docs/roadmap.md M13 row list the script text and style members. --- crates/engine/src/cmd/textstyles.rs | 8 ++--- crates/engine/src/cmd/textstyles/tests.rs | 3 ++ crates/engine/src/lib.rs | 4 +++ crates/engine/src/script/dom/text/styles.rs | 37 ++++++++++++++++++--- crates/engine/src/script/mod.rs | 22 ++++++++++++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/execute.rs | 3 ++ crates/engine/src/tests/script_styles.rs | 21 ++++++++++++ docs/gaps.md | 2 +- docs/mcp.md | 3 +- docs/roadmap.md | 2 +- 11 files changed, 94 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 3b57c2e067..3b64929cc2 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -1270,11 +1270,11 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { }; let path = str_param(p, "path"); let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); - let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?, - (None, Some(text), _) => text.as_bytes().to_vec(), + let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(), + (None, Some(text), _) => text.as_bytes().into(), (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), - (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, + (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(), _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; if bytes.len() > MAX_LOAD_BYTES { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 1f8511d7ac..f2d2354000 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -845,6 +845,9 @@ fn loading_refuses_a_file_larger_than_64_mb() { let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let text = " ".repeat(MAX_LOAD_BYTES + 1); + let r = s.execute("textStyle.loadAll", &json!({"data": text})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); assert_eq!(s.doc().unwrap().doc, before); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..335c83eebb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -309,6 +309,10 @@ pub struct Session { pub script_frames: bool, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, + /// The style lists each step of a batch a script runs left in a document whose lists it + /// changed: its uid, revert count, and character and paragraph style lists + /// ([`script::note_style_lists`]). + pub(crate) script_style_trail: Vec, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// Write recovery copies of the unsaved documents before a run, and don't start without them. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 841d006ac6..2b40d92bcd 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -75,13 +75,20 @@ pub(super) struct StyleState { } /// Marks stale each style object whose style the command just run removed or renamed, so a style -/// removed and made again under its name by later commands is another style. A document whose -/// style lists did not change is not checked again. +/// removed and made again under its name by later commands, or by later steps of the same batch, +/// is another style. A document whose style lists did not change is not checked again. pub(in crate::script) fn after_command(h: &Host) { + let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); let mut slots = h.dom.text.styles.slots.borrow_mut(); if !slots.iter().any(|s| s.live) { return; } + for (uid, reverts, c, p) in &trail { + for slot in slots.iter_mut().filter(|x| x.live && x.uid == *uid) { + let list = if slot.para { p } else { c }; + slot.live = slot.reverts == *reverts && (slot.name == normal(slot.para) || list.iter().any(|d| d.name == slot.name)); + } + } let s = h.session.borrow(); let mut seen = h.dom.text.styles.seen.borrow_mut(); seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); @@ -173,6 +180,10 @@ fn stale() -> HostError { HostError::Error(STALE_STYLE.into()) } +fn held_too_many() -> HostError { + HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run")) +} + /// The style object for the style `name` of the document `uid`: the same slot as every other /// object naming it in this run. fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { @@ -182,7 +193,7 @@ fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { Some(i) => i, None => { if slots.len() >= MAX_HELD { - return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); + return Err(held_too_many()); } slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); slots.len() - 1 @@ -416,6 +427,18 @@ fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { } } +/// The `typename` of a style's `characterAttributes`, which throws once the style is gone. +fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, false)?; + Ok(text("CharacterAttributes")) +} + +/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone. +fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, true)?; + Ok(text("ParagraphAttributes")) +} + fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { let (_, m) = attrs_of(h, a, false)?; Ok(char_value(h, attr, &m)) @@ -651,6 +674,10 @@ fn list_add(h: &Host, a: &[Data]) -> Answer { if with_doc(h, doc, |_, st| has_style(st, para, &name)) { return Err(HostError::Error(format!("a style named {name} already exists"))); } + // The new style needs a slot of its own: a run that names as many styles as it may adds none. + if h.dom.text.styles.slots.borrow().len() >= MAX_HELD { + return Err(held_too_many()); + } run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; // An object of a removed style of this name stays stale. forget(h, doc.uid, para, std::slice::from_ref(&name)); @@ -738,9 +765,9 @@ pub(super) fn classes(l: &Link) -> Vec { Some(function(l, list_at)), ) }; - let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + let mut chars = named(vec![("typename", get(l, attrs_typename_char))]); chars.extend(char_members(l)); - let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + let mut paras = named(vec![("typename", get(l, attrs_typename_para))]); paras.extend(para_members(l)); vec![ style(false), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index e537ab8ef7..18e24f1c36 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1236,6 +1236,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); + s.script_style_trail.clear(); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1353,6 +1354,27 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( crossed.map(|data| (data, value)) } +/// A document's uid, revert count, and character and paragraph style lists. +pub(crate) type StyleLists = + (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); + +/// After a step of a batch a script runs: notes the style lists of each document whose lists or +/// revert count the step changed, so the style objects see a style the batch removed and made +/// again under its name as another style ([`dom::after_command`]). +pub(crate) fn note_style_lists(s: &mut Session) { + for st in &s.docs { + let last = s.script_style_trail.iter().rev().find(|(uid, ..)| *uid == st.uid); + let same = last.is_some_and(|(_, reverts, c, p)| { + *reverts == st.reverts + && vectorcraft_doc::Shared::ptr_eq(c, &st.doc.char_styles) + && vectorcraft_doc::Shared::ptr_eq(p, &st.doc.para_styles) + }); + if !same { + s.script_style_trail.push((st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + } + } +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..52852308e3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,6 +165,7 @@ impl Session { script_runs: 0, script_frames: false, script_high_water: Default::default(), + script_style_trail: Vec::new(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..f0eabe06dd 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -84,6 +84,9 @@ impl Session { self.execute_spec(spec, id, params) }; self.reading = outer; + if self.script_in_run && self.depth > 0 && r.is_ok() { + crate::script::note_style_lists(self); + } r } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 759e41eae1..860aecfa81 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -165,6 +165,19 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { ), ); assert!(e.contains("Stale style"), "{e}"); + // So is a style removed and made again by the steps of one batch. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \ + {{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // The attributes object of a removed style throws for its typename too. + let e = + failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); + assert!(e.contains("Stale style"), "{e}"); // A style renamed by a command is stale too, and its text keeps its look after a removal. let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); assert!(e.contains("Stale style"), "{e}"); @@ -359,6 +372,14 @@ fn a_run_names_at_most_4096_styles() { assert_eq!(out, [json!(false), json!(4101)]); let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); assert!(e.contains("4096 styles"), "{e}"); + // `add` with every slot taken adds no style; with one slot left it adds the style. + let out = log( + &mut s, + &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"), + ); + assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);")); + assert_eq!(out, [json!("New"), json!(4102)]); } /// A script loads styles from a file only where it may read files; a file outside that is refused. diff --git a/docs/gaps.md b/docs/gaps.md index 47a1680f6e..561946b6d0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and - character and paragraph attributes, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, its character and paragraph styles, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 411ef4ba07..0495483d8e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13112,7 +13112,8 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The 64 MB limit also applies to `data` and to the +decoded bytes of `dataBase64`; a `dataBase64` string too long to decode to 64 MB or less is refused before it is decoded. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..99e740189c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, and the installed fonts; the rest of the script document model (layers, artboards, paths, stories and threads of type, and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From a5690d2d35485db131a6adb6be3c9c5c3136993c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:08:05 -0800 Subject: [PATCH 035/104] Scripts: stories of one thread share their text index, and a deleted story's missing members say Stale story Stories read from different frames of one thread share one index of the story's text while the document is unchanged, instead of each keeping its own copy. A frame listed in two threads shares only with a story whose frames match. Story.lines, insertionPoints, textRanges and textSelection check the story first, so a story whose frame was deleted throws Stale story. The cross-document baseFrame test passes a rectangle of the other document and checks the error and that the rectangle stays a path. docs/mcp.md no longer says baseFrame and postFix throw, the text-frame entry in docs/target-app-parity.md no longer lists stories and threading as missing, and the M13 row in docs/roadmap.md lists text frames and stories. --- crates/engine/src/script/dom/text/threads.rs | 74 +++++++++++++++----- crates/engine/src/tests/script_threads.rs | 27 ++++++- docs/mcp.md | 4 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index ee81129944..cfdb4119c6 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -34,7 +34,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ use super::super::{ Answer, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get, handle_of, - id_of, id_parts, in_compound, item_of, item_ref, later, method, named, num, property, text, whole, with_doc, + id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, text, whole, with_doc, }; use super::{ ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched, @@ -284,7 +284,8 @@ fn story_text(st: &DocState, frames: &[NodeId]) -> String { frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect() } -/// The story's index and its generation now, read again when its document changed. +/// The story's index and its generation now, read again when its document changed. The stories +/// read from the frames of one story share one index of its text while the document is unchanged. fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc, u64), HostError> { if text_of(st, anchor).is_none() { return Err(HostError::Error(STALE_STORY.into())); @@ -292,24 +293,45 @@ fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc {} - Some(l) => { - let frames = charged_frames(h, st, anchor)?; - let text = story_text(st, &frames); - if l.reverts != st.reverts || text != l.index.text { - l.stamp += 1; - l.floor = l.stamp; - l.edits.clear(); - l.index = Rc::new(Index::new(text)); + let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts; + if !logs.get(&key).is_some_and(current) { + let frames = charged_frames(h, st, anchor)?; + // Another frame of the same story read at this state of the document has the same text; + // a frame listed in two threads can belong to another story, so its frames must match. + let mut shared = None; + if frames.len() > 1 { + h.charge_call(frames.len() as u64)?; + if let Some((f, l)) = + frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l))) + && charged_frames(h, st, f)? == frames + { + shared = Some(l.index.clone()); } - l.doc = Arc::downgrade(&st.doc); - l.reverts = st.reverts; } - None => { - let frames = charged_frames(h, st, anchor)?; - let index = Rc::new(Index::new(story_text(st, &frames))); - logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + let index = match shared { + Some(index) => index, + None => { + let text = story_text(st, &frames); + match logs.get(&key) { + Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(), + _ => Rc::new(Index::new(text)), + } + } + }; + match logs.get_mut(&key) { + Some(l) => { + if l.reverts != st.reverts || index.text != l.index.text { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + } + l.index = index; + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() }); + } } } let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?; @@ -691,6 +713,20 @@ fn range_later(link: &Link, name: &'static str) -> (String, HostMember) { (name.to_string(), HostMember::Property { get: f.clone(), set: f }) } +/// A member of `Story` that is not available yet: reading or assigning it throws, after the check +/// that the story is still there. +fn story_later(link: &Link, name: &'static str) -> (String, HostMember) { + let message = format!("Story.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + this_story(&h, &a)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + /// The members of `TextFrame` this module adds. pub(super) fn frame_members(l: &Link) -> Vec<(String, HostMember)> { named(vec![ @@ -717,7 +753,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("words", get(l, story_words)), ("paragraphs", get(l, story_paragraphs)), ]); - story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| later(l, "Story", m))); + story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m))); let mut range = named(vec![ ("typename", get(l, span_typename)), ("parent", get(l, span_story)), diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index 6d919a21d9..433cc041e7 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -440,10 +440,16 @@ fn a_frame_of_another_document_cannot_be_linked() { let before = state(&s, &ids); s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); + s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap(); let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); assert!(m.contains("different documents"), "{m}"); - let m = failure(&mut s, "app.documents[1].textFrames.areaText(app.documents[1].pageItems[0], undefined, app.documents[0].textFrames[2]);"); - assert!(m.contains("another document") || m.contains("PathItem"), "{m}"); + let out = log( + &mut s, + "var d = app.documents[1], p = d.pageItems[1];\ + try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[2]); } catch (e) { vc.log(String(e.message)); }\ + vc.log(p.typename); vc.log(d.textFrames.length);", + ); + assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]); s.execute("document.activate", &json!({"index": 0})).unwrap(); unchanged(&s, &ids, &before); } @@ -453,6 +459,8 @@ fn a_deleted_frame_makes_its_story_and_links_stale() { let (mut s, _, _) = threaded(STORY); let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.length;"); assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.lines;"); + assert!(m.contains("Stale story"), "{m}"); let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); assert!(m.contains("Stale page item"), "{m}"); let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); @@ -520,6 +528,21 @@ fn a_thread_listing_a_frame_twice_is_walked_once() { assert!(threads(&s).is_empty()); } +/// When a frame is listed in two threads, a story read from a frame of the second thread reads +/// that thread's text, not the text of the story read before it from a shared frame. +#[test] +fn stories_of_threads_that_share_a_frame_keep_their_own_text() { + let mut s = new_doc(); + let a = area(&mut s, 10.0, 120.0, 60.0, "One."); + let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); + let c = area(&mut s, 300.0, 120.0, 60.0, "Three!"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]]; + let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[2].story.length);"); + let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count()); + assert_ne!(ab, bc); + assert_eq!(out, vec![json!(ab), json!(bc)]); +} + /// A story and its range keep the exact id of the frame they were read from, also past 2^53. #[test] fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() { diff --git a/docs/mcp.md b/docs/mcp.md index 99d79dd67c..5db12d3918 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2692,8 +2692,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation` - value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not - available yet. A `TextFrame` + value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and + `baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`, `AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`, `createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..ab191ea587 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 355a11543a..17698d2eb6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. From 997375be0d2190f956d304d8452f7ea4b9e2daf3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:27:14 -0800 Subject: [PATCH 036/104] Scripts: a batch keeps one copy of the style lists for its style objects While a script runs a `command.batch`, the session kept the style lists of every step that changed them, so each such step also made the next edit copy the whole list. The session now keeps one copy of each open document's lists, as the last step left them, and records the names of the styles a step removed or renamed and the documents a step reverted. The style objects check those names, so a style that a batch removes and makes again, or renames and names back, is still a different style. --- crates/engine/src/lib.rs | 7 +- crates/engine/src/script/dom/text/styles.rs | 13 ++-- crates/engine/src/script/mod.rs | 73 ++++++++++++++++----- crates/engine/src/session/documents.rs | 2 +- crates/engine/src/tests/script_styles.rs | 23 +++++++ 5 files changed, 93 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 335c83eebb..0cffcac358 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -309,10 +309,9 @@ pub struct Session { pub script_frames: bool, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, - /// The style lists each step of a batch a script runs left in a document whose lists it - /// changed: its uid, revert count, and character and paragraph style lists - /// ([`script::note_style_lists`]). - pub(crate) script_style_trail: Vec, + /// The styles the steps of a batch a script runs removed or renamed and the documents they + /// reverted ([`script::note_style_lists`]). + pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// Write recovery copies of the unsaved documents before a run, and don't start without them. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 2b40d92bcd..fd896918a9 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -76,17 +76,20 @@ pub(super) struct StyleState { /// Marks stale each style object whose style the command just run removed or renamed, so a style /// removed and made again under its name by later commands, or by later steps of the same batch, -/// is another style. A document whose style lists did not change is not checked again. +/// is another style. A document whose style lists did not change is not checked again. A live +/// slot's style was in its document's list when the command started, so a step that removed or +/// renamed it is in the trail's removed names. pub(in crate::script) fn after_command(h: &Host) { let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); let mut slots = h.dom.text.styles.slots.borrow_mut(); if !slots.iter().any(|s| s.live) { return; } - for (uid, reverts, c, p) in &trail { - for slot in slots.iter_mut().filter(|x| x.live && x.uid == *uid) { - let list = if slot.para { p } else { c }; - slot.live = slot.reverts == *reverts && (slot.name == normal(slot.para) || list.iter().any(|d| d.name == slot.name)); + for slot in slots.iter_mut().filter(|x| x.live) { + if trail.reverted.contains(&slot.uid) + || (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone()))) + { + slot.live = false; } } let s = h.session.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 18e24f1c36..e89bf94c06 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1236,7 +1236,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); - s.script_style_trail.clear(); + s.script_style_trail = StyleTrail::start(s); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1274,6 +1274,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value Ok((v, objects, bytes, save)) } Err(e) => { + s.script_style_trail = StyleTrail::default(); if let Some(save) = save && !save.restore(s) { @@ -1350,6 +1351,8 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( // Style objects follow only a command that is kept. if crossed.is_ok() { dom::after_command(host); + } else { + session.borrow_mut().script_style_trail = StyleTrail::default(); } crossed.map(|data| (data, value)) } @@ -1358,23 +1361,63 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( pub(crate) type StyleLists = (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); -/// After a step of a batch a script runs: notes the style lists of each document whose lists or -/// revert count the step changed, so the style objects see a style the batch removed and made -/// again under its name as another style ([`dom::after_command`]). -pub(crate) fn note_style_lists(s: &mut Session) { - for st in &s.docs { - let last = s.script_style_trail.iter().rev().find(|(uid, ..)| *uid == st.uid); - let same = last.is_some_and(|(_, reverts, c, p)| { - *reverts == st.reverts - && vectorcraft_doc::Shared::ptr_eq(c, &st.doc.char_styles) - && vectorcraft_doc::Shared::ptr_eq(p, &st.doc.para_styles) - }); - if !same { - s.script_style_trail.push((st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())); - } +/// What the steps of a command a script runs did to the documents' style lists +/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step +/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the +/// documents a step reverted. +#[derive(Default)] +pub(crate) struct StyleTrail { + lists: Vec, + pub(crate) gone: std::collections::HashSet<(u64, bool, String)>, + pub(crate) reverted: Vec, +} + +impl StyleTrail { + /// A trail that starts from the documents' style lists now. + fn start(s: &Session) -> Self { + let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); + StyleTrail { lists, ..Default::default() } } } +/// After a step of a batch a script runs: notes the styles the step removed or renamed and the +/// documents it reverted, so the style objects see a style the batch removed and made again under +/// its name as another style ([`dom::after_command`]). The trail keeps one copy of each open +/// document's lists, however many steps change them. +pub(crate) fn note_style_lists(s: &mut Session) { + let trail = &mut s.script_style_trail; + trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); + for st in &s.docs { + let (c, p) = (&st.doc.char_styles, &st.doc.para_styles); + let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else { + trail.lists.push((st.uid, st.reverts, c.clone(), p.clone())); + continue; + }; + if last.1 != st.reverts { + if !trail.reverted.contains(&st.uid) { + trail.reverted.push(st.uid); + } + } else { + for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] { + if vectorcraft_doc::Shared::ptr_eq(old, new) { + continue; + } + let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect(); + for d in old.iter().filter(|d| !names.contains(d.name.as_str())) { + trail.gone.insert((st.uid, para, d.name.clone())); + } + } + } + *last = (st.uid, st.reverts, c.clone(), p.clone()); + } +} + +/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]). +#[cfg(test)] +pub(crate) fn retained_style_lists(s: &Session) -> usize { + s.script_style_trail.lists.len() +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 52852308e3..c448541a23 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,7 +165,7 @@ impl Session { script_runs: 0, script_frames: false, script_high_water: Default::default(), - script_style_trail: Vec::new(), + script_style_trail: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 860aecfa81..12bded346f 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -174,6 +174,15 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { ), ); assert!(e.contains("Stale style"), "{e}"); + // And a style a batch renames and then names back. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \ + {{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); // The attributes object of a removed style throws for its typename too. let e = failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); @@ -191,6 +200,20 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { assert_eq!(runs(&s, id)[0].2, 40.0); } +/// The steps of one batch a script runs keep one copy of a document's style lists, however many of +/// them change the lists. +#[test] +fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() { + let (mut s, _) = doc_with("Hello"); + let commands: Vec = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect(); + s.script_in_run = true; + let r = s.execute("command.batch", &json!({"commands": commands})); + s.script_in_run = false; + r.unwrap(); + assert_eq!(char_names(&s).len(), 20); + assert_eq!(crate::script::retained_style_lists(&s), 1); +} + /// A removal or rename whose result cannot cross to the script is put back, and the style's object /// still names the style after it. #[test] From 98535b70d478342c341e616e1c8988db22ce26db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:07:39 -0800 Subject: [PATCH 037/104] Swatches: a swatch undone during a drag is not duplicated or deleted on drop When the drag's last checked state was gone from the undo history, the panel checked the dragged rows against the current document only. An undo of the step that made a dragged swatch, followed by a new swatch of the same name and paint before the panel was drawn again (for example two control requests handled in one frame), left the new swatch eligible for New Swatch and Delete Swatch. A dragged swatch deleted and brought back by an undo before the next check was eligible too, although the panel leaves it out when it sees the deletion. The panel now checks the dragged rows after every command the app runs, not only when it is drawn. For steps inside one command it also records the newest undo step, the one under it and the newest redo steps with the rows: - After an undo of the newest step, a row is kept only when the state the undo gave back, the states of the steps made since and the current state all hold it unchanged. - A row is also left out when a state that an undo left (kept by the redo steps made since) does not hold it unchanged. - When more than one step was undone, or steps were dropped past the history's limits, every row is left out of the drop. An undo of a step that left a dragged swatch alone still lets it be duplicated or deleted. HistoryEntry::serial exposes the step number that History::step already reports for the newest steps. --- crates/engine/src/history.rs | 6 + crates/ui-egui/src/app/commands.rs | 4 +- crates/ui-egui/src/panels/swatches.rs | 1 + crates/ui-egui/src/panels/swatches/actions.rs | 98 +++++++++++++--- crates/ui-egui/src/panels/swatches/tests.rs | 111 +++++++++++++++++- 5 files changed, 196 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index d472ec760c..51c38e8e09 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -109,6 +109,12 @@ impl HistoryEntry { self.named.as_ref().filter(|n| n.label() == self.label) } + /// A number no other step takes ([`History::step`]). Undo and Redo make the step they move + /// with a new number, and so does an edit merged into the newest step. + pub fn serial(&self) -> u64 { + self.serial + } + /// The step that undoing (redoing) the step `costs` came from makes: it keeps `doc`, the /// document before the undo, whose next state is now `now` (that step's document). Its figures /// are that step's the other way round when `doc` is still the document they were taken diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..b52addfe41 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -275,9 +275,11 @@ impl VectorcraftApp { } // A renamed spot color swatch stays the Color Guide's base; a deleted one ends the link. panels::color_guide::after_command(self, id, ¶ms, v, spot_base); - // A renamed color group stays selected in the Swatches panel. + // A renamed color group stays selected in the Swatches panel, and the rows dragged + // from its list are checked against what the command left. if let Some(ctx) = self.ui_ctx.clone() { panels::swatches::after_command(&ctx, id, ¶ms, v); + panels::swatches::follow_drag(self, &ctx); } if id == "file.new" { self.status(""); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index 41b42bfd60..0f6c0b1fe5 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -30,6 +30,7 @@ mod dnd; mod libraries; mod tiles; +pub(crate) use actions::follow_drag; pub use actions::menu; #[cfg(test)] use actions::{deletable, delete, mergeable, new_swatch, selected_group}; diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 7ba6fda3dd..5572e4f778 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -1,7 +1,7 @@ use std::sync::{Arc, Weak}; use vectorcraft_color::SwatchGroup; -use vectorcraft_engine::DocState; +use vectorcraft_engine::{DocState, History, HistoryEntry}; use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; @@ -149,14 +149,37 @@ impl HeldRow { } } -/// The rows being dragged from the list, in the order of the drag's names, and the document they -/// were last checked against. A row is `None` once a state of the document since the drag started -/// did not hold it unchanged: deleted, edited, or deleted and made again under its name, also with -/// the same paint. +/// The rows being dragged from the list, in the order of the drag's names, and the document and +/// undo history they were last checked against. A row is `None` once a state of the document since +/// the drag started did not hold it unchanged: deleted, edited, or deleted and made again under its +/// name, also with the same paint. #[derive(Clone, Default)] struct HeldRows { doc: Weak, + /// The newest undo step of the document and the one under it, and the next redo step and the + /// one under it ([`steps`]). + steps: [u64; 4], rows: Vec<(String, Option)>, + /// For each row, whether the document undoing the newest step gives back (that step's + /// document) holds it unchanged. + back: Vec, +} + +/// The newest undo step of `st` and the one under it, and the next redo step and the one under it +/// ([`HistoryEntry::serial`]), 0 for none. +fn steps(st: &DocState) -> [u64; 4] { + let serial = |list: &[HistoryEntry], back: usize| list.len().checked_sub(back).and_then(|i| list.get(i)).map_or(0, HistoryEntry::serial); + let h = &st.history; + [serial(&h.undo, 1), serial(&h.undo, 2), serial(&h.redo, 1), serial(&h.redo, 2)] +} + +impl HeldRows { + /// `rows`, checked against document `st` as it is now. + fn at(st: &DocState, rows: Vec<(String, Option)>) -> Self { + let last = st.history.undo.last(); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(last).is_some_and(|(r, e)| r.unchanged_in(&e.doc))).collect(); + HeldRows { doc: Arc::downgrade(&st.doc), steps: steps(st), rows, back } + } } /// Records the document and the rows a drag from the list started with this frame, so that New @@ -166,7 +189,7 @@ pub(super) fn drag_started(app: &VectorcraftApp, ctx: &egui::Context) { set_pstate(ctx, DRAG_DOC, st.map(|st| st.uid)); let held = match (st, egui::DragAndDrop::payload::(ctx).as_deref()) { (Some(st), Some(PanelDrag::Paint { rows: Some(r), .. })) => { - HeldRows { doc: Arc::downgrade(&st.doc), rows: r.names.iter().map(|n| (n.clone(), HeldRow::of(&st.doc, n))).collect() } + HeldRows::at(st, r.names.iter().map(|n| (n.clone(), HeldRow::of(&st.doc, n))).collect()) } _ => HeldRows::default(), }; @@ -174,26 +197,65 @@ pub(super) fn drag_started(app: &VectorcraftApp, ctx: &egui::Context) { } /// The dragged rows ([`HeldRows`]) checked against every state document `st` passed through since -/// they were last checked: the states its undo steps kept since then, and the current one. When -/// the last checked state is not among them (an undo, or steps dropped past the history's limits), -/// only the current state is checked. +/// they were last checked, and the current one. Those states are the ones the redo steps made +/// since then keep (the states an undo left), and: +/// - While the newest undo step of then is still in the history, the states the undo steps made +/// since then keep. +/// - After an undo of that step, or an edit merged into it, the state before that step and the +/// states the undo steps made since then keep. +/// +/// Otherwise (more than one step undone, or steps dropped past the history's limits) the states in +/// between are not known, and every row is left out of the drop. The panel checks the rows after +/// every command the app runs ([`follow_drag`]), so only the steps of one command go unseen. One +/// undo step is one change: the states between the commands of a `command.batch` are not kept, and +/// a row the batch leaves as it found it stays in the drop. fn held_rows(st: &DocState, ctx: &egui::Context) -> HeldRows { - let mut held: HeldRows = pstate(ctx, DRAG_ROWS); - if std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc)) { + let held: HeldRows = pstate(ctx, DRAG_ROWS); + let now = steps(st); + let same = std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&st.doc)); + if same && held.steps == now { return held; } - let since = st.history.undo.iter().rposition(|e| std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&e.doc))); - let between = since.and_then(|i| st.history.undo.get(i + 1..)).unwrap_or_default(); - for (_, row) in &mut held.rows { - if row.as_ref().is_some_and(|r| !(between.iter().all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc))) { - *row = None; + let (undo, redo) = (&st.history.undo, &st.history.redo); + // Where the steps made after the step with `serial` start in `list`: 0 for none. + let after = |list: &[HistoryEntry], serial: u64| { + if serial == 0 { Some(0) } else { list.iter().rposition(|e| e.serial() == serial).map(|i| i + 1) } + }; + let [newest, below, next, further] = held.steps; + // The redo steps made since: above the next redo step of then, or above the one under it once a + // redo took that step. + let left = redo.get(after(redo, next).or_else(|| after(redo, further)).unwrap_or(0)..).unwrap_or_default(); + // The states in between, and whether they start with the state an undo of the newest step gave back. + let (between, undone) = match after(undo, newest) { + // With no step before it, the first step keeps the last checked state, unless steps were + // dropped past the history's limits, which leave at least that many steps. + Some(0) => { + let kept = same + || undo.len() < st.history.limit.min(History::MIN_STEPS) + || undo.first().is_none_or(|e| std::ptr::eq(held.doc.as_ptr(), Arc::as_ptr(&e.doc))); + (kept.then_some(undo.as_slice()), false) } - } - held.doc = Arc::downgrade(&st.doc); + Some(i) => (undo.get(i..), false), + None => (after(undo, below).and_then(|i| undo.get(i..)), true), + }; + let unchanged = |r: &HeldRow, b: &[HistoryEntry]| b.iter().chain(left).all(|e| r.unchanged_in(&e.doc)) && r.unchanged_in(&st.doc); + let rows = held + .rows + .into_iter() + .zip(held.back) + .map(|((name, row), back)| (name, row.filter(|r| (back || !undone) && between.is_some_and(|b| unchanged(r, b))))) + .collect(); + let held = HeldRows::at(st, rows); set_pstate(ctx, DRAG_ROWS, held.clone()); held } +/// Checks the rows being dragged from the list against the active document after a command ran +/// ([`held_rows`]), so that the commands after it cannot replace one unseen. +pub(crate) fn follow_drag(app: &VectorcraftApp, ctx: &egui::Context) { + dragged_rows(app, ctx); +} + /// The swatches and color groups of the active document being dragged from the list that Delete /// Swatch can delete: neither None nor Registration, and still in the document unchanged. Empty for /// any other drag, and for a drag started in another document. diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 58e767817c..81b4096bd5 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -788,8 +788,9 @@ fn swatches_dropped_on_delete_swatch_are_deleted_after_asking() { /// Delete Swatch takes only swatches dragged from the active document's list: a paint dragged from /// elsewhere, art, and a swatch dragged from another document whose name the active document also /// has delete nothing, ask nothing and are not outlined. A secondary button released while a swatch -/// is held over the button ends the drag without asking, and a swatch deleted while it is dragged -/// leaves alone a new swatch made under its name. +/// is held over the button ends the drag without asking, and a swatch deleted or undone while it is +/// dragged leaves alone a new swatch made under its name, and the swatch an undo brings back. A +/// swatch dragged while an undo takes back a step that left it alone is still deleted. #[test] fn delete_swatch_ignores_other_drags() { let mut app = app(); @@ -866,6 +867,50 @@ fn delete_swatch_ignores_other_drags() { frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 5.5); assert_eq!(dialog_message(&app), None, "the new swatch of that name asks nothing"); assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (replaced, undo_replaced), "the new swatch of that name is kept"); + // A swatch the newest undo step made, undone while it is dragged, and a new swatch made under + // its name before the drop, both inside one command (run on the session, so the panel does + // not check the rows between them). + let hold_orange = |app: &mut VectorcraftApp, time: f64| { + frame_out(app, &ctx, vec![], Modifiers::NONE, time); + let from = tile_center(&ctx, "Orange"); + frame_out(app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, time + 0.1); + frame_out(app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, time + 0.2); + let drag = egui::DragAndDrop::payload::(&ctx); + assert!(matches!(drag.as_deref(), Some(PanelDrag::Paint { rows: Some(r), .. }) if r.names == ["Orange"]), "Orange is dragged"); + }; + hold_orange(&mut app, 6.0); + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("swatch.new", &json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.4); + assert!(!outlined(&held, trash), "the new swatch made after the undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 6.5); + assert_eq!(dialog_message(&app), None, "the new swatch made after the undo asks nothing"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (replaced.clone(), undo_replaced), + "the new swatch made after the undo is kept" + ); + // A swatch deleted while it is dragged and brought back by an undo, inside one command. + hold_orange(&mut app, 6.6); + app.session.execute("swatch.delete", &json!({"names": ["Orange"]})).unwrap(); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.clone(), replaced, "the undo brings Orange back"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.85); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 6.9); + assert!(!outlined(&held, trash), "a swatch brought back by an undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 6.95); + assert_eq!(dialog_message(&app), None, "a swatch brought back by an undo asks nothing"); + // A swatch dragged while an undo takes back a step that left it alone is still deleted. + app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})).unwrap(); + hold_orange(&mut app, 7.0); + app.session.execute("edit.undo", &json!({})).unwrap(); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 7.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(trash.center())], Modifiers::NONE, 7.4); + assert!(outlined(&held, trash), "a swatch an undo left alone is outlined"); + frame_out(&mut app, &ctx, vec![release(trash.center())], Modifiers::NONE, 7.5); + assert!(dialog_message(&app).is_some(), "a swatch an undo left alone is deleted after asking"); } /// Swatches dragged from the list onto New Swatch are duplicated without a dialog, in thumbnail @@ -939,7 +984,8 @@ fn swatches_dropped_on_new_swatch_are_duplicated() { /// New Swatch duplicates only swatches dragged from the active document's list that are still in /// it: a paint dragged from elsewhere, art, a swatch dragged from another document, and a swatch /// deleted while it is dragged duplicate nothing, nor does a new swatch made under the name of a -/// swatch deleted while it is dragged. A secondary button released while a swatch is +/// swatch deleted or undone while it is dragged, or the swatch an undo brings back after deleting it +/// while it is dragged. A secondary button released while a swatch is /// held over the button ends the drag without duplicating, and a click still opens New Swatch. #[test] fn new_swatch_ignores_other_drags() { @@ -1028,14 +1074,69 @@ fn new_swatch_ignores_other_drags() { assert_eq!((app.session.doc().unwrap().doc.clone(), undo_steps(&app)), (other, undo_new), "the other document duplicates nothing"); assert!(app.session.set_active(0)); unchanged(&app, "the first document"); + // A swatch the newest undo step made, undone while it is dragged, and a new swatch made under + // its name before the drop, both inside one command (run on the session, so the panel does + // not check the rows between them). + let glass = json!({"name": "Sea Glass", "color": "#00a99d"}); + let steps = json!([{"command": "swatch.new", "params": glass}, {"command": "swatch.move", "params": {"name": "Sea Glass", "to": 2}}]); + app.run("command.batch", json!({"label": "New Swatch", "commands": steps})).unwrap(); + let made = app.session.doc().unwrap().doc.swatch("Sea Glass").cloned(); + assert!(made.is_some(), "Sea Glass is made"); + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 5.6); + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 5.65); + let from = tile_center(&ctx, "Sea Glass"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from), press(from, PointerButton::Primary, true)], Modifiers::NONE, 5.7); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(from + vec2(6.0, 4.0))], Modifiers::NONE, 5.8); + let drag = egui::DragAndDrop::payload::(&ctx); + assert!(matches!(drag.as_deref(), Some(PanelDrag::Paint { rows: Some(r), .. }) if r.names == ["Sea Glass"]), "Sea Glass is dragged"); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch("Sea Glass").is_none(), "the undo takes Sea Glass away"); + app.session.execute("swatch.new", &glass).unwrap(); + let (replaced, undo_replaced) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert_eq!(replaced.swatch("Sea Glass").cloned(), made, "the new swatch is the same as the one undone"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 5.85); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 5.9); + assert!(!outlined(&held, new), "the new swatch made after the undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 5.95); + assert!(app.ui.dialog.is_none(), "the new swatch made after the undo opens no dialog"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (replaced, undo_replaced), + "the new swatch made after the undo is not duplicated" + ); + app.run("edit.undo", json!({})).unwrap(); + unchanged(&app, "after the undo case"); + // A swatch deleted while it is dragged and brought back by an undo, then an edit that clears + // the redo steps, each a command of its own before the panel is drawn again. The app checks the + // rows after each command it runs with the window's context. + app.ui_ctx = Some(ctx.clone()); + hold_orange(&mut app, 6.0); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})).unwrap(); + let (restored, undo_restored) = (app.session.doc().unwrap().doc.clone(), undo_steps(&app)); + assert!(restored.swatch("Orange").is_some(), "the undo brings Orange back"); + frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 6.3); + let held = frame_out(&mut app, &ctx, vec![Event::PointerMoved(new.center())], Modifiers::NONE, 6.4); + assert!(!outlined(&held, new), "a swatch brought back by an undo is not outlined"); + frame_out(&mut app, &ctx, vec![release(new.center())], Modifiers::NONE, 6.5); + assert!(app.ui.dialog.is_none(), "a swatch brought back by an undo opens no dialog"); + assert_eq!( + (app.session.doc().unwrap().doc.clone(), undo_steps(&app)), + (restored, undo_restored), + "a swatch brought back by an undo is not duplicated" + ); + app.run("edit.undo", json!({})).unwrap(); + app.ui_ctx = None; + unchanged(&app, "after the restored case"); // A click still opens New Swatch. - frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 6.0); + frame_out(&mut app, &ctx, vec![], Modifiers::NONE, 7.0); let click = vec![ Event::PointerMoved(new.center()), press(new.center(), PointerButton::Primary, true), press(new.center(), PointerButton::Primary, false), ]; - frame_out(&mut app, &ctx, click, Modifiers::NONE, 6.1); + frame_out(&mut app, &ctx, click, Modifiers::NONE, 7.1); assert!(app.ui.dialog.is_some(), "a click opens the New Swatch dialog"); } From 8e23d74985eb178d8a43f79c3fe73f252580e54b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:20 -0800 Subject: [PATCH 038/104] Scripts: textFrames.removeAll() refuses type on a locked artboard textFrames.removeAll() now stops with the same error as pageItems.removeAll() and PageItem.remove() when a type object sits on a locked artboard, and deletes nothing. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/text.rs | 13 ++++++++++--- crates/engine/src/tests/script_dom.rs | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c02d65dfbd..b1dab0816e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1561,7 +1561,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// The error of `remove()` and `removeAll()` for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0366dec5dd..e1386310d3 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1215,19 +1215,26 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st); let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..35baf42e88 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -997,6 +997,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}"); + assert!(s.active().unwrap().doc.node(t).is_some()); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); From 9c636b9036c2b9cce38da4a0d96d37a763776d92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:21 -0800 Subject: [PATCH 039/104] Scripts: a character style applied to an empty frame styles text set later CharacterStyle.applyTo returned early on any empty range, so on an empty text frame it never reached charStyle.apply, which restyles the stored runs of empty text. It now passes an empty frame through and keeps the no-op only for an empty range inside text. --- crates/engine/src/script/dom/text/styles.rs | 3 ++- crates/engine/src/tests/script_styles.rs | 10 ++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index fd896918a9..87bfde4f27 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -359,7 +359,8 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let (_, ba, bb) = para_range(&index, s, e); (ba, bb) } else { - if s == e { + // An empty range inside text changes nothing; empty text takes the style on its runs. + if s == e && index.len() > 0 { return Ok(Data::Undefined); } (index.byte(s, false), index.byte(e, true)) diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 12bded346f..df96906aec 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -256,6 +256,16 @@ fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); } +/// A character style applied to an empty frame styles the text set in it later. +#[test] +fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() { + for target in ["tf", "tf.textRange"] { + let (mut s, id) = doc_with(""); + log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';")); + assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}"); + } +} + /// A paragraph style styles every paragraph the text touches, and only those. #[test] fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { diff --git a/docs/mcp.md b/docs/mcp.md index 0495483d8e..b302b7ee18 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,8 +2756,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the - style's document; a character style on an empty range changes nothing, and a paragraph style styles every - paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order + style's document; a character style on an empty range inside text changes nothing, on empty text it styles the + text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left + out is false. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws From d261130741b46e71eed594bb95eb23edbac6fb14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:21 -0800 Subject: [PATCH 040/104] i18n: translate the 64 MB style file limit in every complete catalog The error for a styles file over the load limit reads "the file is larger than 64 MB". Most complete catalogs translate it through their `the file is larger than {_1} MB` row; ca, el, fi, id and vi have no such row, so each gets an exact row next to its 1 MB one. A test checks the message in every complete-message language. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 14 ++++++++++++++ crates/ui-egui/src/i18n/vi.tsv | 1 + 6 files changed, 19 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..635746fe75 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7549,6 +7549,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg the file holds no preferences el fitxer no conté cap preferència @msg `{key}` names a folder, which preferences files leave out `{key}` indica una carpeta, i els fitxers de preferències no inclouen carpetes @msg the file is larger than 1 MB el fitxer ocupa més d’1 MB +@msg the file is larger than 64 MB el fitxer ocupa més de 64 MB @msg give `path` or `data` indiqueu `path` o `data` @msg `{key}` must be an object `{key}` ha de ser un objecte @msg `prefs.import` runs on its own, not as a batch step `prefs.import` s’executa sol, no com a pas d’un lot diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..e2f3ebce06 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5729,6 +5729,7 @@ digits Malayalam Μαλαγιάλαμ @msg the file holds no preferences το αρχείο δεν περιέχει προτιμήσεις @msg `{key}` names a folder, which preferences files leave out το `{key}` ορίζει φάκελο, και τα αρχεία προτιμήσεων δεν περιέχουν φακέλους @msg the file is larger than 1 MB το αρχείο είναι μεγαλύτερο από 1 MB +@msg the file is larger than 64 MB το αρχείο είναι μεγαλύτερο από 64 MB @msg give `path` or `data` δώστε `path` ή `data` @msg `{key}` must be an object το `{key}` πρέπει να είναι αντικείμενο @msg `prefs.import` runs on its own, not as a batch step το `prefs.import` εκτελείται μόνο του, όχι ως βήμα δέσμης diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d791677d24 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6012,6 +6012,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the file holds no preferences tiedostossa ei ole asetuksia @msg `{key}` names a folder, which preferences files leave out `{key}` nimeää kansion, eikä asetustiedostoissa ole kansioita @msg the file is larger than 1 MB tiedosto on suurempi kuin 1 Mt +@msg the file is larger than 64 MB tiedosto on suurempi kuin 64 Mt @msg give `path` or `data` anna `path` tai `data` @msg `{key}` must be an object `{key}` on oltava objekti @msg `prefs.import` runs on its own, not as a batch step `prefs.import` ajetaan yksinään, ei erän vaiheena diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..ed4341007e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6090,6 +6090,7 @@ imageTrace Outline Kontur @msg the file holds no preferences file tidak berisi preferensi @msg `{key}` names a folder, which preferences files leave out `{key}` menunjuk folder, dan file preferensi tidak menyertakan folder @msg the file is larger than 1 MB file lebih besar dari 1 MB +@msg the file is larger than 64 MB berkas lebih besar dari 64 MB @msg give `path` or `data` berikan `path` atau `data` @msg `{key}` must be an object `{key}` harus berupa objek @msg `prefs.import` runs on its own, not as a batch step `prefs.import` dijalankan sendiri, bukan sebagai langkah batch diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..fb428adbd9 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3860,6 +3860,20 @@ fn warped_type_note_is_translated() { } } +/// The error for a character or paragraph styles file over the 64 MB load limit is translated in +/// every complete catalog, through an exact row or the `the file is larger than {_1} MB` template. +#[test] +fn styles_file_size_limit_is_translated() { + assert_eq!(vectorcraft_engine::cmd::textstyles::MAX_LOAD_BYTES, 64 << 20); + let error = "the file is larger than 64 MB"; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(shown.contains("64"), "{code}: {shown}"); + } +} + /// The notes a CDR import adds to its warnings are translated in every complete catalog. /// They are constants, which the scan of message literals doesn't see. #[test] diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..d58bfa4bc4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6461,6 +6461,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg the file holds no preferences tệp không chứa tùy chọn nào @msg `{key}` names a folder, which preferences files leave out `{key}` chỉ định một thư mục, và tệp tùy chọn không chứa thư mục @msg the file is larger than 1 MB tệp lớn hơn 1 MB +@msg the file is larger than 64 MB tệp lớn hơn 64 MB @msg give `path` or `data` hãy cung cấp `path` hoặc `data` @msg `{key}` must be an object `{key}` phải là một đối tượng @msg `prefs.import` runs on its own, not as a batch step `prefs.import` chạy riêng, không phải là một bước trong lô From d26ae6f344f62ab7729abc0a0dc3bbe7df5a8a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:16:39 -0800 Subject: [PATCH 041/104] Color Wheel: contrast lines follow a widening band, show for a fill of None and hide under Alt - The contrast lines count a narrow band's crossings among a cell's crossings where no band on the next line joins it, so a band that widens past the samples is no longer cut across. - The lines show where a pick passes when the fill or stroke is None or a pattern (`contrast_pick_backdrop`), and are hidden while Alt sends a pick to the other proxy. - The Background chip shows the background the ratio uses, so a pinned 100 % K shows as black with a rich black Appearance of Black. - `color.contrast` with "below" is an error when a blend mode other than Normal mixes the color with art that is not one color where its level reads it; a blend inside an isolating group over such art still answers. - `wcag::closest_passing`, `color.contrast`'s params text and docs/mcp.md say that a nearer passing color can be missed when the passing lightnesses fall in more than one stretch, that a null fix shows no chip, and that a null `contrastBackground` sets Behind Selection. - The wide-gamut contrast test restores the color settings through `restored_settings()`. --- crates/color/src/wcag.rs | 5 +- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/colorcmds.rs | 93 +++++++++---- crates/engine/src/tests/colorcontrast.rs | 116 ++++++++++++++++ crates/engine/tests/color_settings.rs | 4 +- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 131 ++++++++++++------ .../src/panels/tests_color_wheel_contrast.rs | 29 ++-- .../tests_color_wheel_contrast_lines.rs | 54 +++++++- docs/mcp.md | 22 ++- 11 files changed, 370 insertions(+), 90 deletions(-) diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index 16b34bb166..ba5bb3b974 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -124,7 +124,10 @@ pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { /// When no step passes, the highest ratio between the neighbors of the highest step is looked for, /// so a color that passes only in a narrow band between white and black (as under a Difference /// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is -/// bounded: at most 167 colors are tested. +/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors +/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio. +/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested +/// steps before the first passing one is missed, and a farther color can be returned. pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> { let passes = |c: [f32; 3]| ratio(c) >= minimum; let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fdc6abc838..f4ffaa239e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -845,7 +845,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. pub use addons::{fold_source, print_hidden}; -pub use colorcmds::{Backdrop, contrast_measure}; +pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index f3f250dba1..064adcf1ef 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel; null when the color already meets the level, or when no lightness of its hue does}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), @@ -1208,6 +1208,21 @@ pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { /// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and /// what it measures it against. fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { + let (color, backdrop) = contrast_reading(s, p, true)?; + let color = color.ok_or_else(|| bad("color.contrast", no_color()))?; + Ok((color, backdrop)) +} + +/// What a color picked for the active proxy would be measured against by `color.contrast` with +/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the +/// Color Wheel's contrast lines show where a pick would pass. +pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result { + contrast_reading(s, p, false).map(|(_, backdrop)| backdrop) +} + +/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when +/// `need_color`. +fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option, Backdrop)> { const C: &str = "color.contrast"; check_numbers(p, &["opacity"], C)?; let opacity = match p.get("opacity").and_then(Value::as_f64) { @@ -1222,18 +1237,25 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { let given = p.get("color").is_some_and(|v| !v.is_null()); let (color, drawn) = match p.get("color") { None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?, - Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()), + Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()), }; + if need_color && color.is_none() { + return Err(bad(C, no_color())); + } let rich_black = s.prefs.black_on_screen == "rich"; let cms = vectorcraft_color::cms::active(); let shown = |c: &Color| shown_rgb(&cms, rich_black, c); let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + // Whether the background read is one color across its pixels. + let mut uniform = true; // The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as. let (against, written) = match p.get("against").filter(|_| !below) { None => { // The sample in working RGB, rounded to 8 bits: the background the answer writes is the // one the ratio uses, and giving it back answers the same ratio. - let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0)); + let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?; + uniform &= one; + let working = to_8bit(cms.srgb_to_rgb(sample)); (cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working) } Some(v) => { @@ -1275,6 +1297,8 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { let mut passes = vec![]; let mut alpha = 1.0f32; let mut alone = 1.0f32; + // Whether a level so far read art that is not one color. + let mut mixed = false; for (k, step) in steps.iter().enumerate() { if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 { continue; @@ -1283,19 +1307,29 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { let scope = above.iter().find(|a| a.isolate); let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::>(); let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e)); - let backdrop = match scope { - Some(_) if !sampled => ([0.0; 3], 0.0), - None if !sampled => (against, 1.0), + let (backdrop, one) = match scope { + Some(_) if !sampled => (([0.0; 3], 0.0), true), + None if !sampled => ((against, 1.0), uniform), // The background itself, as the answer writes it. - None if step.hide.is_none() && full.is_empty() => (against, 1.0), + None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform), _ => read(scope.map(|a| &a.within))?, }; // The alpha of the art below the level inside the level around it, while a blending level // lies further out (none for a given background). - let inner = match above.first() { - Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1, - _ => 0.0, + let (inner, inner_one) = match above.first() { + Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => { + let ((_, a), one) = read(Some(&around.within))?; + (a, one) + } + _ => (0.0, true), }; + // A blend mode mixes the color with the art below it pixel by pixel, which one color read for + // art of several colors does not stand for, also when that art reaches it through the levels + // inside it. + mixed |= !one || !inner_one; + if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 { + return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`")); + } let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner }; (_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone)); passes.push(pass); @@ -1415,8 +1449,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { /// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not /// compared, since the given opacity takes their place; with `below` (the background is sampled), /// objects in different translucent or blending groups or layers differ, since the art below each -/// such level is read with it hidden. -fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> { +/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern), +/// and the drawing is then the one a solid color in its place would have. +fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option, Drawn), String> { let stroke = !s.fill_active; let (fill_mixed, stroke_mixed) = s.proxy_mixed(); if if stroke { stroke_mixed } else { fill_mixed } { @@ -1471,20 +1506,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re } else { drawing = source()?.unwrap_or_default(); } - let no_color = || "the active fill or stroke has no color: give `color`".to_string(); - match if stroke { stroke_paint } else { fill } { - Paint::Solid { color, .. } => Ok((color, drawing)), + let found = match if stroke { stroke_paint } else { fill } { + Paint::Solid { color, .. } => Some((color, drawing.clone())), Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => { let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0)); let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0); - f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color) + f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))) } Paint::Gradient(g) => { let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1)); - g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color) + g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))) } - Paint::None | Paint::Pattern { .. } => Err(no_color()), - } + Paint::None | Paint::Pattern { .. } => None, + }; + Ok(match found { + Some((color, drawn)) => (Some(color), drawn), + None => (None, drawing), + }) +} + +/// The message for an active fill or stroke with no color to measure. +fn no_color() -> String { + "the active fill or stroke has no color: give `color`".to_string() } /// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its @@ -1605,14 +1648,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec { /// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it; /// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer /// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing, -/// without artboards. +/// without artboards. Also whether the square's pixels are all one color. fn color_below( s: &Session, rich_black: bool, hide: Option<&Part>, full: &[&Part], scope: Option<&Part>, -) -> std::result::Result<([f32; 3], f32), String> { +) -> std::result::Result<(([f32; 3], f32), bool), String> { super::has_selection(s)?; let st = s.active().ok_or("no document open")?; let ids = st.selection.objects.clone(); @@ -1741,8 +1784,10 @@ fn color_below( let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts); let px = img.pixels.as_chunks::<4>().0; if px.is_empty() { - return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }); + return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true)); } + // Whether the pixels are one color, to within one step of 255 per channel. + let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1))); // The pixels are premultiplied: the average color is their sum over their alpha's. let mut sum = [0.0f64; 4]; for p in px { @@ -1752,10 +1797,10 @@ fn color_below( } let alpha = sum[3] / (px.len() as f64 * 255.0); if alpha <= 0.0 { - return Ok(([0.0; 3], 0.0)); + return Ok((([0.0; 3], 0.0), uniform)); } let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32); - Ok((rgb, alpha as f32)) + Ok(((rgb, alpha as f32), uniform)) } /// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it. diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 8a8c203488..7c2a5c838f 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -993,6 +993,122 @@ fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() { assert!((3.0..3.04).contains(&ratio(&back)), "{back}"); } +/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a +/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws +/// as it is, on the canvas and in the answer, for each blend mode of the object. +#[test] +fn isolation_leaves_a_translucent_normal_row_as_it_draws() { + let id = |v: Value| v["id"].as_u64().unwrap(); + for blend in ["normal", "multiply", "screen", "difference", "overlay"] { + for fill in ["#808080", "#ffffff", "#2040a0"] { + for lower in [false, true] { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + if lower { + s.execute("appearance.addFill", &json!({})).unwrap(); + } + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items; + let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap(); + if lower { + s.execute("object.group", &json!({})).unwrap(); + s.execute("transparency.set", &json!({"blend": "screen"})).unwrap(); + s.execute("select.set", &json!({"ids": [n]})).unwrap(); + } + let plain = s.execute("color.contrast", &json!({})).unwrap(); + let (p, drawn) = canvas_ratio(&s, &plain); + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + let isolated = s.execute("color.contrast", &json!({})).unwrap(); + let (q, _) = canvas_ratio(&s, &isolated); + let case = format!("{blend} {fill} lower row and group: {lower}"); + assert_eq!(p, q, "the canvas draws the same: {case}"); + assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}"); + assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}"); + } + } + } +} + +/// A Difference square centered on the edge between locked black and white art: the art behind it +/// is not one color where it is read, so no one color stands for it; a given background answers, +/// and over one color the background is read as before. +#[test] +fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + // Without the default stroke, which would cover the edge. + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}"); + let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap(); + assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}"); + // In Normal mode the color is drawn as it is, over the background read as one color. + s.execute("transparency.set", &json!({"blend": "normal"})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); + // Moved over the white art alone, the square blends with one color again. + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap(); + let r = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}"); +} + +/// A Difference square over a white square in a 50 % group that isolates its blending, over the +/// edge between black and white art: the square blends only with the white inside the group, so +/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer. +#[test] +fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap()); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap(); + s.execute("transparency.set", &json!({"blend": "difference"})).unwrap(); + s.execute("object.group", &json!({"ids": [back, square]})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap(); + s.execute("select.set", &json!({"ids": [square]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); +} + +/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's +/// contrast lines show where a solid color in its place passes. +#[test] +fn a_pick_for_a_fill_of_none_is_measured_against_the_background() { + let mut s = blended_over_red("normal"); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure"); + let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap(); + let cms = vectorcraft_color::cms::active(); + let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0))); + let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]); + assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}"); + assert_eq!(backdrop.against_hex(), "#ff0000"); +} + #[test] fn for_takes_only_the_three_categories() { let mut s = Session::new(); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 61bfba6fb3..b388e8ef7b 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { /// behind the selection, given back, answers the same ratio. #[test] fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() { - let _g = settings(); - let before = cms::active_settings(); + let _g = restored_settings(); let mut s = session(); exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"})); @@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space exec(&mut s, "paint.setFill", json!({"color": "#808080"})); let below = s.execute("color.contrast", &json!({})); let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok()); - cms::set_active(&before).unwrap(); let given = given.unwrap(); assert_eq!(given["against"], "#806040", "{given}"); let (below, again) = (below.unwrap(), again.unwrap()); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ae699a7629..70ffce9503 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1604,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 71d2ace197..726c717e09 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1605,7 +1605,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index ee1469a833..c8187102da 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -66,7 +66,7 @@ use vectorcraft_color::oklab::{self, CHROMA_FULL}; use vectorcraft_color::wcag::{self, Category}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl}; use vectorcraft_doc::{ColorMode, NodeId}; -use vectorcraft_engine::cmd::{Backdrop, contrast_measure}; +use vectorcraft_engine::cmd::{Backdrop, contrast_measure, contrast_pick_backdrop}; use super::color::{Target, apply, wheel_target}; use super::{color_json, pstate, set_pstate}; @@ -812,14 +812,20 @@ type FieldPoint = (f32, f32); /// its two crossings. type Bands = Vec<(f32, FieldPoint, FieldPoint)>; +/// The edge from sample (i, j) across (true) or down (false). +type EdgeKey = (usize, usize, bool); + /// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in /// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell -/// whose corners fall on both sides gets a segment between the crossings on its edges, placed by -/// bisection (marching squares; a cell with two opposite corners passing is split by its center). +/// whose edges are crossed gets segments between the crossings on its edges, placed by bisection +/// (marching squares; a cell crossed more than twice, as one with two opposite corners passing, is +/// split by its center). /// With `narrow`, around a failing sample higher than its neighbors in a column or a row, the highest /// ratio is looked for, so a passing band narrower than the samples gets its two edges too, joined -/// from column to column or from row to row. Segments that share an end are joined into one -/// polyline. +/// from column to column or from row to row. Where no band on the next or the previous line joins +/// one, its two crossings count among the crossings of the cell on that side, so a band that widens +/// past the samples or ends there is joined to the cell's other crossings instead of being cut +/// across. Segments that share an end are joined into one polyline. pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64], n: usize, narrow: bool) -> Lines { let n = n.max(1); let at = |i: usize| i as f32 / n as f32; @@ -850,28 +856,10 @@ pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64 }) }; let mut segments: Vec<[FieldPoint; 2]> = vec![]; - for i in 0..n { - for j in 0..n { - let (top, right, bottom, left) = (edge(i, j, true), edge(i + 1, j, false), edge(i, j + 1, true), edge(i, j, false)); - match (top, right, bottom, left) { - (Some(t), Some(rt), Some(b), Some(l)) => { - // Opposite corners pass: the center says which pair of them it joins. - let half = 0.5 / n as f32; - if pass((at(i) + half, at(j) + half)) == (r(i, j) >= min) { - segments.extend([[t, rt], [b, l]]); - } else { - segments.extend([[t, l], [rt, b]]); - } - } - _ => { - let found: Vec = [top, right, bottom, left].into_iter().flatten().collect(); - if let &[p, q] = found.as_slice() { - segments.push([p, q]); - } - } - } - } - } + // The crossings of the bands narrower than the samples on each edge between samples, with + // whether no band on the next line (the column to the right, the row below) and no band on + // the line before joins the band on that side. + let mut loose: HashMap> = HashMap::new(); // Bands narrower than the samples, along each column and then each row. for across in [false, true].into_iter().filter(|_| narrow) { let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) }; @@ -900,11 +888,62 @@ pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64 found }) .collect(); - for pair in bands.windows(2) { - let [this, next] = pair else { continue }; - for (peak, a, b) in this { - if let Some((_, c, d)) = next.iter().find(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32) { - segments.extend([[*a, *c], [*b, *d]]); + // The band of `next` that the band peaking at `peak` joins. + let joins = |next: &Bands, peak: f32| next.iter().position(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32); + for (k, this) in bands.iter().enumerate() { + let next = bands.get(k + 1); + let before = k.checked_sub(1).and_then(|k| bands.get(k)); + for (b, &(peak, p, q)) in this.iter().enumerate() { + let joined = next.and_then(|next| joins(next, peak).and_then(|m| next.get(m))); + if let Some(&(_, c, d)) = joined { + segments.extend([[p, c], [q, d]]); + } + let joined_before = before.is_some_and(|before| before.iter().any(|(bp, ..)| joins(this, *bp) == Some(b))); + let e = ((peak * n as f32).floor() as usize).min(n - 1); + let key = if across { (e, k, true) } else { (k, e, false) }; + let open = [joined.is_none(), !joined_before]; + loose.entry(key).or_default().extend([(p, open), (q, open)]); + } + } + } + for i in 0..n { + for j in 0..n { + let (x0, y0, w) = (at(i), at(j), 1.0 / n as f32); + // Where point `p` on edge `s` (0 to 3: top, right, bottom, left) lies going around + // the cell clockwise from its top left corner. + let place = |s: usize, p: FieldPoint| match s { + 0 => (p.0 - x0) / w, + 1 => 1.0 + (p.1 - y0) / w, + 2 => 2.0 + (x0 + w - p.0) / w, + _ => 3.0 + (y0 + w - p.1) / w, + }; + // The cell's edges, each with the side of the edge's line the cell is on: after + // its top and left edges' lines (0) and before its right and bottom edges' (1). + let sides = [((i, j, true), 0), ((i + 1, j, false), 1), ((i, j + 1, true), 1), ((i, j, false), 0)]; + let mut around: Vec<(f32, FieldPoint)> = vec![]; + for (s, (key, side)) in sides.into_iter().enumerate() { + let (ei, ej, across) = key; + around.extend(edge(ei, ej, across).map(|p| (place(s, p), p))); + let band = loose.get(&key).into_iter().flatten().filter(|(_, open)| open.get(side).copied().unwrap_or(false)); + around.extend(band.map(|&(p, _)| (place(s, p), p))); + } + around.sort_by(|a, b| a.0.total_cmp(&b.0)); + let m = around.len(); + if m < 2 { + continue; + } + // Going around from the top left corner, the side changes at each crossing. Where + // the crossings leave more than one passing stretch of the edges, the center says + // whether those stretches join inside the cell (the segments cut off the failing + // stretches) or not (they cut off the passing ones). + let corner = r(i, j) >= min; + let half = 0.5 / n as f32; + let cut = if m == 2 { !corner } else { !pass((x0 + half, y0 + half)) }; + // The stretch between crossings 0 and 1 is on the side the corner is not. + let start = usize::from(corner == cut); + for k in (start..m).step_by(2) { + if let (Some(&(_, p)), Some(&(_, q))) = (around.get(k), around.get((k + 1) % m)) { + segments.push([p, q]); } } } @@ -1071,8 +1110,12 @@ fn measure(app: &VectorcraftApp, ui: &Ui) -> Measured { (Some((k, answer)), Some((kb, backdrop))) if k == key && kb == key => Measured { answer, backdrop }, _ => { let against = pinned.as_ref().map_or_else(|| json!("below"), color_json); - let m = contrast_measure(&app.session, &json!({ "against": against, "for": category.id() })).ok(); - let (answer, backdrop) = m.map_or((None, None), |(r, b)| (Some(r), Some(b))); + let p = json!({ "against": against, "for": category.id() }); + // With no color to measure (a fill of None, a pattern), a pick there is still measured. + let (answer, backdrop) = match contrast_measure(&app.session, &p) { + Ok((r, b)) => (Some(r), Some(b)), + Err(_) => (None, contrast_pick_backdrop(&app.session, &p).ok()), + }; set_pstate(ui.ctx(), RATIO, Some((key.clone(), answer.clone()))); set_pstate(ui.ctx(), BACKDROP, Some((key, backdrop.clone()))); Measured { answer, backdrop } @@ -1082,17 +1125,20 @@ fn measure(app: &VectorcraftApp, ui: &Ui) -> Measured { /// The contrast row: the background's chip, the ratio cut off at two decimals, the AA and AAA /// results for the chosen category, and a chip of the closest color that passes the first level the -/// color fails; a dash when there is no background or no color to measure. Without a pinned -/// background the first chip shows the background in the answer. Only when there is no answer is -/// the background read on its own ([`background`]), so the chip still shows it. The fix chip keeps -/// its space while hidden. Returns the fix color when its chip is clicked. +/// color fails, when `color.contrast` finds one for that level; a dash when there is no background +/// or no color to measure. The first chip shows the background the answer measured against, pinned +/// or not, else the one a pick would be measured against. Only when there is neither is the +/// background read on its own ([`background`]), so the chip still shows it. The fix chip keeps its +/// space while hidden. Returns the fix color when its chip is clicked. fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option { let category = app.ui.color_wheel.contrast_for; let pinned = app.ui.color_wheel.contrast_background; let answer = m.answer.as_ref(); - // The background the ratio was measured against. - let measured = answer.filter(|_| pinned.is_none()).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); - let chip = match pinned.or(measured) { + // The background the ratio was measured against, or a pick would be (a pinned 100 % K shows + // as black with a rich black Appearance of Black). + let against = answer.and_then(|r| r["against"].as_str().map(str::to_string)).or_else(|| m.backdrop.as_ref().map(Backdrop::against_hex)); + let measured = against.as_deref().and_then(Color::from_hex); + let chip = match measured.or(pinned) { Some(c) => Some(c), None => background(app, ui), }; @@ -1654,7 +1700,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), ROWS_LIVE, None::); } if let Some(m) = &measured { - if let Some(backdrop) = &m.backdrop { + // With Alt held a pick goes to the other proxy, which the lines do not measure. + if let Some(backdrop) = m.backdrop.as_ref().filter(|_| !super::alt_held(ui)) { let lines = lines_for(app, ui, backdrop, &tgt, hsb, cmyk_doc); draw_contrast_lines(ui, field_rect, &lines); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index aea80f72d8..1a1606a5bc 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -125,6 +125,18 @@ fn the_background_is_the_art_behind_the_selection() { assert_eq!(chip.value().as_deref(), Some("FFFF00")); } +/// A pinned 100 % K is measured as black with a rich black Appearance of Black, and the Background +/// chip names the black the ratio uses. +#[test] +fn the_background_chip_shows_the_black_a_pinned_k_is_measured_as() { + let mut app = app("#ffffff"); + app.run("ui.colorWheel", json!({"contrastBackground": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap(); + app.session.prefs.black_on_screen = "rich".into(); + let h = harness(app); + assert!(shows(&h, "21.00:1"), "white on black"); + assert_eq!(h.get_by_label("Background").value().as_deref(), Some("000000")); +} + #[test] fn nothing_selected_and_nothing_pinned_shows_no_ratio() { let mut app = app("#000000"); @@ -186,8 +198,8 @@ fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() { assert_eq!(measured(&h).as_deref(), Some("#ffffff")); } -/// With no color to measure the row has no ratio, and the chip still shows the background, read on -/// its own, and read again for another selection during an interaction. +/// With no color to measure the row has no ratio, and the chip still shows the background a pick +/// would be measured against, read again for another selection during an interaction. #[test] fn a_paint_with_no_color_still_shows_the_background() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); @@ -203,12 +215,13 @@ fn a_paint_with_no_color_still_shows_the_background() { app.run("ui.colorWheel", json!({"contrast": true})).unwrap(); let mut h = harness(app); assert!(shows(&h, "—"), "a fill of None has no ratio"); - let hex = |h: &Harness<'static, VectorcraftApp>| behind(h).and_then(|(_, hex)| hex); - assert_eq!(hex(&h).as_deref(), Some("#ffff00")); + let hex = |h: &Harness<'static, VectorcraftApp>| h.get_by_label("Background").value(); + assert_eq!(hex(&h).as_deref(), Some("FFFF00")); + assert!(behind(&h).is_none(), "the background a pick is measured against was not read again on its own"); h.state_mut().run("select.set", json!({"ids": [b]})).unwrap(); h.state_mut().session.begin_interaction("test").unwrap(); h.run_steps(2); - assert_eq!(hex(&h).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction"); + assert_eq!(hex(&h).as_deref(), Some("FFFFFF"), "the other selection's background is read during the interaction"); } /// With no color to measure, a move during an interaction reads the background again at the @@ -224,14 +237,14 @@ fn a_move_during_an_interaction_reads_the_background_again() { app.run("paint.setFill", json!({"none": true})).unwrap(); app.run("ui.colorWheel", json!({"contrast": true})).unwrap(); let mut h = harness(app); - let hex = |h: &Harness<'static, VectorcraftApp>| behind(h).and_then(|(_, hex)| hex); + let hex = |h: &Harness<'static, VectorcraftApp>| h.get_by_label("Background").value(); h.state_mut().session.begin_interaction("test").unwrap(); h.run_steps(2); - assert_eq!(hex(&h).as_deref(), Some("#ffff00")); + assert_eq!(hex(&h).as_deref(), Some("FFFF00")); h.state_mut().run("object.move", json!({"dx": 110, "dy": 0})).unwrap(); assert!(h.state().session.in_interaction(), "the move is part of the interaction"); h.run_steps(2); - assert_eq!(hex(&h).as_deref(), Some("#ffffff"), "the background at the new place"); + assert_eq!(hex(&h).as_deref(), Some("FFFFFF"), "the background at the new place"); } /// An interaction keeps no answer for another selection: the row asks again, and the chip shows diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs index d8501b6351..698bb07426 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -1,15 +1,15 @@ //! The Color Wheel panel's contrast lines on the box's field and the wheel's square, and the chip of //! the closest passing color in the contrast row, drawn headless. -use egui::vec2; +use egui::{Event, Modifiers, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb}; use vectorcraft_engine::Session; -use super::color_wheel::{LINES, Lines, LinesKey, box_pick, show}; -use super::pstate; +use super::color_wheel::{LINES, Lines, LinesKey, box_pick, contrast_lines, show}; +use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; @@ -115,6 +115,54 @@ fn a_line_that_runs_up_the_field_is_found() { assert!(spread(&ys) > 0.9 && spread(&xs) < 0.05, "{line:?}"); } +/// A passing band around x = 0.515625 that is narrower than the samples near the top and wider +/// below: every point of its center passes, so no line crosses it, and its two edges run on either +/// side of it from the top to the bottom. +#[test] +fn a_band_that_widens_past_the_samples_is_not_cut_across() { + let center = 0.515625; + let ratio = |x: f32, y: f32| 4.5 + 0.009 + 0.013 * f64::from(y) - f64::from((x - center).abs()); + let lines = contrast_lines(&ratio, &[4.5], 32, true); + let aa = lines.first().expect("one level"); + for line in aa { + for pair in line.windows(2) { + let [p, q] = pair else { continue }; + assert!((p.0 - center) * (q.0 - center) > 0.0, "{p:?} to {q:?} crosses the passing center"); + } + } + let side = |left: bool| aa.iter().flatten().filter(|p| (p.0 < center) == left).map(|p| p.1).collect::>(); + for points in [side(true), side(false)] { + let low = points.iter().copied().fold(f32::INFINITY, f32::min); + let high = points.iter().copied().fold(f32::NEG_INFINITY, f32::max); + assert!(low < 0.05 && high > 0.95, "an edge runs from the top to the bottom: {low} to {high}"); + } +} + +/// With a fill of None the row shows a dash, and the field still marks where a pick there passes. +#[test] +fn a_fill_of_none_keeps_its_lines() { + let mut app = app("box", "hue"); + app.run("paint.setFill", json!({"none": true})).unwrap(); + let h = harness(app); + assert!(h.query_by_label("—").is_some(), "no color to measure"); + let lines = lines(&h); + assert!(lines.first().is_some_and(|aa| !aa.is_empty()), "an AA line: {lines:?}"); +} + +/// While Alt is held a pick goes to the other proxy, so the field's lines, which measure the active +/// one, are not drawn; they come back once Alt is let go. +#[test] +fn the_lines_are_hidden_while_alt_is_held() { + let mut h = harness(app("box", "hue")); + set_pstate(&h.ctx, LINES, None::<(LinesKey, Lines)>); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(pstate::>(&h.ctx, LINES).is_none(), "no lines with Alt held"); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert!(pstate::>(&h.ctx, LINES).is_some(), "the lines are back"); +} + #[test] fn graphics_have_one_line() { let mut app = app("box", "saturation"); diff --git a/docs/mcp.md b/docs/mcp.md index b884e3e6b7..d57f88be22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -692,13 +692,17 @@ whole cell or none of it, so a grayed cell can hold printable colors and a clear print. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or -`highContrast2`). Keys left out keep their values. Params that are not an object, another key or a value off +`highContrast2`). Keys left out keep their values, and so do keys given as `null`, except `contrastBackground`. Params that are not an object, another key or a value off the list return an error and change nothing. `{"contrast": true}` shows Show Contrast's row under the wheel or the box, `contrastFor` (`normalText`, `largeText` or `graphics`, which has AA only) picks the category its results are for, and `contrastBackground` (a color, or `null` for the color behind the selection) pins the background it measures against, as `color.contrast` below answers it. With the row shown, the wheel's square and the box's field draw lines where the -color picked there meets AA (solid) and AAA (dashed) for the category, and when the color fails a level, a chip at the -end of the row shows `color.contrast`'s `fix` for the first level it fails; a click, or Enter while the chip has the focus, applies it. +color picked there meets AA (solid) and AAA (dashed) for the category, also when the active fill or stroke is None +or a pattern and the row shows a dash. The lines are hidden while Alt is held, since a pick then goes to the other +proxy. The row's first chip shows the background the ratio is measured against, so a pinned 100 % K shows as black +with a rich black Appearance of Black. When the color fails a level and +`color.contrast`'s `fix` has a color for the first level it fails, a chip at the end of the row shows that color; a +click, or Enter while the chip has the focus, applies it. When that fix is `null`, the row shows no chip. `{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel or the box. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences. @@ -1220,7 +1224,10 @@ selected objects that draw one color with different blend modes, or at different with a translucent or blending row over different shown rows below it), where hidden objects do not count, and the error names `opacity` when giving it settles the difference; a proxy of None, a pattern or a hidden row without `color`; and without `color`, a proxy's object drawn through an opacity mask that is not disabled, its own or that of a group, layer or instance -around it, since the mask sets how much of the color shows at each point. `against` in the +around it, since the mask sets how much of the color shows at each point; and with `"below"`, a color drawn with a +blend mode other than Normal (its row's, the object's, or a group's or layer's) while the art read behind it (a 1 pt +square at the center, as each level reads it) is not one color, since the mode mixes the color with each part of +that art in its own way. `against` in the answer is the background as a working RGB `#rrggbb`, the form `against` takes; the sampled background is rounded to 8 bits, so giving it back answers the same ratio, except when `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over @@ -1231,8 +1238,11 @@ color that meets it when drawn the same way, in the model of the measured color, closest color also meets the level with the color, the background, the art below each group or layer it is drawn through, the opacities, and the color and alpha each level gives rounded to 8 bits per channel. The search keeps the color's [OKLCH](https://bottosson.github.io/posts/oklab/) hue, raises or lowers its lightness, -whichever takes the smaller step, and lowers its chroma where sRGB cannot show it. A level is `null` when the color -already meets it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no color meets 7:1 there). +whichever takes the smaller step, and lowers its chroma where sRGB cannot show it. It tests 16 lightnesses on each +side and narrows down the first that passes, so where the passing lightnesses on a side fall apart in more than one +stretch (under some blend modes), a nearer passing color between two tested lightnesses can be missed. A level is +`null` when the color already meets it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no +color meets 7:1 there). Color Themes (local only: no online service) keeps five-colour themes in the preferences. `colorTheme.save {colors: [...]}` saves up to five colours as they are, `colorTheme.save {color, rule}` saves the five-colour theme a From 1a21617e7394c28aafc51489ee716e0fc29dcaf2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:25:06 -0800 Subject: [PATCH 042/104] Scripts: text ranges take a number as contents, a new length and paragraph attributes - `contents` on a text frame or text range takes a number and writes it as `String(number)` gives it; other values still throw. - Setting a text range's `length` moves its end and leaves the text as it is (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ lists it as read/write). A value that is not a whole number from 0 to the units left in the frame throws. Each read of a member that gives a range gives a new object, so setting one range's length leaves the others alone. - A text range has the paragraph attributes as well as the character attributes, so `range.justification` reads and sets the paragraphs the range touches. - `characters`, `words` and `paragraphs` have `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)` (https://ai-scripting.docsforadobe.dev/jsobjref/Words/), which insert the text as one `text.editRange` and give its range. An added word is kept apart from its neighbors by a space and an added paragraph by a paragraph break; an empty string runs no command. - `app.textFonts.getByName` also finds a bundled face by its PostScript name. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom/text.rs | 162 +++++++++++++++++++++++-- crates/engine/src/tests/script_text.rs | 118 +++++++++++++++++- docs/mcp.md | 22 +++- docs/target-app-parity.md | 2 +- 4 files changed, 280 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..233ba56621 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -24,11 +24,17 @@ //! text. //! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no //! longer kept is stale. +//! - Setting a range's `length` moves its end and leaves the text as it is; each read of a member +//! that gives a range gives a new object. +//! - `add` on `characters`, `words` or `paragraphs` inserts after the collection's last item, and +//! `addBefore` before its first. An added word is kept apart from the characters next to it by a +//! space, and an added paragraph by a paragraph break. //! - A character attribute read on a range whose characters differ gives the first character's //! value; set on an empty range it changes nothing. A paragraph attribute reads the first -//! paragraph the range touches and sets every one of them. +//! paragraph the range touches and sets every one of them. A text range has the members of +//! both its `characterAttributes` and its `paragraphAttributes`. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::{HashMap, VecDeque}; use std::rc::Rc; use std::sync::{Arc, Weak}; @@ -188,6 +194,10 @@ pub(in crate::script) struct TextState { /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. fonts: RefCell>>, + /// The number of text range objects made, which numbers the next one. + made: Cell, + /// The span of each range object, by its number, whose `length` the script set. + resized: RefCell>, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -320,20 +330,32 @@ fn usize_of(n: f64) -> Option { whole(n).and_then(|v| usize::try_from(v).ok()) } +/// A new object of `class` for the span `s..e` of the frame `item` at generation `stamp`. Each +/// object is numbered, so setting one range's `length` leaves every other range as it is. fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data { let [high, low] = id_parts(item.id); - host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)]) + let made = &h.dom.text.made; + made.set(made.get() + 1); + host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp), float(made.get())]) } /// The span `d` names, when it is an object of one of `classes`. fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result { + span_and_number(h, d, classes).map(|(span, _)| span) +} + +/// The span `d` names and the number of its object, when it is an object of one of `classes`. +fn span_and_number(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<(Span, u64), HostError> { let handle = classes.iter().find_map(|c| handle_of(d, c)); - let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else { + let Some(&[run, uid, high, low, s, e, stamp, number]) = handle.as_deref() else { return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange")))); }; let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?; - let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) }; - Ok(Span { item: frame, start, end, stamp }) + let (Some(start), Some(end), Some(stamp), Some(number)) = (usize_of(s), usize_of(e), whole(stamp), whole(number)) else { + return Err(HostError::Error(STALE_RANGE.into())); + }; + let (start, end, stamp) = h.dom.text.resized.borrow().get(&number).copied().unwrap_or((start, end, stamp)); + Ok((Span { item: frame, start, end, stamp }, number)) } /// The text frame `this` names. @@ -401,10 +423,18 @@ fn read_contents(h: &Host, r: Span) -> Answer { Ok(text(to_script(&index.text[a..b]))) } +/// The text a script gives as `contents`: a string, or a number as `String(number)` writes it. +fn contents_of(value: &Data) -> std::result::Result { + match value { + Data::String(v) => Ok(from_script(v)), + Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)), + _ => Err(HostError::Type("contents must be a string or a number".into())), + } +} + /// Replaces the text of `r` with `value`, as one `text.editRange`. fn write_contents(h: &Host, r: Span, value: &Data) -> Answer { - let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) }; - let insert = from_script(v); + let insert = contents_of(value)?; let (index, s, e, _) = resolve(h, r)?; let (a, b) = (index.byte(s, false), index.byte(e, true)); if index.text[a..b] == insert { @@ -562,6 +592,21 @@ fn range_length(h: &Host, a: &[Data]) -> Answer { Ok(num(float((e - s) as u64))) } +/// Setting `length` moves the range's end to that many UTF-16 units after its start; the text +/// does not change. A length that is not a whole number from 0 to the units left in the frame +/// throws. +fn range_set_length(h: &Host, a: &[Data]) -> Answer { + let (r, number) = span_and_number(h, arg(a, 0), &["TextRange"])?; + let (index, s, _, stamp) = resolve(h, r)?; + let n = super::number(arg(a, 1), "length")?; + let left = index.len() - s; + let Some(n) = usize_of(n).filter(|n| *n <= left) else { + return Err(HostError::Range(format!("length must be a whole number from 0 to {left}"))); + }; + h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp)); + Ok(Data::Undefined) +} + /// `remove()`: deletes the range's text. fn range_remove(h: &Host, a: &[Data]) -> Answer { write_contents(h, this_range(h, a)?, &text("")) @@ -650,6 +695,85 @@ fn part_at(h: &Host, a: &[Data]) -> Answer { Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange"))) } +/// Where `add` puts its text: before or after the relative object. +fn text_placement(d: &Data) -> std::result::Result { + match d { + Data::Undefined => Ok(true), + Data::String(s) if s == "ElementPlacement.PLACEBEFORE" || s == "ElementPlacement.PLACEATBEGINNING" => Ok(false), + Data::String(s) if s == "ElementPlacement.PLACEAFTER" || s == "ElementPlacement.PLACEATEND" => Ok(true), + _ => Err(HostError::Type("insertionLocation must be PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING or PLACEATEND".into())), + } +} + +/// `add(contents, relativeObject?, insertionLocation?)` and, with `before`, `addBefore(contents)`: +/// inserts `contents` after the collection's last item (`addBefore`: before its first item), or +/// before or after `relativeObject`, a text range or text frame of the same frame, as one +/// `text.editRange`. A word gets a space on each side that touches another character that is not +/// white space; a paragraph gets a paragraph break on each side that touches another paragraph. +/// → the range of `contents`. +fn part_add(h: &Host, a: &[Data], before: bool) -> Answer { + let (r, part) = this_part(h, a)?; + let contents = contents_of(arg(a, 1))?; + let (index, s, e, _) = resolve(h, r)?; + let at = if before || matches!(arg(a, 2), Data::Undefined) { + let (items, spans) = part_spans(&index, part, s, e); + let span = |k: usize| match spans { + None => index.char_span(k), + Some(list) => list.get(k).copied(), + }; + if before { + items.clone().next().and_then(span).map_or(s, |(x, _)| x) + } else { + items.clone().next_back().and_then(span).map_or(e, |(_, y)| y) + } + } else { + let rel = arg(a, 2); + let target = if handle_of(rel, "TextFrame").is_some() { + whole_span(h, item_of(h, rel)?)?.1 + } else { + span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))? + }; + if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id { + return Err(HostError::Error("relativeObject must be text of the same text frame".into())); + } + let (_, ts, te, _) = resolve(h, target)?; + if text_placement(arg(a, 3))? { te } else { ts } + }; + if contents.is_empty() { + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + return Ok(range_ref(h, r.item, at, at, stamp, "TextRange")); + } + let b = index.byte(at, false); + let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next()); + let (lead, trail) = match part { + Part::Characters => ("", ""), + Part::Words => { + let apart = |c: Option| c.is_some_and(|c| !c.is_whitespace()); + let lead = if apart(prev) && !contents.starts_with(char::is_whitespace) { " " } else { "" }; + let trail = if apart(next) && !contents.ends_with(char::is_whitespace) { " " } else { "" }; + (lead, trail) + } + Part::Paragraphs => ( + if prev.is_some_and(|c| c != '\n') && !contents.starts_with('\n') { "\n" } else { "" }, + if next.is_some() && !contents.ends_with('\n') { "\n" } else { "" }, + ), + }; + let insert = format!("{lead}{contents}{trail}"); + edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?; + record(h, r.item, &index, at, 0, &insert)?; + let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?; + let start = at + lead.encode_utf16().count(); + Ok(range_ref(h, r.item, start, start + contents.encode_utf16().count(), stamp, "TextRange")) +} + +fn part_add_after(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, false) +} + +fn part_add_before(h: &Host, a: &[Data]) -> Answer { + part_add(h, a, true) +} + // ---- character attributes ---- #[derive(Clone, Copy)] @@ -1280,19 +1404,24 @@ fn fonts_at(h: &Host, a: &[Data]) -> Answer { Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined }) } -/// `textFonts.getByName(name)`: the PostScript name, then the family and style with a space. +/// `textFonts.getByName(name)`: the PostScript name of a bundled or installed face, then the family +/// and style with a space. fn fonts_by_name(h: &Host, a: &[Data]) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; if name.len() > super::MAX_TEXT_BYTES { return Err(HostError::Range("the name is too long".into())); } - let named = vectorcraft_text::FontDb::global().by_postscript_name(name); + let named = vectorcraft_text::FontDb::global().find_postscript(name).map(|f| (f.family.clone(), f.style.clone())); let i = with_fonts(h, |l| { h.charge_call(l.len() as u64)?; let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s))); Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name)))) })?; - i.map(|i| host_ref("TextFont", &[float(h.run), float(i as u64)])).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + match (i, named) { + (Some(i), _) => Ok(host_ref("TextFont", &[float(h.run), float(i as u64)])), + (None, Some((family, style))) => Ok(font_ref(h, &family, &style)), + (None, None) => Err(HostError::Error(NOT_FOUND.into())), + } } fn fonts_index(h: &Host, a: &[Data]) -> Answer { @@ -1493,7 +1622,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("start", read_only(l, range_start, "TextRange", "start")), ("end", read_only(l, range_end, "TextRange", "end")), ("characterOffset", read_only(l, range_start, "TextRange", "characterOffset")), - ("length", read_only(l, range_length, "TextRange", "length")), + ("length", property(l, range_length, range_set_length)), ("characters", get(l, characters)), ("words", get(l, words)), ("paragraphs", get(l, paragraphs)), @@ -1504,6 +1633,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.extend(para_members(l)); range.extend( [ "lines", @@ -1529,7 +1659,13 @@ pub(super) fn classes(l: &Link) -> Vec { class( name, None, - named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + named(vec![ + ("typename", get(l, part_typename)), + ("length", get(l, part_length)), + ("parent", get(l, part_parent)), + ("add", method(l, part_add_after)), + ("addBefore", method(l, part_add_before)), + ]), Some(function(l, part_at)), ) }; diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 36dff46fa0..a357ecfe40 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -88,7 +88,19 @@ fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() { let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);"); assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]); assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e"); - assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = 5;").contains("contents must be a string")); + assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number")); +} + +#[test] +fn contents_takes_a_number_as_its_text() { + let (mut s, id) = doc_with("x"); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\ + t.textRange.characters[0].contents = 2.5; vc.log(t.contents);", + ); + assert_eq!(out, vec![json!("7"), json!("2.5")]); + assert_eq!(plain(&s, id), "2.5"); } #[test] @@ -189,7 +201,10 @@ fn bad_attribute_values_are_refused_without_a_change() { ("r.textFont = 'Arial';", "textFont must be a TextFont"), ("r.paragraphAttributes.justification = 'LEFT';", "Justification value"), ("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"), - ("r.length = 1;", "cannot be set yet"), + ("r.length = -1;", "length must be a whole number from 0 to 3"), + ("r.length = 1.5;", "length must be a whole number from 0 to 3"), + ("r.length = 4;", "length must be a whole number from 0 to 3"), + ("r.length = 'two';", "length must be a finite number"), ] { let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}")); assert!(e.contains(want), "{src}: {e}"); @@ -246,10 +261,10 @@ fn paragraph_attributes_set_the_paragraphs_a_range_touches() { &mut s, "var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\ p[0].paragraphAttributes.spaceAfter = 4;\ - vc.log([p[0].justification === undefined, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ + vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\ vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);", ); - assert_eq!(out, vec![json!([true, "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); + assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]); // The empty paragraph after a final break belongs only to an empty range at the end. let (mut s, id) = doc_with("a\n"); let out = log( @@ -431,6 +446,101 @@ fn text_fonts_list_and_assign_fonts_by_name() { assert_eq!(&set, &(family.clone(), style.clone())); } +#[test] +fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() { + let (mut s, id) = doc_with("hello world"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\ + vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\ + w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\ + t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);", + ); + assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]); + assert_eq!(plain(&s, id), "Jello world"); + assert_eq!(undo_steps(&s), before + 1); +} + +#[test] +fn collections_of_text_add_words_characters_and_paragraphs() { + let cases = [ + ("t.words.add('x')", "hello world", "hello world x", "x"), + ("t.words.addBefore('x')", "hello world", "x hello world", "x"), + ("t.words[0].words.add('x')", "hello world", "hello x world", "x"), + ("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"), + ("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"), + ("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"), + ("t.words.add('x')", "hello world ", "hello world x ", "x"), + ("t.words.add('x')", "", "x", "x"), + ("t.words.add(7)", "a", "a 7", "7"), + ("t.characters.add('!')", "hi", "hi!", "!"), + ("t.characters[0].characters.add('x')", "hi", "hxi", "x"), + ("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"), + ("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"), + ("t.paragraphs.addBefore('top')", "one", "top\none", "top"), + ]; + for (call, text, after, added) in cases { + let (mut s, id) = doc_with(text); + let before = undo_steps(&s); + let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);")); + assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}"); + assert_eq!(plain(&s, id), after, "{call} on {text:?}"); + assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}"); + } + // Empty contents add nothing; bad arguments throw before anything changes. + let (mut s, id) = doc_with("ab"); + s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); + let before = undo_steps(&s); + let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + assert_eq!(out, vec![json!([0, 5])]); + for (call, want) in [ + ("t.words.add(null)", "contents must be a string or a number"), + ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), + ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), + ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), + ] { + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + assert!(e.contains(want), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), before); + assert_eq!(plain(&s, id), "ab"); +} + +#[test] +fn text_fonts_find_a_bundled_face_by_its_postscript_name() { + let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else { + return; // Built without the bundled fonts. + }; + let ps = face.postscript_name(); + let (mut s, _) = doc_with("abc"); + let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);")); + assert_eq!(out, vec![json!([face.family, face.style, ps])]); +} + +#[test] +fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() { + let (mut s, id) = doc_with("first\nsecond\nthird"); + let before = undo_steps(&s); + let out = log( + &mut s, + "var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\ + vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\ + t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);", + ); + assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]); + let justify: Vec = match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(), + _ => panic!("not text"), + }; + assert_eq!(justify, vec![Justify::Center; 3]); + assert_eq!(undo_steps(&s), before + 1); + let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';"); + assert!(e.contains("Justification value"), "{e}"); + assert_eq!(undo_steps(&s), before + 1); +} + #[test] fn create_outline_and_conversions_return_the_new_objects() { let (mut s, id) = doc_with("Hi"); diff --git a/docs/mcp.md b/docs/mcp.md index b837b20a5e..445018f241 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2701,7 +2701,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot `convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has `contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`, `words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and - `remove()`, and the character attributes themselves. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to + `remove()`, and the character and paragraph attributes themselves. `contents` takes a string, or a number as + `String(number)` writes it. Setting `length` to a whole number from 0 to the units left in the frame moves the range's + end and leaves the text as it is. The `characters`, `words` and `paragraphs` collections + (https://ai-scripting.docsforadobe.dev/jsobjref/Words/) have `length`, `parent`, `[i]`, + `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its + range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to 5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`, set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are @@ -2709,8 +2714,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` (https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/) lists every style of every family in the font menu, with - `length`, `[i]`, `index(key)` and `getByName(name)`, which takes a PostScript name or the family and style joined by a - space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`, + `length`, `[i]`, `index(key)` and `getByName(name)`, which takes the PostScript name of a bundled or installed font, or + the family and style joined by a space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`, `TextOrientation` and `Justification` hold strings such as `"Justification.CENTER"`. VectorCraft's own rules: offsets and lengths count UTF-16 code units, as a JavaScript string does, and an offset inside a surrogate pair takes in its whole character; one item of `characters` is one code point. `contents` gives a @@ -2735,9 +2740,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws - `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and - `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and - `orientation` cannot be set yet. + `Stale text font`. Each read of a member that gives a range gives a new object, so setting one range's `length` + leaves the others as they are. `add` without a relative object inserts after the collection's last item, and + `addBefore` before its first; with one, a text range or the text frame of the same frame, `PLACEBEFORE` and + `PLACEATBEGINNING` insert at its start and `PLACEAFTER`, `PLACEATEND` or no location at its end. An added word is + kept apart from the characters next to it by a space, and an added paragraph by a paragraph break; adding an empty + string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` + and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, + `characterOffset` and `orientation` cannot be set yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..1eb1fe5b41 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From c0d5fddc7c41bdcf57f72457e67afbd2c360d214 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:40:35 -0800 Subject: [PATCH 043/104] Scripts: the host's name table lists the text ranges' paragraph attributes and the add methods --- .../tests/it/script_host_vs_scriptcheck.rs | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b23788236e..fb505bbd2c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -151,19 +151,21 @@ const INSIDE: &[(&str, &str)] = &[ "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ - duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ - getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ - insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ - paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ - story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ - tracking tracking= typename underline underline= verticalScale verticalScale= words", + duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ + getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ + horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ + paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ + spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \ + textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ + verticalScale= words", ), ("Characters.", "prototype"), - ("Characters.prototype.", "constructor length parent typename"), + ("Characters.prototype.", "add addBefore constructor length parent typename"), ("Words.", "prototype"), - ("Words.prototype.", "constructor length parent typename"), + ("Words.prototype.", "add addBefore constructor length parent typename"), ("Paragraphs.", "prototype"), - ("Paragraphs.prototype.", "constructor length parent typename"), + ("Paragraphs.prototype.", "add addBefore constructor length parent typename"), ("CharacterAttributes.", "prototype"), ( "CharacterAttributes.prototype.", From ecc4d9cd7489ee58078dafe310bbb264148943ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:04:35 -0800 Subject: [PATCH 044/104] Tests: text frame tests index page items topmost first pageItems and textFrames now list the topmost object first, so the tests pick the rectangle and the open path by their new indices. --- crates/engine/src/tests/script_text.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 36dff46fa0..f22853d4e7 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,8 +56,8 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ @@ -67,7 +67,7 @@ fn text_frames_add_point_area_and_path_type() { ); assert_eq!(out[0], json!(4)); assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); - assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("At"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); + assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("Area"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); assert_eq!(undo_steps(&s), before + 1); // A path of another kind, or no path, is refused. assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); @@ -476,7 +476,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); From 8ede10f809d0d51fdf3b40e984f8fb4b37a527fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:15:35 -0800 Subject: [PATCH 045/104] Color Wheel: the contrast drag test drags the hue ring A drag on the wheel's inner square sets the color without a preview interaction, so the test drags the ring, which previews on one. --- crates/ui-egui/src/panels/tests_color_wheel_contrast.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index dc8bf6a825..2f938cc8e2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -187,11 +187,14 @@ fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() { assert!(behind(&p).is_none(), "the answer gave the background"); let ratio = |p: &Panel| p.app().ui.color_wheel_panel.ratio.as_ref().and_then(|(_, r)| r.as_ref()).and_then(|r| r["ratio"].as_f64()); let first = ratio(&p); - let at = p.node("Saturation and brightness").center(); - p.fx.drag_hold_at(at, egui::vec2(24.0, 0.0)); + // A drag on the hue ring, near its right edge. + let wheel = p.node("Color wheel").rect; + let at = wheel.center() + egui::vec2(wheel.width() * 0.45, 0.0); + let by = egui::vec2(0.0, 24.0); + p.fx.drag_hold_at(at, by); assert!(p.app().session.in_interaction(), "the drag previews on an interaction"); assert_ne!(ratio(&p), first, "the row asked again for the previewed color"); - p.fx.release_at(at + egui::vec2(24.0, 0.0)).idle(2); + p.fx.release_at(at + by).idle(2); assert!(!p.app().session.in_interaction(), "the release ends the drag"); assert!(behind(&p).is_none(), "the background was not read on its own during or after the drag"); assert_eq!(measured(&p).as_deref(), Some("#ffffff")); From 49c049117082d7c1b1d3b6e106793738fb4939c4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:28:18 -0800 Subject: [PATCH 046/104] Swatches: test the drag check after each command with a running drag The new test starts a row drag through the drag session and runs Delete, Undo and an unrelated edit with no pass of the panel in between. The check that runs after every command then keeps New Swatch from duplicating the restored swatch and Delete Swatch from deleting it. --- crates/ui-egui/src/panels/swatches/tests.rs | 46 +++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 9d5606a2b5..123f5be08b 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -665,6 +665,52 @@ fn new_swatch_skips_rows_replaced_during_the_drag() { assert_eq!(undo_steps(&app), undo + 1); } +/// The rows of a drag running in the drag session are checked after every command the app runs: +/// a swatch deleted and brought back by an undo, then an edit that clears the redo steps, all with +/// no pass of the panel in between, is neither duplicated by New Swatch nor deleted by Delete +/// Swatch. +#[test] +fn rows_dragged_in_the_session_are_checked_after_every_command() { + use craft::behavior::keyed; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::testing::Fixture; + + let mut app = app(); + let payload = rows_drag(&app, "Orange", &["Orange"]); + // A list row that starts the drag through the drag session, as a row of the panel does. + let mut fixture = Fixture::new(move |ui| { + let payload = payload.clone(); + let _ = List::::new("Drag source").drag_payload(move |_: &ListDrag| Some(payload.clone())).show_items( + ui, + &keyed(&[0u32], |key: &u32| *key), + &mut |_, _| ListRow::new("Dragged"), + ); + }); + fixture.room(vec2(240.0, 120.0)); + fixture.settle(); + app.ui_ctx = Some(fixture.ctx().clone()); + let from = fixture.by_label("Dragged").expect("the drag source").center(); + let key = crate::dialogs::confirm::KIND; + fixture.drag_at_pausing(from, vec2(0.0, 60.0), |f| { + let drag = craft::ui::runtime::drag::active::(f.ctx()).expect("the rows drag"); + for (id, params) in [ + ("swatch.delete", json!({"names": ["Orange"]})), + ("edit.undo", json!({})), + ("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})), + ] { + app.run(id, params).unwrap(); + } + let restored = doc_and_steps(&app); + assert!(restored.0.swatch("Orange").is_some(), "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is not duplicated"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "a swatch brought back by an undo asks nothing"); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is kept"); + }); +} + /// A selected swatch dragged onto New Swatch or Delete Swatch carries the selected swatches that /// the find field hides, which the browser leaves out of the drag, as a click on Delete Swatch /// takes them too. The copies are selected in panel order. A grabbed swatch outside the selection From 8d48a0d2754d0ea249548b52e4685467bd59a789 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:54:24 -0800 Subject: [PATCH 047/104] =?UTF-8?q?Swatches:=20a=20row=20drag=20started=20?= =?UTF-8?q?before=20File=20=E2=80=BA=20Revert=20drops=20nothing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Revert keeps the document's uid and clears its history, so a drag started before it could still duplicate or delete a swatch of the reverted document that has the same name and paint. The drag now also records the document's revert count, and New Swatch and Delete Swatch take no rows when it has changed. --- crates/ui-egui/src/panels/swatches/dnd.rs | 35 +++++++++++++-------- crates/ui-egui/src/panels/swatches/tests.rs | 19 +++++++++++ 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index c22726a967..beff034708 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -96,11 +96,13 @@ fn steps(st: &DocState) -> [u64; 4] { [serial(&h.undo, 1), serial(&h.undo, 2), serial(&h.redo, 1), serial(&h.redo, 2)] } -/// A document as a drag from the list finds it: its `uid`, its state, its newest steps ([`steps`]) -/// and the state undoing the newest undo step gives back (that step's document). +/// A document as a drag from the list finds it: its `uid` and its count of File › Revert +/// ([`DocState::reverts`]), its state, its newest steps ([`steps`]) and the state undoing the newest +/// undo step gives back (that step's document). #[derive(Clone)] pub(super) struct DragStart { uid: u64, + reverts: u64, doc: Arc, steps: [u64; 4], back: Option>, @@ -109,24 +111,25 @@ pub(super) struct DragStart { impl DragStart { pub(super) fn of(st: &DocState) -> Self { let back = st.history.undo.last().map(|e| Arc::clone(&e.doc)); - DragStart { uid: st.uid, doc: Arc::clone(&st.doc), steps: steps(st), back } + DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back } } /// Rows `names` as this document holds them. fn rows(&self, names: &[String]) -> HeldRows { let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect(); let back = rows.iter().map(|(_, r)| r.as_ref().zip(self.back.as_deref()).is_some_and(|(r, d)| r.unchanged_in(d))).collect(); - HeldRows { uid: self.uid, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back } + HeldRows { uid: self.uid, reverts: self.reverts, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back } } } -/// The rows a drag from the list carries, in the order of its names, and the document (`uid`) and -/// the state and undo history they were last checked against. A row is `None` once a state of the -/// document since the drag started did not hold it unchanged: deleted, edited, or deleted and made -/// again under its name, also with the same paint. +/// The rows a drag from the list carries, in the order of its names, and the document (`uid`, and +/// its count of File › Revert) and the state and undo history they were last checked against. A +/// row is `None` once a state of the document since the drag started did not hold it unchanged: +/// deleted, edited, or deleted and made again under its name, also with the same paint. #[derive(Clone)] pub(crate) struct HeldRows { uid: u64, + reverts: u64, doc: Weak, /// The newest undo step of the document and the one under it, and the next redo step and the /// one under it ([`steps`]). @@ -139,7 +142,12 @@ pub(crate) struct HeldRows { impl PartialEq for HeldRows { fn eq(&self, other: &Self) -> bool { - self.uid == other.uid && self.doc.ptr_eq(&other.doc) && self.steps == other.steps && self.rows == other.rows && self.back == other.back + self.uid == other.uid + && self.reverts == other.reverts + && self.doc.ptr_eq(&other.doc) + && self.steps == other.steps + && self.rows == other.rows + && self.back == other.back } } @@ -200,15 +208,16 @@ fn checked(held: HeldRows, st: &DocState) -> HeldRows { .collect(); let last = undo.last(); let back = rows.iter().map(|(_, r)| r.as_ref().zip(last).is_some_and(|(r, e)| r.unchanged_in(&e.doc))).collect(); - HeldRows { uid: held.uid, doc: Arc::downgrade(&st.doc), steps: now, rows, back } + HeldRows { uid: held.uid, reverts: held.reverts, doc: Arc::downgrade(&st.doc), steps: now, rows, back } } /// The names of drag `r` that the active document has held unchanged since the drag started -/// ([`checked`]), in the drag's order. Empty when the drag started in another document. The panel -/// keeps what it found for the drag, so the next check starts from there. +/// ([`checked`]), in the drag's order. Empty when the drag started in another document, or before +/// File › Revert replaced the document. The panel keeps what it found for the drag, so the next +/// check starts from there. pub(super) fn follow(app: &mut VectorcraftApp, r: &SwatchRows) -> Vec { let Some(st) = app.session.active() else { return vec![] }; - if st.uid != r.held.uid { + if st.uid != r.held.uid || st.reverts != r.held.reverts { return vec![]; } let kept = &mut app.ui.swatches_panel.drag; diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 123f5be08b..479f0a5f55 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -665,6 +665,25 @@ fn new_swatch_skips_rows_replaced_during_the_drag() { assert_eq!(undo_steps(&app), undo + 1); } +/// A drag started before File › Revert replaced the document duplicates and deletes nothing, also +/// when the reverted document holds the same swatches. +#[test] +fn rows_dragged_before_a_revert_are_left_alone() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + let drag = rows_drag(&app, "Orange", &["Orange"]); + let at = app.session.active_index().expect("a document"); + let copy = doc(&app); + assert!(app.session.replace_document(at, copy)); + let reverted = doc_and_steps(&app); + assert!(reverted.0.swatch("Orange").is_some(), "the reverted document has Orange"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), reverted, "the reverted document's Orange is not duplicated"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the reverted document asks nothing"); + assert_eq!(doc_and_steps(&app), reverted, "the reverted document keeps Orange"); +} + /// The rows of a drag running in the drag session are checked after every command the app runs: /// a swatch deleted and brought back by an undo, then an edit that clears the redo steps, all with /// no pass of the panel in between, is neither duplicated by New Swatch nor deleted by Delete From 1af9fe50d37d1f3e9472e53fb7d3255fc4b1683a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:14:07 -0800 Subject: [PATCH 048/104] Color Wheel: objects that differ in isolation over a blending lower row have no one answer A translucent or blending row drawn over a lower row that blends reads the art behind the object only when the object does not isolate its blending. Selected objects that differ only in isolation then draw the color over different rows, so color.contrast reports that their colors differ instead of measuring both with the first object's isolation. A blending row at no opacity, or a fill row covered by an opaque solid Normal fill row, does not count. --- crates/engine/src/cmd/colorcmds.rs | 19 ++++++++- crates/engine/src/tests/colorcontrast.rs | 49 ++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 4475897d9a..5bcbb930c9 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1418,7 +1418,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32; /// levels that change what they draw must be the same objects too, since the art below each one is /// read with that object hidden, and the object's opacity must be the same apart from its row's, /// since the row draws over the object's rows below it and the object over the art behind it, and a -/// row that blends or is translucent must lie over the same shown rows. +/// row that blends or is translucent must lie over the same shown rows, and over a lower row that +/// blends, with the same isolation. fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0); let level = |x: &Level, y: &Level| { @@ -1434,10 +1435,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1); // A row that blends or lets art through draws over the rows below it, read at one point. let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0); + // A lower row that blends reads the art behind the object unless the object isolates its + // blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending + // row at no opacity does not show, nor does a fill row without effects under an opaque solid + // Normal fill row without effects, which covers the same shape (a stroke reaches outside it). + let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty(); + let covers = |i: &vectorcraft_doc::AppearanceItem| { + plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. }) + }; + let over_blended = |d: &Drawn| { + over_rows(d) + && d.lower + .iter() + .enumerate() + .any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers))) + }; row(a) == row(b) && (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower) && a.blend == b.blend && (row(a).is_none() || a.isolate == b.isolate) + && (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate) && (given_opacity || (total(a) - total(b)).abs() < 1e-6) && (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6) && la.len() == lb.len() diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 7c2a5c838f..609aa9189e 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -1036,6 +1036,55 @@ fn isolation_leaves_a_translucent_normal_row_as_it_draws() { } } +/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one +/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the +/// other, so the white draws over different rows and there is no one answer. A given background +/// stands for the rows below and answers. +#[test] +fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let square = |s: &mut Session, x: i32, isolate: bool| { + let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items; + let top = items.iter().rposition(|i| i.is_fill()).unwrap(); + let lower = items.iter().position(|i| i.is_fill()).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + if isolate { + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + } + n + }; + let a = square(&mut s, 30, false); + let b = square(&mut s, 120, true); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}"); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ"), "{e}"); + s.execute("color.contrast", &json!({"against": "#000000"})).unwrap(); + // A blending row at no opacity does not show, so the isolation no longer changes the answer. + for n in [a, b] { + let st = s.active().unwrap(); + let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap(); + } + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); +} + /// A Difference square centered on the edge between locked black and white art: the art behind it /// is not one color where it is read, so no one color stands for it; a given background answers, /// and over one color the background is read as before. diff --git a/docs/mcp.md b/docs/mcp.md index 2787bc8791..0f2326bf51 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1236,7 +1236,8 @@ is drawn); a picked object of a dynamic symbol instance hides only itself, and t These are errors: `"below"` with nothing selected; a "?" proxy (hidden objects count there, as in the Color panel); selected objects that draw one color with different blend modes, or at different opacities without `opacity` (with `"below"`, also in different groups or layers that are translucent, have a blend mode or isolate their blending, or -with a translucent or blending row over different shown rows below it), where hidden objects do not count, and the +with a translucent or blending row over different shown rows below it, or over a shown row that blends in objects +that differ in isolating their blending), where hidden objects do not count, and the error names `opacity` when giving it settles the difference; a proxy of None, a pattern or a hidden row without `color`; and without `color`, a proxy's object drawn through an opacity mask that is not disabled, its own or that of a group, layer or instance around it, since the mask sets how much of the color shows at each point; and with `"below"`, a color drawn with a From 9c74e2f3ba6070c758971c5bc40cc6c824071f40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:04:58 -0800 Subject: [PATCH 049/104] Scripts: the host name table lists only the members the host defines --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 448e558c32..e12077408e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -100,7 +100,7 @@ const INSIDE: &[(&str, &str)] = &[ "Document.prototype.", "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames toString \ typename views views= width", ), ("Layer.", "prototype"), From 46c3e4bcff3ede242e8ed32bec591a50e9778998 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:43:17 -0800 Subject: [PATCH 050/104] Scripts: text and thread tests read frames topmost first, as pageItems lists them --- crates/engine/src/script/dom/text/threads.rs | 2 +- crates/engine/src/tests/script_text.rs | 10 +-- crates/engine/src/tests/script_threads.rs | 74 ++++++++++---------- docs/mcp.md | 4 +- 4 files changed, 45 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index cfdb4119c6..e96282ba93 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -14,7 +14,7 @@ //! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the //! frame is deleted, it throws `Stale story`. //! - `document.stories` lists one story for each type object in no thread and one for each thread, -//! in the paint order of their first frames. `index` with a string finds the first story whose +//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose //! first frame has that name. //! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep //! their place through edits made through them, as a frame's ranges do, and are stale after any diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..e711768477 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -62,7 +62,7 @@ fn text_frames_add_point_area_and_path_type() { var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); @@ -492,16 +492,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); - let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ ("t.words.add(null)", "contents must be a string or a number"), ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), - ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), ] { - let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); @@ -586,7 +586,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index 433cc041e7..c8f5737dfc 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -73,14 +73,14 @@ fn stories_list_one_story_for_each_thread_and_each_frame_in_none() { area(&mut s, 400.0, 120.0, 40.0, "Alone"); let out = log( &mut s, - "var d = app.activeDocument, st = d.stories[0];\ + "var d = app.activeDocument, st = d.stories[1];\ vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\ vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\ vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\ - vc.log(d.stories[1].textFrames[0].contents); vc.log(d.stories[1].textFrames.length);\ + vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\ d.textFrames.add(); vc.log(d.stories.length);\ vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\ - vc.log(d.textFrames[2].story.textFrames[0].contents);", + vc.log(d.textFrames[1].story.textFrames[0].contents);", ); assert_eq!( out, @@ -262,9 +262,9 @@ fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { let before = undo_steps(&s); let out = log( &mut s, - "var t = app.activeDocument.textFrames; t[0].nextFrame = t[1];\ - vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[0].story.textRange.contents);\ - t[0].nextFrame = t[1];", + "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\ + t[2].nextFrame = t[1];", ); assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]); assert_eq!(threads(&s), vec![vec![a, b]]); @@ -275,7 +275,7 @@ fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { s.execute("edit.undo", &json!({})).unwrap(); assert!(threads(&s).is_empty()); assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into())); - log(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];"); assert_eq!(threads(&s), vec![vec![b, a]]); assert_eq!(story(&s, &[b, a]), "Second.First story."); } @@ -287,9 +287,9 @@ fn null_breaks_the_link_and_each_frame_keeps_its_text() { let before = undo_steps(&s); let out = log( &mut s, - "var t = app.activeDocument.textFrames, st = t[1].story; t[1].previousFrame = null;\ - vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[0].nextFrame);\ - t[0].nextFrame = null;", + "var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\ + t[1].nextFrame = null;", ); assert_eq!(out, vec![json!(2), json!(1), json!(null)]); assert!(threads(&s).is_empty()); @@ -310,9 +310,9 @@ fn area_and_path_text_thread_the_new_frame_to_a_base_frame() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\ - var after = d.textFrames.areaText(p[1], undefined, base);\ - var first = d.textFrames.areaText(p[2], TextOrientation.HORIZONTAL, base, false);\ - var last = d.textFrames.pathText(p[3], undefined, undefined, undefined, after, true);\ + var after = d.textFrames.areaText(p[2], undefined, base);\ + var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\ vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);", ); assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]); @@ -330,9 +330,9 @@ fn a_bad_base_frame_is_refused_before_a_frame_is_made() { let count = |s: &Session| s.active().unwrap().doc.node_count(); let (n, before) = (count(&s), undo_steps(&s)); let d = "var d = app.activeDocument, p = d.pageItems;"; - assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0]);")).contains("only area type")); - assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, p[1]);")).contains("baseFrame must be a TextFrame")); - assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, d.textFrames[0], 'yes');")).contains("postFix")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix")); assert_eq!((count(&s), undo_steps(&s)), (n, before)); } @@ -389,9 +389,9 @@ fn a_link_to_the_frame_itself_is_refused() { fn a_link_that_makes_a_loop_is_refused() { let (mut s, ids) = three(); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); assert!(m.contains("loop"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); assert!(m.contains("loop"), "{m}"); unchanged(&s, &ids, &before); } @@ -400,9 +400,9 @@ fn a_link_that_makes_a_loop_is_refused() { fn a_link_into_the_middle_of_a_story_is_refused() { let (mut s, ids) = three(); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); assert!(m.contains("already has a previous frame"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[0];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];"); assert!(m.contains("already has a next frame"), "{m}"); unchanged(&s, &ids, &before); } @@ -411,13 +411,13 @@ fn a_link_into_the_middle_of_a_story_is_refused() { fn point_type_and_other_values_cannot_be_linked() { let (mut s, ids) = three(); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); assert!(m.contains("only area type"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); assert!(m.contains("only area type"), "{m}"); - let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = 5;"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;"); assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); - let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = undefined;"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;"); assert!(m.contains("TextFrame or null"), "{m}"); unchanged(&s, &ids, &before); } @@ -425,11 +425,11 @@ fn point_type_and_other_values_cannot_be_linked() { #[test] fn a_hidden_or_locked_frame_in_either_story_stops_a_link() { let (mut s, ids) = three(); - log(&mut s, "app.activeDocument.textFrames[1].locked = true;"); + log(&mut s, "app.activeDocument.textFrames[2].locked = true;"); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); assert!(m.contains("hidden or locked"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].nextFrame = null;"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;"); assert!(m.contains("hidden or locked"), "{m}"); unchanged(&s, &ids, &before); } @@ -441,12 +441,12 @@ fn a_frame_of_another_document_cannot_be_linked() { s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); area(&mut s, 10.0, 100.0, 40.0, "Elsewhere"); s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap(); - let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); + let m = failure(&mut s, "app.documents[0].textFrames[1].nextFrame = app.documents[1].textFrames[0];"); assert!(m.contains("different documents"), "{m}"); let out = log( &mut s, - "var d = app.documents[1], p = d.pageItems[1];\ - try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[2]); } catch (e) { vc.log(String(e.message)); }\ + "var d = app.documents[1], p = d.pageItems[0];\ + try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\ vc.log(p.typename); vc.log(d.textFrames.length);", ); assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]); @@ -457,16 +457,16 @@ fn a_frame_of_another_document_cannot_be_linked() { #[test] fn a_deleted_frame_makes_its_story_and_links_stale() { let (mut s, _, _) = threaded(STORY); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.length;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;"); assert!(m.contains("Stale story"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.lines;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;"); assert!(m.contains("Stale story"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;"); assert!(m.contains("Stale page item"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;"); assert!(m.contains("Stale text range"), "{m}"); // A story read from a frame that stays follows it when its link is broken. - let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[1].story; t[0].nextFrame = null; vc.log(st.textFrames.length);"); + let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);"); assert_eq!(out, vec![json!(1)]); } @@ -481,7 +481,7 @@ fn stories_refuse_bad_keys_and_huge_numbers() { assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found")); assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError")); - log(&mut s, "app.activeDocument.textFrames[0].name = 'Lead';"); + log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]); } @@ -537,7 +537,7 @@ fn stories_of_threads_that_share_a_frame_keep_their_own_text() { let b = area(&mut s, 150.0, 120.0, 60.0, "Two."); let c = area(&mut s, 300.0, 120.0, 60.0, "Three!"); std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]]; - let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[2].story.length);"); + let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);"); let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count()); assert_ne!(ab, bc); assert_eq!(out, vec![json!(ab), json!(bc)]); diff --git a/docs/mcp.md b/docs/mcp.md index d9ca3ba49e..772917dad0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2912,8 +2912,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out, and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type. - `Document.stories` lists one story for each type object in no thread and one for each thread, in the paint order of - their first frames, and `index` with a string finds the first story whose first frame has that name. A frame that + `Document.stories` lists one story for each type object in no thread and one for each thread, in the order of + their first frames in `Document.textFrames`, topmost first, and `index` with a string finds the first story whose first frame has that name. A frame that a stored thread lists twice is in its story once. A `Story` is the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its From c71a86d8ad4100348fc3a3e8993c4fe5491afd7d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 08:25:38 -0800 Subject: [PATCH 051/104] Keep unchanged Brush Options out of document history --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/dialogs/brush_options.rs | 15 ++- .../src/dialogs/brush_options/tests.rs | 96 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 7 +- docs/ui-parity.md | 3 +- 6 files changed, 119 insertions(+), 6 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f2444bc019..d0e168e4cb 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1114,7 +1114,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options only when its name or options changed; unchanged approval preserves the brush and adds no Undo", ), ( "ui.brushObjectOptions", diff --git a/crates/ui-egui/src/dialogs/brush_options.rs b/crates/ui-egui/src/dialogs/brush_options.rs index 3dbeece787..9ff3285064 100644 --- a/crates/ui-egui/src/dialogs/brush_options.rs +++ b/crates/ui-egui/src/dialogs/brush_options.rs @@ -3,8 +3,9 @@ //! Tilt, Bearing or Rotation with its Variation, over live previews of the nib and of a stroke //! (light, heavy, light pressure). Bristle Brush Options: Name (a new bristle brush name that is too //! long is refused at OK), Shape and the bristle sliders. Scatter, Art and Pattern Brush Options: see -//! [`super::brush_art_options`]. OK runs `brush.options` (strokes painted with the brush update); -//! a name another brush has, or a new bristle brush name that is too long, keeps the dialog open. +//! [`super::brush_art_options`]. A changed OK runs `brush.options` (strokes painted with the brush update); +//! accepting unchanged settings closes without an Undo step. +//! A name another brush has, or a new bristle brush name that is too long, keeps the dialog open. //! //! Fields: `__brush` (the brush's name), `__type` (`calligraphic` | `bristle` | `scatter` | `art` | //! `pattern`), `name`. @@ -183,6 +184,7 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op initial.set(OPENED, FieldValue::Json(Value::Object(opened))); initial.set(KEYS, FieldValue::Json(json!(keys))); } + let unchanged = (!object && !flag(&initial, CREATE)).then(|| (string(&initial, "name"), string(&initial, "__brush"), params(&initial))); // The canvas of the current window: the Key Color dropper samples there while the dialog is open. let canvas = crate::doc_windows::current(app).map(crate::canvas::canvas_id); let dialog = HostedParamDialog::new(&ctx, KIND, initial, move |fields| { @@ -202,6 +204,15 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map, object_keys: Op None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()), _ => {} } + if let Some((opened_name, brush, opened_params)) = &unchanged { + let name = string(&result.fields, "name"); + // The command ignores an empty name and trims a supplied rename. + let same_name = name == *opened_name || name.trim().is_empty() || name.trim() == brush; + if same_name && params(&result.fields) == *opened_params { + // A deleted brush still reports its normal error instead of accepting a stale dialog. + return app.run("brush.get", json!({"name": brush})).map(|_| ()); + } + } ok(app, result) }) .ok_or("no window")?, diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 34e11865cf..d28d07fa44 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -9,6 +9,102 @@ fn app() -> VectorcraftApp { app } +#[test] +fn unchanged_normal_brush_approval_keeps_the_document_and_undo_history_exact() { + use crate::tests::panel_harness::Panel; + + for name in ["6 pt. Flat", "Bristle Round", "Confetti", "Arrow", "Diamonds"] { + let mut app = app(); + let params = if name == "Arrow" { json!({"width": 100.25}) } else { json!({}) }; + // Establish a saved library before testing a normal approval of an existing brush. + app.run("brush.options", json!({"name": name, "params": params})).unwrap(); + let brush = app.run("brush.get", json!({"name": name})).unwrap(); + let document = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1200.0, 1200.0)); + panel.app().run("ui.brushOptions", json!({"name": name})).unwrap(); + panel.frame(); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(!is_open(&panel.app()), "the unchanged {name} dialog closes normally"); + assert_eq!(panel.app().run("brush.get", json!({"name": name})).unwrap(), brush); + let app = panel.app(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc, document, "unchanged {name} approval preserves the entire stored library"); + assert_eq!(st.revision, revision); + assert_eq!(st.history.undo.len(), undo, "unchanged {name} approval adds no Undo step"); + } +} + +#[test] +fn brush_automation_approval_skips_noop_but_saves_changed_options_in_one_step() { + let mut app = app(); + app.run("brush.options", json!({"name": "Arrow", "params": {"width": 100.25}})).unwrap(); + let original = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let undo = app.session.active().unwrap().history.undo.len(); + open(&mut app, "Arrow"); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original); + assert_eq!(app.session.active().unwrap().revision, revision); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + for name in [" Arrow ", ""] { + open(&mut app, "Arrow"); + set(&mut app, json!({"name": name})); + confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original, "a command-equivalent name does not rewrite the brush"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo); + } + open(&mut app, "Arrow"); + set(&mut app, json!({"width": 110.25})); + confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Arrow"})).unwrap()["width"], json!(110.25)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, original); +} + +#[test] +fn normal_brush_rename_still_saves_and_a_deleted_brush_still_refuses_approval() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut app = app(); + app.run("brush.options", json!({"name": "Arrow", "params": {}})).unwrap(); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, crate::tests::picks::dialogs); + panel.room(vec2(1200.0, 1200.0)); + panel.app().run("ui.brushOptions", json!({"name": "Arrow"})).unwrap(); + panel.frame(); + panel.click_role("Name", Role::TEXT_INPUT); + panel.key(Key::A, Modifiers::COMMAND); + panel.type_text("Renamed Arrow"); + panel.key(Key::Tab, Modifiers::NONE); + panel.click("OK"); + panel.frame(); + panel.frame(); + assert!(!is_open(&panel.app())); + assert!(panel.app().run("brush.get", json!({"name": "Renamed Arrow"})).is_ok()); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().session.active().unwrap().doc, original); + + open(&mut panel.app(), "Arrow"); + panel.app().run("brush.delete", json!({"name": "Arrow"})).unwrap(); + let deleted = panel.app().session.active().unwrap().doc.clone(); + let undo = panel.app().session.active().unwrap().history.undo.len(); + assert!(confirm(&mut panel.app()).unwrap_err().contains("no brush named")); + assert!(is_open(&panel.app()), "the stale unchanged dialog reports its normal error"); + assert_eq!(panel.app().session.active().unwrap().doc, deleted); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + cancel(&mut panel.app()); +} + fn ctx(app: &VectorcraftApp) -> egui::Context { app.ui_ctx.clone().expect("the test app has a context") } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index e4d6d5d1c1..beba3e9870 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1115,7 +1115,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options only when its name or options changed; unchanged approval preserves the brush and adds no Undo", ), ( "ui.brushObjectOptions", diff --git a/docs/mcp.md b/docs/mcp.md index 808f600e69..c99fa4c7e6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,6 +1,6 @@ # VectorCraft MCP server -> **Last updated:** 2026-11-18 · **Change:** Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. +> **Last updated:** 2026-11-27 · **Change:** Brush Options: unchanged approval preserves the brush and adds no Undo; changed options save in one step; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained. > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). @@ -5446,6 +5446,10 @@ already walks Image Trace. Short agent entry points: for new art become no fill and a 0.5 pt black stroke; with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command. +For an existing brush, approving Brush Options without changing its trimmed name or options closes the dialog +without rewriting the brush, changing the document revision or adding Undo. A changed name or option is saved in +one step. A brush deleted while its dialog is open still gives an error on approval. + `brush.selectionArt {ids?|id?}` (a query) replies `{art}`: the object that `brush.new` given the same `ids` or `id`, or the same selection, takes as a new scatter or art brush's art and as a new pattern brush's side tile. Several objects become one group, and `art` is `null` when nothing is selected or `ids` name no object. In the app, the @@ -17024,6 +17028,7 @@ the error text. The interactive fallback applies only to ordinary File > Save, n | Date | Change | |---|---| +| 2026-11-27 | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-18 | Production Preflight: output and artboard scope, four check summaries, clickable canvas ids, effective PPI and explicit unchecked resolution coverage. | | 2026-11-14 | Built-in Tech Circuit brush library (id `tech-circuit`): Circuit Trace, Bus Lines and Terminal Nodes; ten built-in libraries. | | 2026-11-13 | The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides; Snap to Grid and Snap to Pixel still move its ends (#7252). | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9b146bfcd4..82c864ef85 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-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-27 · **Change:** minor (Brush Options: unchanged approval preserves the brush and adds no Undo; changed options save in one step; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -70,6 +70,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-27 | minor | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | From 5552e8a0151938daed134ae02d7129a5a2019d53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:55:54 -0800 Subject: [PATCH 052/104] Color Wheel: contrast measures a painting tool's color without the selection's drawing While the Live Paint Bucket or the Shape Builder is the active tool, the proxy shows the color the tool paints with, so color.contrast no longer takes the selected objects' opacities and blend modes for it, and selected objects drawn differently are no longer an error. This brings the change from #9358 onto this branch. --- crates/engine/src/cmd/colorcmds.rs | 7 ++++--- crates/engine/src/tests/colorcontrast.rs | 25 ++++++++++++++++++++++++ docs/mcp.md | 2 ++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 28121554ab..49aec43594 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color`), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), @@ -1496,8 +1496,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re .transpose() }; let drawing; - // Selected objects that share a color but draw it differently have no one answer. - if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) { + // Selected objects that share a color but draw it differently have no one answer. While the + // active tool paints with the proxy's color, the selection does not draw it. + if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) { let item = s.appearance_item(); // Every painted object inside a selected group counts, as the proxy's color comes from all, // except hidden ones and those inside a hidden group, which draw nothing. The first shown diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 609aa9189e..fdcc6264dc 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); } +/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the +/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no +/// error. +#[test] +fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap(); + let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let bucket = s.execute("color.contrast", &json!({})).unwrap(); + assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}"); + assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}"); + // A second selected object drawn at another opacity does not make the answer ambiguous. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let both = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}"); +} + #[test] fn a_translucent_group_counts_for_the_art_inside_it() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 5cd7a16596..cd97824036 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1229,6 +1229,8 @@ the art below it inside the object, groups and layer around it, the object's row the background when `against` or `opacity` is given; inside an object, group or layer that isolates its blending, the modes blend only with the art it holds); `opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque. +While the active tool paints with the proxy's color (the Live Paint Bucket, the Shape Builder's fill), that color is +drawn the same way, and the selected objects' opacities and blend modes do not apply. `against` takes a color, or `"below"` (the default, also for `null`): the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it (locked art, opacity, blend modes and images included; template layers and guides left out, as exports leave them out; the artboard's white where nothing From 477c861f62e22dec652c2329e1452234fa824af1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 17:45:10 -0800 Subject: [PATCH 053/104] Keep parity status and revision history unchanged --- docs/ui-parity.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 82c864ef85..7547d495c4 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-27 · **Change:** minor (Brush Options: unchanged approval preserves the brush and adds no Undo; changed options save in one step; scores and estimates unchanged); previously: minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-25 · **Change:** minor (G12: History row menus adapted to shared Craft list/menu controls after rebase (#8845); scores and estimates unchanged; previously: G12/M14: History row context menus, pending-edit snapshot targeting, keyboard access and document-switch dismissal (#8845); scores and estimates unchanged; previously: Pencil Edit Selected Paths follows lifted strokes, carves, loops, closes and redraws compound paths; Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: G12: Asset Export tile context menus; scores and estimates unchanged; previously: Properties panel per context (G12): contextual text Quick Actions (Create Outlines, Retype, Find and Replace…); scores and estimates unchanged; previously: Layers: a targeted item with an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the target circle's four looks differ, #8711; scores and estimates unchanged; previously: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged; Gradient stop editor: native Color-tab menu offers the five Color panel modes (#7918); validation pending; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -70,7 +70,6 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-27 | minor | Brush Options: untouched approval preserves the brush, document revision and Undo; changed settings save in one step. Native UI and automation covered. Scores and estimates unchanged. | | 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. | | 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. | | 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. | @@ -442,6 +441,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Interaction | Status | Evidence | |---|---|---| | Brush Options › Key Color eyedropper yields to one canvas click, then resumes the same draft and previous tool | done | #8284; the pick changes the dialog draft without painting or editing the document. OK applies the brush options; Cancel discards them. Escape ends the pick without sampling before a later Escape cancels the dialog. Six full-app input regressions in `crates/ui-egui/tests/brush_keycolor_modal_repro.rs` cover the actual pick, OK/reopen/Cancel, Escape, reentry, held clicks, stale releases and ordinary modal blocking. | +| Brush Options skip unchanged approval | done | Approving without editing preserves the brush, document revision and Undo history. | | Ordinary Save refused by filesystem permissions/read-only storage offers Save As | focused UI regressions passed; native acceptance pending | #6146; `io::tests_read_only_save`; same name/format suggested; unchanged format keeps options, changed format opens its Save options; Documents folder, UID-bound continuation; cancellation and automation isolation | | Selection artwork drag hovers a visible document tab to activate it, then drops editable artwork on its canvas | done | `tests_document_drag`, `edit.dropSelection`, lossless resource and one-step Undo regressions; a release over another document's tiled pane copies it there too (`canvas::panes` tests), and so does a release over a floating window drawn inside the main window (`doc_windows` tests); overflow-menu drag and floating OS windows remain separate | | A document tab dragged along the tab strip moves its document; a line marks where it goes, the current document and every document's view stay as they were, and a drag off the strip still floats it | done | #5663, [public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html); `document.move`; `tests::tab_reorder`, `chrome::tests` (drop index with floating and view tabs), `engine` `tests::document_move` | From 4ec043813a762bef287bf4f86fcf337d1f84bbda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:33:32 -0800 Subject: [PATCH 054/104] Color Wheel: contrast lines stain picks for a symbol object with no fill With a picked object of a dynamic symbol instance whose fill or stroke is None or a pattern, the contrast lines measured picks unstained, although a solid pick there is mixed towards the instance's stain when drawn. Picks are now measured with the stain, as for a solid color; gradients are still measured unstained. --- crates/engine/src/cmd/colorcmds.rs | 13 ++++++++----- crates/engine/src/tests/colorcontrast.rs | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 49aec43594..b046c85090 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1341,7 +1341,7 @@ fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option< (_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone)); passes.push(pass); } - let stain = if given { None } else { stain_of(s) }; + let stain = if given { None } else { stain_of(s, !need_color) }; Ok((color, Backdrop { against, written, passes, stain, rich_black })) } @@ -1619,11 +1619,14 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s /// The color and amount a fill stains the picked object of a dynamic symbol instance with /// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when -/// such an object is picked and its proxy shows a solid color. -fn stain_of(s: &Session) -> Option<(Color, f32)> { +/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None +/// or a pattern counts too, as the pick puts a solid color in its place. +fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> { let (fill, stroke) = s.proxy_paints(); - if !matches!(if s.fill_active { fill } else { stroke }, Paint::Solid { .. }) { - return None; + match if s.fill_active { fill } else { stroke } { + Paint::Solid { .. } => {} + Paint::None | Paint::Pattern { .. } if pick => {} + _ => return None, } let st = s.active()?; let sp = st.selection.symbol_part.as_ref()?; diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index fdcc6264dc..fecd16ed2a 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -786,6 +786,25 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() { assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}"); } +/// A pick for a picked symbol object with a fill of None puts a solid color there, which the +/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained. +#[test] +fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() { + let mut s = picked_symbol_part(); + let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance; + s.active_mut().unwrap().selection.symbol_part = None; + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] }); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure"); + let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap(); + let cms = vectorcraft_color::cms::active(); + let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0))); + let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); + assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}"); +} + #[test] fn a_picked_symbol_object_is_drawn_at_its_instances_opacity() { let mut s = picked_symbol_part(); From 62f1abe5bd34b43942543d6802ab36ec324a8f93 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:58:46 -0800 Subject: [PATCH 055/104] Scripts: collection reads look up names such as -1 and 1.5 The indexer hands a key that is the text of a number to the collection as a number, so pageItems["-1"] and documents["1.5"] read as positions and gave undefined, and "-1" in pageItems was false, even when getByName("-1") found the object. pageItems and documents now take only array indices as positions and look up any other number by its text as a name, giving undefined when nothing has it. index(key) still takes a number as a position. --- crates/engine/src/script/dom.rs | 70 ++++++++++++++++++++------- crates/engine/src/tests/script_dom.rs | 30 ++++++++++++ docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 87 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 46ca2824d4..c61dc66b7e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -840,11 +840,19 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer { Ok(host_ref("Application", &[])) } -/// `documents[i]`, and `documents["name"]` as `getByName` reads it. +/// `documents[i]`, and `documents["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no document has it. fn docs_at(h: &Host, a: &[Data]) -> Answer { let s = h.session.borrow(); let at = match arg(a, 1) { - Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)), + Data::Number(n) => match position(*n) { + Some(i) => s.documents().get(i), + None => { + let name = vectorcraft_js::number_to_string(*n); + s.documents().iter().find(|d| d.title() == name) + } + }, Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) { None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())), found => found, @@ -864,10 +872,11 @@ fn docs_by_name(h: &Host, a: &[Data]) -> Answer { fn docs_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => docs_by_name(h, a), - Data::Number(_) => match docs_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let s = h.session.borrow(); + let st = position(*n).and_then(|i| s.documents().get(i)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?; + Ok(doc_ref(h, st.uid)) + } _ => Err(HostError::Type("give a name or an index".into())), } } @@ -1453,27 +1462,49 @@ fn probing(a: &[Data]) -> bool { matches!(arg(a, 2), Data::Bool(true)) } -/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. +/// The position an indexer key names when it is an array index, 0 to 2^32 - 2. +fn position(n: f64) -> Option { + whole(n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) +} + +/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it. A key that is the text of a +/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is +/// looked up as that name, giving `undefined` when no object has it. fn items_at(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - if let Data::String(_) = arg(a, 1) { - return match items_by_name(h, a) { + match arg(a, 1) { + Data::String(_) => match items_by_name(h, a) { Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined), r => r, - }; + }, + Data::Number(n) => match position(*n) { + Some(i) => Ok(item_at(h, doc, i)), + None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) { + Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined), + r => r, + }, + }, + _ => Ok(Data::Undefined), } - let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; - let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))) +} + +/// The object at position `i` of `pageItems`, or `undefined` past the end. +fn item_at(h: &Host, doc: Doc, i: usize) -> Data { + with_doc(h, doc, |_, st| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))) } fn items_by_name(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + items_named(h, doc, name) +} + +/// The first object of `pageItems` named `name`, or `Not found`. +fn items_named(h: &Host, doc: Doc, name: &str) -> Answer { with_doc(h, doc, |_, st| { let ids = page_items(h, st); h.charge_call(ids.len() as u64)?; - let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); + let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name)); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) } @@ -1481,10 +1512,13 @@ fn items_by_name(h: &Host, a: &[Data]) -> Answer { fn items_index(h: &Host, a: &[Data]) -> Answer { match arg(a, 1) { Data::String(_) => items_by_name(h, a), - Data::Number(_) => match items_at(h, a)? { - Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), - d => Ok(d), - }, + Data::Number(n) => { + let doc = items_doc(h, a)?; + match position(*n).map(|i| item_at(h, doc, i)) { + None | Some(Data::Undefined) => Err(HostError::Error(NOT_FOUND.into())), + Some(d) => Ok(d), + } + } _ => Err(HostError::Type("give a name or an index".into())), } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index c1aa77e6a6..a8a0615354 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1753,6 +1753,36 @@ fn a_collection_read_with_a_name_gives_the_named_object() { assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); } +/// A collection read with a name that is the text of a number but not an array index, such as `-1` +/// or `1.5`, gives the object of that name, and `undefined` when nothing has it; array indices stay +/// positions, and `index` still takes a number as a position. +#[test] +fn a_collection_read_with_a_number_name_that_is_not_an_index_gives_the_named_object() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap(); + s.execute("object.setProps", &json!({"ids": [b.0], "name": "NaN"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, m = [];\ + vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p.NaN === p.getByName('NaN'), 'NaN' in p]);\ + vc.log([p['1.5'] === undefined, '1.5' in p, p[0].name, p['1'].name]);\ + try { p.index(-1); } catch (e) { m.push(e.message); }\ + var t = new DocumentPreset(); t.title = '1.5'; var d = app.documents.addDocument('Print', t);\ + var ds = app.documents; vc.log([ds['1.5'] === d, '1.5' in ds, ds[1.5] === d, ds['-1'] === undefined, '-1' in ds]);\ + try { ds.index(1.5); } catch (e) { m.push(e.message); }\ + vc.log(m);", + ); + assert_eq!( + out, + vec![ + json!([true, true, true, true, true]), + json!([true, false, "NaN", "-1"]), + json!([true, true, true, true, false]), + json!(["Not found", "Not found"]), + ] + ); +} + /// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or /// locked layer throw and the run changes nothing, while its name and note still change; an object /// that is hidden or locked itself takes them. diff --git a/docs/mcp.md b/docs/mcp.md index 1bbe49574d..2aa1994574 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2848,7 +2848,10 @@ other files through `$`: [Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/) shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws `Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too - (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` + (VectorCraft's own rule). A read with the text of a number that is not an array index, such as + `pageItems["-1"]`, `pageItems[1.5]` or `documents["NaN"]`, looks for an object of that name and gives `undefined` + when nothing has it, and `"-1" in pageItems` is true when an object has that name; `index(key)` takes a number as + a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note` take a number or a Boolean as the text `String(value)` gives. `String(object)` gives `[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document ]`, `[Layer ]`, `[Application]` and `[PageItems]` (VectorCraft's own rule). diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a54102e675..8ba494f9bb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1089,7 +1089,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name (a name that is the text of a number, such as `-1` or `1.5`, included) and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 7da320875f8590ecebe06b932cc225eacfa3f098 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Sat, 28 Nov 2026 11:14:03 +0500 Subject: [PATCH 056/104] Object Mosaic: clear the away warning on return to the original image (#9848) A refusal given while the dialog was in another drawing, or with its image unselected, now clears once the per-frame sync finds the original image again, for both OK's held refusal and Use Ratio's note. Refusals of the values themselves, and the Revert and Undo/Redo guards, stay. --- crates/ui-egui/src/dialogs/object_mosaic.rs | 75 ++++++++++++++++++++- 1 file changed, 72 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/object_mosaic.rs b/crates/ui-egui/src/dialogs/object_mosaic.rs index 49f355273a..43d43d4c93 100644 --- a/crates/ui-egui/src/dialogs/object_mosaic.rs +++ b/crates/ui-egui/src/dialogs/object_mosaic.rs @@ -108,6 +108,9 @@ pub struct ObjectMosaicDialog { note: Option