From cc5d3b5537f723cb7885bd8f617d0ec38bf80e44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:20:49 -0800 Subject: [PATCH 001/153] 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 ad4a6477b371d35e57945d382e9465be480d96f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 04:31:52 -0800 Subject: [PATCH 002/153] Color Wheel: Copy Color As copies the color as hex, hex with alpha, CSS or CMYK values Part of #978. The Color Wheel panel menu gets Copy Color As, with Hex, Hex with Alpha, CSS rgb(), CSS hsl(), CSS oklch() and CMYK Values. Each item puts the panel's color on the clipboard as plain text and shows what it copied in the status bar. The opacity that Show Opacity edits goes into Hex with Alpha (ff at 100 %) and, under 100 %, after a slash in the CSS forms. CSS oklch() is gray while the working RGB space is not sRGB. color.format {color, opacity?, notation} answers the text. Hex, the CSS forms and color.parse use the same working RGB numbers, so color.parse reads every form but CMYK back to the same color. CMYK Values converts through the color settings and is written as a new swatch is named (C=0 M=50 Y=100 K=0). --- crates/color/src/css.rs | 160 +++++++++++++++- crates/engine/src/cmd/colorcmds.rs | 34 ++++ crates/engine/src/cmd/paint.rs | 6 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/colormgmt.rs | 67 +++++++ crates/engine/tests/color_settings.rs | 36 ++++ crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 8 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tests.rs | 21 +++ crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 50 ++++- .../src/panels/tests_color_wheel_copy.rs | 175 ++++++++++++++++++ docs/mcp.md | 17 ++ docs/target-app-parity.md | 2 +- 40 files changed, 843 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_copy.rs diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 6fa17e0df1..20fb11dd7a 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -6,7 +6,7 @@ //! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also //! take the comma-separated legacy form (). //! Hues take the angle units of CSS Values 4 (). A hex -//! color may leave out its `#`. +//! color may leave out its `#`. [`format`] writes a color in these forms. use crate::oklab::{self, CHROMA_FULL}; @@ -83,6 +83,126 @@ fn byte(v: f32) -> u8 { (v.clamp(0.0, 1.0) * 255.0).round() as u8 } +/// The forms [`format`] writes a color in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Notation { + /// `#rrggbb`. + Hex, + /// `#rrggbbaa`, `ff` for a color without an alpha. + HexAlpha, + /// `rgb(51 102 153)`. + Rgb, + /// `hsl(210 50% 40%)`. + Hsl, + /// `oklch(49.93% 0.0987 250.43)`. + Oklch, +} + +/// `rgb` (red, green and blue from 0 to 1) and the alpha `alpha` (0 to 1) as text of `notation` +/// that [`parse`] reads back to the same `#rrggbb`. Each channel is first rounded to the nearest of +/// 256 steps, as [`hex_of`] rounds it. `rgb()`, `hsl()` and `oklch()` use the space-separated form +/// and add the alpha as a percentage after a `/` when it rounds to less than 100 %; `hsl()` and +/// `oklch()` give their numbers to two places (chroma to four), without trailing zeros, and +/// `oklch()` takes one or two more places where fewer would read back to other bytes. The hue of a +/// gray is 0. [`Notation::Hex`] leaves the alpha out. +pub fn format(rgb: [f32; 3], alpha: Option, notation: Notation) -> String { + // A NaN alpha reads as none. + let alpha = alpha.filter(|a| !a.is_nan()); + let bytes = rgb.map(byte); + let units = bytes.map(|v| f64::from(v) / 255.0); + let [r, g, b] = bytes; + match notation { + Notation::Hex => hex_of(rgb), + Notation::HexAlpha => format!("{}{:02x}", hex_of(rgb), byte(alpha.unwrap_or(1.0))), + Notation::Rgb => format!("rgb({r} {g} {b}{})", alpha_part(alpha)), + Notation::Hsl => { + let [h, s, l] = rgb_to_hsl(units); + format!("hsl({} {}% {}%{})", hue_text(h), number(s * 100.0, 2), number(l * 100.0, 2), alpha_part(alpha)) + } + Notation::Oklch => { + let lch = oklab::to_oklch(units.map(|v| v as f32)); + // The fewest places that read back to the same bytes, from two (four for chroma). + let fits = |p: i32| oklch_rounded(lch, p).filter(|&[l, c, h]| oklab::from_oklch(l, c, h).0.map(byte) == bytes); + let (p, [l, c, h]) = (0..3).find_map(|extra| fits(extra).map(|v| (extra, v))).unwrap_or((2, oklch_rounded(lch, 2).unwrap_or(lch))); + let places = |base: i32| usize::try_from(base + p).unwrap_or(2); + let c = number(c, places(4)); + // A chroma that rounds to 0 is a gray, whose hue is 0. + let h = if c == "0" { "0".to_string() } else { hue_text_to(h, places(2)) }; + format!("oklch({}% {c} {h}{})", number(l * 100.0, places(2)), alpha_part(alpha)) + } + } +} + +/// OKLCH `lch` rounded as [`format`] writes it with `extra` more places than two for the +/// lightness percentage and the hue and four for the chroma, or `None` when no chroma at or under +/// the rounded one within [`OKLCH_CHROMA_STEPS`] steps lies inside sRGB. A color on the edge of +/// sRGB can round to a point just outside it, where [`parse`] would lower the chroma to the edge at +/// the rounded lightness and hue; the chroma is lowered a step at a time instead. +fn oklch_rounded([l, c, h]: [f64; 3], extra: i32) -> Option<[f64; 3]> { + let (l, h) = (rounded(l, 4 + extra), rounded(h, 2 + extra)); + let step = 10f64.powi(-(4 + extra)); + let mut c = rounded(c, 4 + extra); + for _ in 0..OKLCH_CHROMA_STEPS { + if c <= 0.0 || oklab::in_srgb(oklab::oklch_to_srgb(l, c, h)) { + return Some([l, c.max(0.0), h]); + } + c = rounded(c - step, 4 + extra); + } + None +} + +/// The most steps [`oklch_rounded`] lowers a chroma by to bring it inside sRGB. +const OKLCH_CHROMA_STEPS: usize = 50; + +/// `v` rounded to `places` decimal places. +fn rounded(v: f64, places: i32) -> f64 { + let f = 10f64.powi(places); + (v * f).round() / f +} + +/// ` / 50%` for an alpha that rounds to less than 100 %, else nothing. +fn alpha_part(alpha: Option) -> String { + let percent = number(f64::from(alpha.unwrap_or(1.0).clamp(0.0, 1.0)) * 100.0, 2); + if percent == "100" { String::new() } else { format!(" / {percent}%") } +} + +/// A hue in degrees to two places, 360 written as 0. +fn hue_text(h: f64) -> String { + hue_text_to(h, 2) +} + +/// A hue in degrees to `places` places, 360 written as 0. +fn hue_text_to(h: f64, places: usize) -> String { + let text = number(h, places); + if text == "360" { "0".to_string() } else { text } +} + +/// `v` to `places` decimal places, without trailing zeros or a sign on zero. +fn number(v: f64, places: usize) -> String { + let text = format!("{v:.places$}"); + let text = if text.contains('.') { text.trim_end_matches('0').trim_end_matches('.') } else { text.as_str() }; + if text == "-0" { "0".to_string() } else { text.to_string() } +} + +/// Hue in degrees (0 to 360), saturation and lightness (0 to 1) of `rgb`, by CSS Color 4's +/// rgbToHsl (); the hue of a gray is 0. +fn rgb_to_hsl([r, g, b]: [f64; 3]) -> [f64; 3] { + let (max, min) = (r.max(g).max(b), r.min(g).min(b)); + let (d, l) = (max - min, (max + min) / 2.0); + if d == 0.0 { + return [0.0, 0.0, l]; + } + let s = if l == 0.0 || l == 1.0 { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let h = if max == r { + (g - b) / d + if g < b { 6.0 } else { 0.0 } + } else if max == g { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + [h * 60.0, s, l] +} + /// A hex color of 3, 4, 6 or 8 digits, with or without `#`. fn hex(text: &str) -> Option { let digits = text.strip_prefix('#').unwrap_or(text); @@ -404,6 +524,26 @@ mod tests { assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); } + #[test] + fn format_writes_each_notation_with_the_alpha_where_it_belongs() { + let rgb = [0.2, 0.4, 0.6]; + let half = Some(0.5); + assert_eq!(format(rgb, half, Notation::Hex), "#336699"); + assert_eq!(format(rgb, half, Notation::HexAlpha), "#33669980"); + assert_eq!(format(rgb, None, Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, Some(1.0), Notation::HexAlpha), "#336699ff"); + assert_eq!(format(rgb, half, Notation::Rgb), "rgb(51 102 153 / 50%)"); + assert_eq!(format(rgb, None, Notation::Rgb), "rgb(51 102 153)"); + assert_eq!(format(rgb, Some(0.99999), Notation::Rgb), "rgb(51 102 153)", "an alpha that rounds to 100 % is left out"); + assert_eq!(format(rgb, Some(0.125), Notation::Hsl), "hsl(210 50% 40% / 12.5%)"); + assert_eq!(format(rgb, None, Notation::Oklch), "oklch(49.93% 0.0987 250.43)"); + assert_eq!(format([0.5; 3], None, Notation::Hsl), "hsl(0 0% 50.2%)"); + assert_eq!(format([1.0; 3], None, Notation::Oklch), "oklch(100% 0 0)"); + assert_eq!(format([0.0; 3], Some(0.0), Notation::Oklch), "oklch(0% 0 0 / 0%)"); + assert_eq!(format([1.0, 0.0, 0.0], None, Notation::Hsl), "hsl(0 100% 50%)"); + assert_eq!(format([-1.0, 2.0, f32::NAN], Some(f32::NAN), Notation::Rgb), "rgb(0 255 0)"); + } + proptest! { #[test] fn random_text_never_panics(text in "\\PC{0,60}") { @@ -431,5 +571,23 @@ mod tests { prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a)); prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}")); } + + #[test] + fn each_notation_reads_back_to_the_same_color(r: u8, g: u8, b: u8, a: u8) { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let alpha = f32::from(a) / 255.0; + for notation in [Notation::Hex, Notation::HexAlpha, Notation::Rgb, Notation::Hsl, Notation::Oklch] { + let text = format(rgb, Some(alpha), notation); + let c = parse(&text).unwrap_or_else(|| panic!("{text} should parse")); + prop_assert_eq!(hex_of(c.rgb), hex_of(rgb), "{}", text); + let read = c.alpha.unwrap_or(1.0); + match notation { + Notation::Hex => prop_assert_eq!(c.alpha, None), + Notation::HexAlpha => prop_assert_eq!(byte(read), a), + // A percentage to two places, left out when it rounds to 100. + _ => prop_assert!((read - alpha).abs() <= 0.00006, "{} gives {}", text, read), + } + } + } } } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 071f2ed3f7..93dad8a9a2 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -145,9 +145,43 @@ pub fn specs() -> Vec { always, parse_color ), + cmd!( + query "color.format", + "Format Color", + [], + None, + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity is under 100, hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + always, + format_color + ), ] } +fn format_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.format"; + let col = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?; + let opacity = super::paint::opacity_param(p, C)?; + let notation = match text_param(p, "notation", C)? { + Some("hex") => Some(css::Notation::Hex), + Some("hexAlpha") => Some(css::Notation::HexAlpha), + Some("rgb") => Some(css::Notation::Rgb), + Some("hsl") => Some(css::Notation::Hsl), + Some("oklch") => Some(css::Notation::Oklch), + Some("cmyk") => None, + _ => return Err(bad(C, "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk")), + }; + let cms = vectorcraft_color::cms::active(); + let intent = cms.settings().intent; + let text = match notation { + None => vectorcraft_doc::swatches::color_name(cms.convert(&col, Model::Cmyk, intent)), + Some(css::Notation::Oklch) if !cms.rgb_is_srgb() => return Err(bad(C, "OKLCH needs sRGB as the working RGB space")), + // The working RGB numbers, as the Color panel's hex field and color.parse read them; for + // oklch() the working RGB space is sRGB. + Some(n) => css::format(cms.convert(&col, Model::Rgb, intent).to_rgb_uncalibrated(), opacity, n), + }; + Ok(json!({ "text": text })) +} + fn parse_color(_: &mut Session, p: &Value) -> Result { const C: &str = "color.parse"; let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2a2cab339d..ae9dcda41e 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -522,9 +522,9 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result { apply_paint_opacity(s, p, paint, opacity, fill) } -/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None` -/// when it is left out or null. -fn opacity_param(p: &Value, cmd: &str) -> Result> { +/// The `opacity` param of `paint.setFill`, `paint.setStroke` and `color.format` (a percentage) as +/// 0..1; `None` when it is left out or null. +pub(crate) fn opacity_param(p: &Value, cmd: &str) -> Result> { match p.get("opacity") { None | Some(Value::Null) => Ok(None), Some(v) => match v.as_f64() { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index ff5734a4f6..0c55a60a49 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -140,6 +140,7 @@ pub(super) const ALLOWED: &[&str] = &[ "charStyle.setAttrs", "charStyle.unused", "color.convert", + "color.format", "color.gamutCheck", "color.harmony", "color.parse", diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 2c76f2b0b6..70b1aeb0b6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -390,6 +390,73 @@ fn parse_err(s: &mut Session, p: Value) -> String { s.execute("color.parse", &p).unwrap_err().to_string() } +/// `color.format` writes each notation, with the opacity only where it belongs, and `color.parse` +/// reads every notation but CMYK back to the same color and opacity. +#[test] +fn format_writes_each_notation_and_parse_reads_it_back() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let s = &mut s; + let fmt = |s: &mut Session, color: Value, opacity: Value, notation: &str| { + let r = s.execute("color.format", &json!({ "color": color, "opacity": opacity, "notation": notation })).unwrap(); + r["text"].as_str().unwrap().to_string() + }; + let blue = json!("#336699"); + for (notation, at_half, at_full) in [ + ("hex", "#336699", "#336699"), + ("hexAlpha", "#33669980", "#336699ff"), + ("rgb", "rgb(51 102 153 / 50%)", "rgb(51 102 153)"), + ("hsl", "hsl(210 50% 40% / 50%)", "hsl(210 50% 40%)"), + ] { + assert_eq!(fmt(s, blue.clone(), json!(50), notation), at_half, "{notation}"); + assert_eq!(fmt(s, blue.clone(), Value::Null, notation), at_full, "{notation}"); + } + let oklch = fmt(s, blue.clone(), json!(25), "oklch"); + assert!(oklch.starts_with("oklch(") && oklch.ends_with(" / 25%)"), "{oklch}"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let cmyk = s.execute("color.convert", &json!({ "color": "#336699", "to": "cmyk" })).unwrap(); + let pct: Vec = cmyk["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + let expected = format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3]); + assert_eq!(expected, "C=87 M=61 Y=19 K=0", "the default color settings, as docs/mcp.md gives them"); + assert_eq!(fmt(s, blue.clone(), json!(50), "cmyk"), expected); + assert_eq!(fmt(s, json!({"c": 10, "m": 20, "y": 30, "k": 0}), Value::Null, "cmyk"), "C=10 M=20 Y=30 K=0", "a CMYK color keeps its values"); + assert_eq!(fmt(s, json!({"gray": 40}), Value::Null, "cmyk"), "C=0 M=0 Y=0 K=40"); + for color in [json!("#336699"), json!("#0a0b0c"), json!("#ff0000"), json!("#ffffff"), json!({"c": 100, "m": 0, "y": 0, "k": 0})] { + for (notation, opacity) in [("hex", Value::Null), ("hexAlpha", json!(40)), ("rgb", json!(12.5)), ("hsl", json!(99.99)), ("oklch", json!(0))] { + let text = fmt(s, color.clone(), opacity.clone(), notation); + let shown = fmt(s, color.clone(), Value::Null, "hex"); + let r = s.execute("color.parse", &json!({ "text": text })).unwrap(); + assert_eq!(r["hex"], json!(shown), "{color} {notation}: {text}"); + match notation { + "hex" => assert_eq!(r["opacity"], Value::Null, "{text}"), + "hexAlpha" => assert_eq!(r["opacity"], json!(40.0), "{text}"), + _ => assert_eq!(r["opacity"], opacity.as_f64().map_or(Value::Null, |o| json!(o)), "{text}"), + } + } + } +} + +/// `color.format` refuses a missing or wrong color, opacity or notation. +#[test] +fn format_refuses_bad_params() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut err = |p: Value| s.execute("color.format", &p).unwrap_err().to_string(); + let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk"; + assert!(err(json!({"color": "#336699"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "css"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": "HEX"})).ends_with(notation)); + assert!(err(json!({"color": "#336699", "notation": 1})).ends_with("`notation` must be a string")); + assert!(err(json!({"notation": "hex"})).ends_with("missing or invalid `color`")); + assert!(err(json!({"color": "#33669980", "notation": "hex"})).ends_with("missing or invalid `color`")); + for opacity in [json!(-1), json!(101), json!("50"), json!(true)] { + assert!( + err(json!({"color": "#336699", "opacity": opacity, "notation": "rgb"})).ends_with("`opacity` must be a number from 0 to 100"), + "{opacity}" + ); + } +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 81fc274743..6bd0a9d66f 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1048,3 +1048,39 @@ fn color_parse_takes_oklch_only_in_an_srgb_working_space() { assert_eq!((&hex["hex"], &hex["opacity"]), (&json!("#336699"), &json!(50.2))); assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again"); } + +/// `color.format` writes `oklch()` only while the working RGB space is sRGB, and writes every CSS +/// form of a CMYK color from the RGB numbers the rendering intent gives, so `color.parse` reads each +/// back to the hex color `color.format` gives. +#[test] +fn color_format_writes_every_css_form_through_the_intent() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + let format = |s: &mut Session, color: &serde_json::Value, notation: &str| { + s.execute("color.format", &json!({"color": color, "notation": notation})).map(|r| r["text"].as_str().unwrap_or_default().to_string()) + }; + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let wide = format(&mut s, &json!("#336699"), "oklch").map_err(|e| e.to_string()); + // The Generic CMYK profile's file loaded as an ICC profile, which converts through the intent. + let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name; + s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap(); + let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); + let intents_differ = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8) + != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); + // Collected as results, so that a failure still restores the process-wide settings first. + let mut read_back = vec![]; + for notation in ["hex", "rgb", "hsl", "oklch"] { + let text = format(&mut s, &cyan, notation).map_err(|e| e.to_string()); + let hex = text.clone().and_then(|t| s.execute("color.parse", &json!({"text": t})).map(|r| r["hex"].clone()).map_err(|e| e.to_string())); + read_back.push((notation, text, hex)); + } + cms::set_active(&old).unwrap(); + cms::unregister_icc(&icc); + assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}"); + assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB"); + let hex = read_back[0].1.clone().unwrap(); + for (notation, text, back) in read_back { + assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}"); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 8d6a2c626f..a263c2c503 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2360,6 +2360,14 @@ font-technology Variable Променливи Show Hex Field Показване на шестнадесетичното поле Hex or CSS color Шестнадесетичен или CSS цвят Parse Color Разчитане на цвят + Format Color Форматиране на цвят + Copy Color As Копиране на цвета като + Hex Hex + Hex with Alpha Hex с алфа + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Стойности CMYK Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване Opacity Mask Маска за непрозрачност Opacity Mask Info Информация за маската за непрозрачност @@ -4354,6 +4362,8 @@ axis Both И двете @msg `color` must be a colour `color` трябва да бъде цвят @msg `sliders` must be none or oklch `sliders` трябва да бъде none или oklch @msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` трябва да бъде hex, hexAlpha, rgb, hsl, oklch или cmyk +@msg Copied the color as {text} Цветът е копиран като {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` трябва да бъде шестнадесетичен цвят (#rgb, #rgba, #rrggbb или #rrggbbaa) или CSS цвят rgb(), hsl() или oklch() с най-много 48 знака @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 0120f0ce67..a9ee0af99a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -466,6 +466,14 @@ Show Hex Field Prikaži hex polje Hex or CSS color Hex ili CSS boja Parse Color Raščlani boju + Format Color Formatiraj boju + Copy Color As Kopiraj boju kao + Hex Hex + Hex with Alpha Hex s alfom + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK vrijednosti Stroke Color Boja poteza Fill Gradient Gradijent ispune Stroke Gradient Gradijent poteza @@ -4771,6 +4779,8 @@ imageTrace Outline Obris @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue @msg `sliders` must be none or oklch `sliders` mora biti none ili oklch @msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` mora biti hex, hexAlpha, rgb, hsl, oklch ili cmyk +@msg Copied the color as {text} Boja kopirana kao {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` mora biti hex boja (#rgb, #rgba, #rrggbb ili #rrggbbaa) ili CSS boja rgb(), hsl() ili oklch() od najviše 48 znakova @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 630106a28c..2ccefb1300 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3006,6 +3006,14 @@ digits Malayalam Malaiàlam Show Hex Field Mostra el camp hex Hex or CSS color Color hex o CSS Parse Color Analitza el color + Format Color Formata el color + Copy Color As Copia el color com a + Hex Hex + Hex with Alpha Hex amb alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valors CMYK Opacity & Mask Define Knockout Shape L’opacitat i la màscara defineixen la forma d’exclusió Opacity Mask Màscara d’opacitat Opacity Mask Info Informació de la màscara d’opacitat @@ -5455,6 +5463,8 @@ digits Malayalam Malaiàlam @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` ha de ser none o oklch @msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` ha de ser hex, hexAlpha, rgb, hsl, oklch o cmyk +@msg Copied the color as {text} S’ha copiat el color com a {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` ha de ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() o oklch() de 48 caràcters com a màxim @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index f1203e3730..de1f1d8cc7 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -479,6 +479,14 @@ Show Hex Field Zobrazit pole hex Hex or CSS color Barva hex nebo CSS Parse Color Analyzovat barvu + Format Color Formátovat barvu + Copy Color As Kopírovat barvu jako + Hex Hex + Hex with Alpha Hex s alfou + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Hodnoty CMYK Stroke Color Barva tahu Fill Gradient Přechod výplně Stroke Gradient Přechod tahu @@ -5030,6 +5038,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue @msg `sliders` must be none or oklch `sliders` musí být none nebo oklch @msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` musí být hex, hexAlpha, rgb, hsl, oklch nebo cmyk +@msg Copied the color as {text} Barva zkopírována jako {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musí být barva hex (#rgb, #rgba, #rrggbb nebo #rrggbbaa) nebo barva CSS rgb(), hsl() nebo oklch() o nejvýše 48 znacích @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 9e005f7f9b..9d1bc87f96 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3111,6 +3111,14 @@ liquify-list-end {0}, {1} {0} og {1} Show Hex Field Vis hex-felt Hex or CSS color Hex- eller CSS-farve Parse Color Fortolk farve + Format Color Formatér farve + Copy Color As Kopiér farve som + Hex Hex + Hex with Alpha Hex med alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-værdier Stroke Color Stregfarve Fill Gradient Fyldgradient Stroke Gradient Streggradient @@ -8488,6 +8496,8 @@ mark-style Japanese Japansk @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue @msg `sliders` must be none or oklch `sliders` skal være none eller oklch @msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` skal være hex, hexAlpha, rgb, hsl, oklch eller cmyk +@msg Copied the color as {text} Kopierede farven som {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` skal være en hex-farve (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-farve rgb(), hsl() eller oklch() på højst 48 tegn @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 82348d4849..47dbd96796 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2398,6 +2398,14 @@ file-filter Templates Vorlagen Show Hex Field Hex-Feld einblenden Hex or CSS color Hex- oder CSS-Farbe Parse Color Farbe auswerten + Format Color Farbe formatieren + Copy Color As Farbe kopieren als + Hex Hex + Hex with Alpha Hex mit Alpha + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-Werte Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform Opacity Mask Deckkraftmaske Opacity Mask Info Informationen zur Deckkraftmaske @@ -4633,6 +4641,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein @msg `sliders` must be none or oklch `sliders` muss none oder oklch sein @msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` muss hex, hexAlpha, rgb, hsl, oklch oder cmyk sein +@msg Copied the color as {text} Farbe kopiert als {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` muss eine Hex-Farbe (#rgb, #rgba, #rrggbb oder #rrggbbaa) oder eine CSS-Farbe rgb(), hsl() oder oklch() mit höchstens 48 Zeichen sein @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 40127f1383..4061465ffa 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1978,6 +1978,14 @@ font-technology Variable Μεταβλητές Show Hex Field Εμφάνιση πεδίου Hex Hex or CSS color Χρώμα Hex ή CSS Parse Color Ανάλυση χρώματος + Format Color Μορφοποίηση χρώματος + Copy Color As Αντιγραφή χρώματος ως + Hex Hex + Hex with Alpha Hex με άλφα + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Τιμές CMYK Opacity Mask Μάσκα αδιαφάνειας Opacity: Αδιαφάνεια: Open Άνοιγμα @@ -6355,6 +6363,8 @@ effect Points Σημεία @msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue @msg `sliders` must be none or oklch Το `sliders` πρέπει να είναι none ή oklch @msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk Το `notation` πρέπει να είναι hex, hexAlpha, rgb, hsl, oklch ή cmyk +@msg Copied the color as {text} Το χρώμα αντιγράφηκε ως {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters Το `text` πρέπει να είναι χρώμα Hex (#rgb, #rgba, #rrggbb ή #rrggbbaa) ή χρώμα CSS rgb(), hsl() ή oklch() με έως 48 χαρακτήρες @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 0de22b4365..de84ca5e0a 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2439,6 +2439,14 @@ font-technology Variable Variables Show Hex Field Mostrar campo hex Hex or CSS color Color hex o CSS Parse Color Analizar color + Format Color Formatear color + Copy Color As Copiar color como + Hex Hex + Hex with Alpha Hex con alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valores CMYK Opacity & Mask Define Knockout Shape La opacidad y la máscara definen la forma de exclusión Opacity Mask Máscara de opacidad Opacity Mask Info Información de máscara de opacidad @@ -4735,6 +4743,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` debe ser none u oklch @msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` debe ser hex, hexAlpha, rgb, hsl, oklch o cmyk +@msg Copied the color as {text} Se copió el color como {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` debe ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() u oklch() de 48 caracteres como máximo @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2278d0a26f..63b03f2e54 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -476,6 +476,14 @@ Show Hex Field Näytä heksakenttä Hex or CSS color Heksa- tai CSS-väri Parse Color Jäsennä väri + Format Color Muotoile väri + Copy Color As Kopioi väri muodossa + Hex Heksa + Hex with Alpha Heksa ja alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-arvot Stroke Color Viivan väri Fill Gradient Täytön liukuväri Stroke Gradient Viivan liukuväri @@ -6365,6 +6373,8 @@ mark-style Japanese Japanilainen @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue @msg `sliders` must be none or oklch `sliders` on oltava none tai oklch @msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` on oltava hex, hexAlpha, rgb, hsl, oklch tai cmyk +@msg Copied the color as {text} Väri kopioitiin muodossa {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` on oltava heksaväri (#rgb, #rgba, #rrggbb tai #rrggbbaa) tai CSS-väri rgb(), hsl() tai oklch(), enintään 48 merkkiä @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 932b8ebe52..c57f6569aa 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2431,6 +2431,14 @@ font-technology Variable Variables Show Hex Field Afficher le champ hex Hex or CSS color Couleur hex ou CSS Parse Color Analyser la couleur + Format Color Mettre en forme la couleur + Copy Color As Copier la couleur en + Hex Hex + Hex with Alpha Hex avec alpha + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valeurs CMJN Opacity & Mask Define Knockout Shape L’opacité et le masque définissent la forme de masquage Opacity Mask Masque d’opacité Opacity Mask Info Infos sur le masque d’opacité @@ -4701,6 +4709,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue @msg `sliders` must be none or oklch `sliders` doit valoir none ou oklch @msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` doit valoir hex, hexAlpha, rgb, hsl, oklch ou cmyk +@msg Copied the color as {text} Couleur copiée en {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` doit être une couleur hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou une couleur CSS rgb(), hsl() ou oklch() d’au plus 48 caractères @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 3b492b1cb0..46375e42c2 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2473,6 +2473,14 @@ Show Hex Field Hex ફીલ્ડ બતાવો Hex or CSS color Hex અથવા CSS રંગ Parse Color રંગ પાર્સ કરો + Format Color રંગ ફોર્મેટ કરો + Copy Color As રંગની આ રીતે નકલ કરો + Hex Hex + Hex with Alpha આલ્ફા સાથે Hex + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK મૂલ્યો Opacity & Mask Define Knockout Shape અપારદર્શકતા અને માસ્ક નૉકઆઉટ આકાર વ્યાખ્યાયિત કરે છે Opacity Mask Info અપારદર્શકતા માસ્ક માહિતી Opacity Mask Options અપારદર્શકતા માસ્ક વિકલ્પો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 7186778d0e..6b5c2a0f22 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3280,6 +3280,14 @@ antiAlias Sharp शार्प Show Hex Field हेक्स फ़ील्ड दिखाएँ Hex or CSS color हेक्स या CSS रंग Parse Color रंग पार्स करें + Format Color रंग फ़ॉर्मेट करें + Copy Color As रंग इस रूप में कॉपी करें + Hex हेक्स + Hex with Alpha अल्फ़ा सहित हेक्स + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK मान Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप Opacity Mask ओपेसिटी मास्क Opacity Mask Info ओपेसिटी मास्क की जानकारी @@ -6356,6 +6364,8 @@ antiAlias Sharp शार्प @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए @msg `sliders` must be none or oklch `sliders` none या oklch होना चाहिए @msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` hex, hexAlpha, rgb, hsl, oklch या cmyk होना चाहिए +@msg Copied the color as {text} रंग {text} के रूप में कॉपी किया गया @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` एक हेक्स रंग (#rgb, #rgba, #rrggbb या #rrggbbaa) या अधिकतम 48 वर्णों का CSS rgb(), hsl() या oklch() रंग होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1a8a386dbc..6cfd13644a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2918,6 +2918,14 @@ file-filter Templates Sablonok Show Hex Field Hex mező megjelenítése Hex or CSS color Hex vagy CSS szín Parse Color Szín értelmezése + Format Color Szín formázása + Copy Color As Szín másolása mint + Hex Hex + Hex with Alpha Hex alfával + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-értékek Opacity & Mask Define Knockout Shape Az átlátszatlanság és a maszk adja a kiütés alakját Opacity Mask Átlátszósági maszk Opacity Mask Info Átlátszósági maszk adatai @@ -5097,6 +5105,8 @@ imageTrace Outline Körvonal @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell @msg `sliders` must be none or oklch A `sliders` értéke none vagy oklch lehet @msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk A `notation` értéke hex, hexAlpha, rgb, hsl, oklch vagy cmyk lehet +@msg Copied the color as {text} A szín másolva ebben a formában: {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`: hex szín (#rgb, #rgba, #rrggbb vagy #rrggbbaa) vagy legfeljebb 48 karakteres CSS rgb(), hsl() vagy oklch() szín kell @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 0f274ff3aa..8efb5b2972 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -434,6 +434,14 @@ Show Hex Field Tampilkan bidang hex Hex or CSS color Warna hex atau CSS Parse Color Urai warna + Format Color Format warna + Copy Color As Salin warna sebagai + Hex Hex + Hex with Alpha Hex dengan alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Nilai CMYK Stroke Color Warna stroke Fill Gradient Gradien isian Stroke Gradient Gradien stroke @@ -5755,6 +5763,8 @@ mark-style Japanese Jepang @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue @msg `sliders` must be none or oklch `sliders` harus none atau oklch @msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` harus hex, hexAlpha, rgb, hsl, oklch, atau cmyk +@msg Copied the color as {text} Warna disalin sebagai {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` harus berupa warna hex (#rgb, #rgba, #rrggbb, atau #rrggbbaa) atau warna CSS rgb(), hsl(), atau oklch() dengan paling banyak 48 karakter @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f71698cec5..c10bb13ddc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2475,6 +2475,14 @@ file-filter Templates Modelli Show Hex Field Mostra campo hex Hex or CSS color Colore hex o CSS Parse Color Analizza colore + Format Color Formatta colore + Copy Color As Copia colore come + Hex Hex + Hex with Alpha Hex con alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valori CMYK Opacity & Mask Define Knockout Shape Opacità e maschera definiscono la forma di foratura Opacity Mask Maschera di opacità Opacity Mask Info Informazioni maschera di opacità @@ -4763,6 +4771,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` deve essere none o oklch @msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` deve essere hex, hexAlpha, rgb, hsl, oklch o cmyk +@msg Copied the color as {text} Colore copiato come {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve essere un colore hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un colore CSS rgb(), hsl() o oklch() di al massimo 48 caratteri @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 08c223a437..c3efd5b398 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -522,6 +522,14 @@ digits Malayalam マラヤーラム数字 Show Hex Field 16 進フィールドを表示 Hex or CSS color 16 進または CSS カラー Parse Color カラーを解析 + Format Color カラーを書式化 + Copy Color As 形式を指定してカラーをコピー + Hex 16 進 + Hex with Alpha 16 進 (アルファ付き) + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 値 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: Stroke Color カラー (線) @@ -5179,6 +5187,8 @@ swatch Bright Violet ビビッドバイオレット @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください @msg `sliders` must be none or oklch `sliders` は none または oklch でなければなりません @msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` は hex、hexAlpha、rgb、hsl、oklch または cmyk でなければなりません +@msg Copied the color as {text} カラーを {text} としてコピーしました @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` には 16 進カラー (#rgb、#rgba、#rrggbb、#rrggbbaa) または 48 文字以内の CSS の rgb()、hsl()、oklch() カラーを指定してください @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b1af817bf2..20b8bf861c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2490,6 +2490,14 @@ Show Hex Field Hex ველის ჩვენება Hex or CSS color Hex ან CSS ფერი Parse Color ფერის გარჩევა + Format Color ფერის ფორმატირება + Copy Color As ფერის კოპირება როგორც + Hex Hex + Hex with Alpha Hex ალფათი + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK მნიშვნელობები Stroke Color კონტურის ფერი Fill Gradient შევსების გრადიენტი Stroke Gradient კონტურის გრადიენტი @@ -8101,6 +8109,8 @@ liquify-list-end {0}, {1} {0} და {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue @msg `sliders` must be none or oklch `sliders` უნდა იყოს none ან oklch @msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` უნდა იყოს hex, hexAlpha, rgb, hsl, oklch ან cmyk +@msg Copied the color as {text} ფერი დაკოპირდა როგორც {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` უნდა იყოს hex ფერი (#rgb, #rgba, #rrggbb ან #rrggbbaa) ან CSS ფერი rgb(), hsl() ან oklch(), არაუმეტეს 48 სიმბოლოსი @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index be197ef35a..3117b7cad8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -515,6 +515,14 @@ digits Malayalam 말라얄람어 Show Hex Field 16진수 필드 표시 Hex or CSS color 16진수 또는 CSS 색상 Parse Color 색상 구문 분석 + Format Color 색상 서식 지정 + Copy Color As 다음 형식으로 색상 복사 + Hex 16진수 + Hex with Alpha 알파 포함 16진수 + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 값 Pie End Angle: 파이 끝 각도: Pie Start Angle: 파이 시작 각도: Stroke Color 선 색상 @@ -5106,6 +5114,8 @@ theme Appearance 외관 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 @msg `sliders` must be none or oklch `sliders`는 none 또는 oklch여야 합니다 @msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation`은 hex, hexAlpha, rgb, hsl, oklch 또는 cmyk여야 합니다 +@msg Copied the color as {text} 색상을 {text} 형식으로 복사했습니다 @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`은(는) 16진수 색상(#rgb, #rgba, #rrggbb 또는 #rrggbbaa)이거나 최대 48자의 CSS rgb(), hsl() 또는 oklch() 색상이어야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 64ec429108..87cb7942d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1005,6 +1005,14 @@ liquify-list-end {0}, {1} {0} en {1} Show Hex Field Hexveld tonen Hex or CSS color Hex- of CSS-kleur Parse Color Kleur ontleden + Format Color Kleur opmaken + Copy Color As Kleur kopiëren als + Hex Hex + Hex with Alpha Hex met alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-waarden Stroke Color Contourkleur Fill Gradient Vulverloop Stroke Gradient Contourverloop @@ -8265,6 +8273,8 @@ mark-style Japanese Japans @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn @msg `sliders` must be none or oklch `sliders` moet none of oklch zijn @msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` moet hex, hexAlpha, rgb, hsl, oklch of cmyk zijn +@msg Copied the color as {text} Kleur gekopieerd als {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` moet een hexkleur (#rgb, #rgba, #rrggbb of #rrggbbaa) of een CSS-kleur rgb(), hsl() of oklch() van ten hoogste 48 tekens zijn @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 156d2c6aba..65e18346b3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -438,6 +438,14 @@ Show Hex Field Pokaż pole hex Hex or CSS color Kolor hex lub CSS Parse Color Analizuj kolor + Format Color Formatuj kolor + Copy Color As Kopiuj kolor jako + Hex Hex + Hex with Alpha Hex z alfą + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Wartości CMYK Stroke Color Kolor obrysu Fill Gradient Gradient wypełnienia Stroke Gradient Gradient obrysu @@ -4853,6 +4861,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue @msg `sliders` must be none or oklch `sliders` musi mieć wartość none lub oklch @msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` musi mieć wartość hex, hexAlpha, rgb, hsl, oklch lub cmyk +@msg Copied the color as {text} Skopiowano kolor jako {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musi być kolorem hex (#rgb, #rgba, #rrggbb lub #rrggbbaa) albo kolorem CSS rgb(), hsl() lub oklch() o długości najwyżej 48 znaków @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 171f408e4f..503d4b57cc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1989,6 +1989,14 @@ antiAlias Sharp Nítido Show Hex Field Mostrar Campo Hex Hex or CSS color Cor hex ou CSS Parse Color Interpretar Cor + Format Color Formatar Cor + Copy Color As Copiar Cor Como + Hex Hex + Hex with Alpha Hex com Alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Valores CMYK Opacity & Mask Define Knockout Shape Opacidade e Máscara Definem Forma de Isolamento Opacity Mask Máscara de Opacidade Opacity Mask Info Informações da Máscara de Opacidade @@ -6323,6 +6331,8 @@ mark-style Japanese Japonesas @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue @msg `sliders` must be none or oklch `sliders` deve ser none ou oklch @msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` deve ser hex, hexAlpha, rgb, hsl, oklch ou cmyk +@msg Copied the color as {text} Cor copiada como {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve ser uma cor hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou uma cor CSS rgb(), hsl() ou oklch() de no máximo 48 caracteres @msg the image can't be read as a texture a imagem não pode ser lida como textura diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e49d353f62..768eddcb00 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2464,6 +2464,14 @@ file-filter Templates Шаблоны Show Hex Field Показать поле hex Hex or CSS color Цвет hex или CSS Parse Color Разобрать цвет + Format Color Форматировать цвет + Copy Color As Копировать цвет как + Hex Hex + Hex with Alpha Hex с альфа-каналом + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Значения CMYK Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания Opacity Mask Непрозрачная маска Opacity Mask Info Сведения о непрозрачной маске @@ -4759,6 +4767,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue @msg `sliders` must be none or oklch `sliders` должен быть none или oklch @msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` должен быть hex, hexAlpha, rgb, hsl, oklch или cmyk +@msg Copied the color as {text} Цвет скопирован как {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` должно быть цветом hex (#rgb, #rgba, #rrggbb или #rrggbbaa) или цветом CSS rgb(), hsl() или oklch() длиной не более 48 символов @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 6db42ffbfb..b9abeb0927 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2376,6 +2376,14 @@ font-technology Variable Variabla Show Hex Field Visa hexfält Hex or CSS color Hex- eller CSS-färg Parse Color Tolka färg + Format Color Formatera färg + Copy Color As Kopiera färg som + Hex Hex + Hex with Alpha Hex med alfa + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK-värden Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform Opacity Mask Opacitetsmask Opacity Mask Info Info om opacitetsmask @@ -6348,6 +6356,8 @@ theme Appearance Utseende @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue @msg `sliders` must be none or oklch `sliders` måste vara none eller oklch @msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` måste vara hex, hexAlpha, rgb, hsl, oklch eller cmyk +@msg Copied the color as {text} Kopierade färgen som {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` måste vara en hexfärg (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-färg rgb(), hsl() eller oklch() på högst 48 tecken @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 37b617d12d..9340b61f81 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -475,6 +475,27 @@ fn color_wheel_opacity_strings_are_in_complete_catalogs() { } } +/// The Color Wheel panel's Copy Color As, its status message and the error of `color.format`. +#[test] +fn copy_color_as_strings_are_in_complete_catalogs() { + let labels = ["Copy Color As", "Hex", "Hex with Alpha", "CSS rgb()", "CSS hsl()", "CSS oklch()", "CMYK Values", "Format Color"]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in labels { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let literals = message_literals(); + let notation = "`notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk"; + assert!(literals.contains(notation), "{notation}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, notation), notation, "{code}"); + let copied = "Copied the color as rgb(51 102 153 / 50%)"; + let shown = message(lang, copied); + assert!(shown != copied && shown.contains("rgb(51 102 153 / 50%)"), "{code}: {shown}"); + } +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index dd3e771a76..b1342e37d0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2215,6 +2215,14 @@ font-technology Variable Değişken Show Hex Field Hex Alanını Göster Hex or CSS color Hex veya CSS rengi Parse Color Rengi Ayrıştır + Format Color Rengi Biçimlendir + Copy Color As Rengi Farklı Biçimde Kopyala + Hex Hex + Hex with Alpha Alfalı Hex + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK Değerleri Opacity & Mask Define Knockout Shape Opaklık ve Maske Tanımlama Nakavt Şekli Opacity Mask Opaklık Maskesi Opacity Mask Info Opaklık Maskesi Bilgisi @@ -4470,6 +4478,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır @msg `sliders` must be none or oklch `sliders` none veya oklch olmalıdır @msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` hex, hexAlpha, rgb, hsl, oklch veya cmyk olmalıdır +@msg Copied the color as {text} Renk şu biçimde kopyalandı: {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` bir hex rengi (#rgb, #rgba, #rrggbb veya #rrggbbaa) ya da en fazla 48 karakterlik bir CSS rgb(), hsl() veya oklch() rengi olmalıdır @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b84fe99f60..bf6c7dcf7f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2467,6 +2467,14 @@ file-filter Templates Шаблони Show Hex Field Показати поле hex Hex or CSS color Колір hex або CSS Parse Color Розібрати колір + Format Color Форматувати колір + Copy Color As Копіювати колір як + Hex Hex + Hex with Alpha Hex з альфа-каналом + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Значення CMYK Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування Opacity Mask Маска непрозорості Opacity Mask Info Відомості про маску непрозорості @@ -4747,6 +4755,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue @msg `sliders` must be none or oklch `sliders` має бути none або oklch @msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` має бути hex, hexAlpha, rgb, hsl, oklch або cmyk +@msg Copied the color as {text} Колір скопійовано як {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` має бути кольором hex (#rgb, #rgba, #rrggbb або #rrggbbaa) або кольором CSS rgb(), hsl() або oklch() довжиною не більше 48 символів @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 34c0991600..1a748a1438 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2739,6 +2739,14 @@ digits Hindi Hindi Show Hex Field Hiện trường hex Hex or CSS color Màu hex hoặc CSS Parse Color Phân tích màu + Format Color Định dạng màu + Copy Color As Sao chép màu dưới dạng + Hex Hex + Hex with Alpha Hex có alpha + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values Giá trị CMYK Opacity & Mask Define Knockout Shape Độ mờ & Mặt nạ xác định hình dạng Knockout Opacity Mask Mặt nạ độ mờ Opacity Mask Info Thông tin mặt nạ độ mờ @@ -4757,6 +4765,8 @@ theme Appearance Giao diện @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue @msg `sliders` must be none or oklch `sliders` phải là none hoặc oklch @msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` phải là hex, hexAlpha, rgb, hsl, oklch hoặc cmyk +@msg Copied the color as {text} Đã sao chép màu dưới dạng {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` phải là màu hex (#rgb, #rgba, #rrggbb hoặc #rrggbbaa) hoặc màu CSS rgb(), hsl() hoặc oklch() dài tối đa 48 ký tự @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index dead5e5573..bd6a4cdbd0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2328,6 +2328,14 @@ file-filter Templates 模板 Show Hex Field 显示十六进制字段 Hex or CSS color 十六进制或 CSS 颜色 Parse Color 解析颜色 + Format Color 格式化颜色 + Copy Color As 将颜色复制为 + Hex 十六进制 + Hex with Alpha 十六进制 (含 Alpha) + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 值 Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状 Opacity Mask 不透明度蒙版 Opacity Mask Info 不透明度蒙版信息 @@ -4860,6 +4868,8 @@ imageTrace Outline 轮廓 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue @msg `sliders` must be none or oklch `sliders` 必须是 none 或 oklch @msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` 必须是 hex、hexAlpha、rgb、hsl、oklch 或 cmyk +@msg Copied the color as {text} 已将颜色复制为 {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必须是十六进制颜色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超过 48 个字符的 CSS rgb()、hsl() 或 oklch() 颜色 @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6152ca7220..442d2364f7 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2486,6 +2486,8 @@ file-filter Templates 範本 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue @msg `sliders` must be none or oklch `sliders` 必須是 none 或 oklch @msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 +@msg `notation` must be hex, hexAlpha, rgb, hsl, oklch or cmyk `notation` 必須是 hex、hexAlpha、rgb、hsl、oklch 或 cmyk +@msg Copied the color as {text} 已將顏色複製為 {text} @msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必須是十六進位顏色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超過 48 個字元的 CSS rgb()、hsl() 或 oklch() 顏色 @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @@ -3601,6 +3603,14 @@ liquify-list-end {0}, {1} {0}和{1} Show Hex Field 顯示十六進位欄位 Hex or CSS color 十六進位或 CSS 顏色 Parse Color 剖析顏色 + Format Color 格式化顏色 + Copy Color As 將顏色複製為 + Hex Hex + Hex with Alpha Hex (含 Alpha) + CSS rgb() CSS rgb() + CSS hsl() CSS hsl() + CSS oklch() CSS oklch() + CMYK Values CMYK 值 Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀 Opacity Mask 不透明度遮色片 Opacity Mask Info 不透明度遮色片資訊 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 267834ab4f..1d03f9c35c 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -784,6 +784,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_copy; +#[cfg(test)] mod tests_color_wheel_hex; #[cfg(test)] mod tests_color_wheel_opacity; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index ff6b8a1b4d..e5c7eaecca 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -212,7 +212,7 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S } /// The panel menu: Wheel View and Box View, Box Channel while the box shows, OKLCH Sliders, Show -/// Opacity and Show Hex Field. +/// Opacity, Show Hex Field and Copy Color As. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let set = app.ui.color_wheel.clone(); for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] { @@ -246,6 +246,54 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Show Hex Field"), true, set.hex_field) { command(app, &json!({ "hexField": !set.hex_field })).ok(); } + ui.separator(); + let has_color = wheel_target(app, ui).color().is_some(); + ui.add_enabled_ui(has_color, |ui| { + ui.menu_button(format!(" {}", tl!("Copy Color As")), |ui| copy_menu(app, ui)); + }); +} + +/// The items of Copy Color As. +pub(crate) fn copy_menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let notations = [ + (tl!("Hex"), "hex"), + (tl!("Hex with Alpha"), "hexAlpha"), + (tl!("CSS rgb()"), "rgb"), + (tl!("CSS hsl()"), "hsl"), + (tl!("CSS oklch()"), "oklch"), + (tl!("CMYK Values"), "cmyk"), + ]; + for (label, notation) in notations { + let clicked = if notation == "oklch" { + widgets::menu_item_hint(ui, label, cms::active().rgb_is_srgb(), false, tl!("OKLCH needs sRGB as the working RGB space")) + } else { + menu_item(ui, label, true, false) + }; + if clicked { + copy_color_as(app, ui, notation); + } + } +} + +/// Copy Color As: put `color.format`'s text in `notation` of the color the panel shows on the +/// clipboard, with the opacity of what the row of Show Opacity edits when it has one, and say in +/// the status bar what was copied. Does nothing without a solid color. +pub(crate) fn copy_color_as(app: &mut VectorcraftApp, ui: &Ui, notation: &str) { + let tgt = wheel_target(app, ui); + let Some(color) = tgt.color() else { return }; + let (o, live) = shown_opacity(app, &tgt); + let mut p = json!({ "color": color_json(&color), "notation": notation }); + if live { + p["opacity"] = json!(f64::from(o.clamp(0.0, 1.0)) * 100.0); + } + match app.run("color.format", p) { + Ok(r) => { + let text = r["text"].as_str().unwrap_or_default().to_string(); + ui.ctx().copy_text(text.clone()); + app.status(format!("Copied the color as {text}")); + } + Err(e) => app.status(e), + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, diff --git a/crates/ui-egui/src/panels/tests_color_wheel_copy.rs b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs new file mode 100644 index 0000000000..d80bb191d8 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_copy.rs @@ -0,0 +1,175 @@ +//! The Color Wheel panel's Copy Color As: the text each item puts on the clipboard, the opacity it +//! carries, the status bar message, and that `color.parse` reads each text back. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use vectorcraft_color::cms; +use vectorcraft_engine::Session; + +use super::color_wheel::{copy_color_as, copy_menu, menu}; +use crate::VectorcraftApp; + +/// A harness that draws `draw` with the app's fonts installed. +fn harness(app: VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut egui::Ui)) -> Harness<'static, VectorcraftApp> { + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + draw(app, ui); + }, + app, + ); + h.run_steps(3); + h +} + +/// An app with a selected rectangle filled with #336699 at `opacity` %. +fn app(opacity: f64) -> 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": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#336699", "opacity": opacity})).unwrap(); + app +} + +/// The texts Copy Color As › `notation` puts on the clipboard in one frame. +fn copy(app: &mut VectorcraftApp, notation: &str) -> Vec { + let ctx = egui::Context::default(); + let mut out = ctx.run_ui(Default::default(), |ui| copy_color_as(app, ui, notation)); + out.textures_delta.clear(); + out.platform_output.commands.iter().filter_map(|c| if let egui::OutputCommand::CopyText(t) = c { Some(t.clone()) } else { None }).collect() +} + +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// Copy Color As › CSS rgb() puts CSS Color 4's space-separated form on the clipboard, with the +/// opacity after a slash, and says what it copied; the document does not change. +#[test] +fn css_rgb_copies_the_color_and_the_opacity() { + let mut app = app(50.0); + let before = undo_count(&app); + assert_eq!(copy(&mut app, "rgb"), ["rgb(51 102 153 / 50%)"]); + assert_eq!(app.ui.status, "Copied the color as rgb(51 102 153 / 50%)"); + assert_eq!(undo_count(&app), before, "copying records no undo step"); +} + +/// Hex and CMYK Values never carry the opacity; Hex with Alpha always does, as `ff` at 100 %; CSS +/// adds it only under 100 %. +#[test] +fn each_item_writes_its_notation() { + let mut half = app(50.0); + assert_eq!(copy(&mut half, "hex"), ["#336699"]); + assert_eq!(copy(&mut half, "hexAlpha"), ["#33669980"]); + assert_eq!(copy(&mut half, "hsl"), ["hsl(210 50% 40% / 50%)"]); + let oklch = copy(&mut half, "oklch"); + assert!(oklch[0].starts_with("oklch(") && oklch[0].ends_with(" / 50%)"), "{oklch:?}"); + let mut full = app(100.0); + assert_eq!(copy(&mut full, "hexAlpha"), ["#336699ff"]); + assert_eq!(copy(&mut full, "rgb"), ["rgb(51 102 153)"]); + let cmyk = copy(&mut full, "cmyk"); + assert_eq!(copy(&mut half, "cmyk"), cmyk, "CMYK Values leaves the opacity out"); + // The working CMYK numbers through the color settings, as color.convert gives them. + let r = full.run("color.convert", json!({"color": "#336699", "to": "cmyk"})).unwrap(); + let pct: Vec = r["values"].as_array().unwrap().iter().map(|v| (v.as_f64().unwrap() * 100.0).round() + 0.0).collect(); + assert_eq!(cmyk, [format!("C={} M={} Y={} K={}", pct[0], pct[1], pct[2], pct[3])]); +} + +/// A CMYK fill copies its own CMYK values. +#[test] +fn a_cmyk_fill_copies_its_own_values() { + let mut app = app(100.0); + app.run("paint.setFill", json!({"color": {"c": 10, "m": 20, "y": 30, "k": 0}})).unwrap(); + assert_eq!(copy(&mut app, "cmyk"), ["C=10 M=20 Y=30 K=0"]); +} + +/// `color.parse` reads every copied text but CMYK Values back to the color the hex field shows, +/// and the alpha to the fill's opacity. +#[test] +fn color_parse_reads_each_copied_text_back() { + let mut app = app(25.0); + for notation in ["hex", "hexAlpha", "rgb", "hsl", "oklch"] { + let text = copy(&mut app, notation).pop().unwrap(); + let r = app.run("color.parse", json!({"text": text})).unwrap(); + assert_eq!(r["hex"], "#336699", "{notation}: {text}"); + let opacity = r["opacity"].as_f64(); + match notation { + "hex" => assert_eq!(opacity, None, "{text}"), + // 64 of 255. + "hexAlpha" => assert_eq!(opacity, Some(25.1), "{text}"), + _ => assert_eq!(opacity, Some(25.0), "{text}"), + } + } +} + +/// With nothing selected the panel shows the color for new art, which has no opacity of its own: +/// the copied text carries none. +#[test] +fn with_nothing_selected_the_color_for_new_art_is_copied_without_an_opacity() { + let mut app = app(50.0); + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": "#336699"})).unwrap(); + assert_eq!(copy(&mut app, "hexAlpha"), ["#336699ff"]); + assert_eq!(copy(&mut app, "rgb"), ["rgb(51 102 153)"]); +} + +/// Without a solid color (a fill of None) nothing is copied. +#[test] +fn nothing_is_copied_without_a_solid_color() { + let mut app = app(100.0); + app.run("paint.setFill", json!({"none": true})).unwrap(); + app.ui.status.clear(); + assert!(copy(&mut app, "hex").is_empty()); + assert_eq!(app.ui.status, ""); +} + +/// Panel menu › Copy Color As is gray without a solid color and available with one. +#[test] +fn copy_color_as_is_gray_without_a_solid_color() { + let h = harness(app(100.0), menu); + assert!(!h.get_by_label(" Copy Color As").accesskit_node().is_disabled()); + let mut none = app(100.0); + none.run("paint.setFill", json!({"none": true})).unwrap(); + let h = harness(none, menu); + assert!(h.get_by_label(" Copy Color As").accesskit_node().is_disabled()); +} + +/// While the working RGB space is not sRGB, Copy Color As › CSS oklch() is gray, the other items are +/// not, and copying as oklch() puts the error in the status bar and nothing on the clipboard. +#[test] +fn css_oklch_is_gray_while_the_working_space_is_not_srgb() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_COPY_P3"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel_copy::css_oklch_is_gray_while_the_working_space_is_not_srgb", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated working space test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let h = harness(app(100.0), copy_menu); + assert!(!h.get_by_label(" CSS oklch()").accesskit_node().is_disabled(), "sRGB"); + let mut app = app(100.0); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert!(copy(&mut app, "oklch").is_empty()); + assert!(app.ui.status.ends_with("OKLCH needs sRGB as the working RGB space"), "{}", app.ui.status); + let h = harness(app, copy_menu); + assert!(h.get_by_label(" CSS oklch()").accesskit_node().is_disabled()); + for label in [" Hex", " Hex with Alpha", " CSS rgb()", " CSS hsl()", " CMYK Values"] { + assert!(!h.get_by_label(label).accesskit_node().is_disabled(), "{label}"); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 80a887ab68..1dbecbb65c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -689,6 +689,23 @@ saturation and lightness are so large that a channel overflows to an infinity is as a percentage, or `null` when the text gives none. Any other text is an error. The color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`. +`color.format {"color": "#336699", "opacity": 50, "notation": "rgb"}` answers `{"text": "rgb(51 102 153 / 50%)"}`. +`notation` is `hex` (`#336699`), `hexAlpha` (`#33669980`, and `#336699ff` at 100 % or without `opacity`), `rgb`, `hsl` +(`hsl(210 50% 40% / 50%)`), `oklch` (`oklch(49.93% 0.0987 250.43 / 50%)`) or `cmyk` (`C=87 M=61 Y=19 K=0` with the +default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity is under 100; +`hex` and `cmyk` leave the opacity out. Every notation but `cmyk` writes the working RGB numbers, the same numbers +the Color panel's hex field shows, with lowercase hex digits; `oklch` is an error while the working RGB space is not +sRGB. `hsl()` and `oklch()` give their numbers to two decimal places (chroma to four), and `oklch()` takes up to two +more where fewer would read back to another color. `cmyk` is the color in the working CMYK space +through the color settings, written as a new swatch is named; a CMYK color keeps its own values. `color.parse` reads +every notation but `cmyk` back to the same `#rrggbb`. `opacity` is 0 to 100, and any other value, or another +`notation`, is an error. + +The Color Wheel panel menu's Copy Color As puts the panel's color on the clipboard as Hex, Hex with Alpha, CSS +rgb(), CSS hsl(), CSS oklch() or CMYK Values, the six `color.format` notations, with the opacity that Show Opacity +edits when it has one (whether or not that row shows), and the status bar shows what was copied. CSS oklch() is gray +while the working RGB space is not sRGB, and Copy Color As is gray without a solid color. + 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 portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3ea05ecde0..696ab895e5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1645,7 +1645,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. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`), and `color.parse` reads every form but the CMYK values back to the same color. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.rs`. Scores and estimates are unchanged. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. The item is gray, and `ui.colorWheel` answers an error, while the working RGB space is not sRGB. `color.convert {to: "oklch"}` answers the same L, C and H. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **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"). From 727ef739e756f86dee1187231d9029f202a56330 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 06:48:37 -0800 Subject: [PATCH 003/153] Color Wheel: the progress line says where the alpha and oklch() apply - The Show Hex Field text says a typed alpha sets the opacity only where the Show Opacity row is not gray, and that oklch() is taken only while the working RGB space is sRGB; Copy Color As writes oklch() under the same condition. - color_format_writes_every_css_form_through_the_intent compares the hex with the absolute colorimetric RGB of the cyan, so a formatter that used another intent fails it. --- crates/engine/tests/color_settings.rs | 7 +++++-- docs/target-app-parity.md | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 6bd0a9d66f..a7ae09e5ba 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1066,8 +1066,9 @@ fn color_format_writes_every_css_form_through_the_intent() { let icc = cms::register_icc(&cms::icc_bytes(cms::GENERIC_CMYK).unwrap(), Some("Format Intent CMYK".into())).unwrap().name; s.execute("edit.colorSettings", &json!({"rgb": cms::SRGB, "cmyk": icc, "intent": "absolute"})).unwrap(); let cyan = json!({"c": 100, "m": 0, "y": 0, "k": 0}); - let intents_differ = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8) - != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); + let absolute = cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::AbsoluteColorimetric).map(|v| (v * 255.0).round() as u8); + let intents_differ = + absolute != cms::active().cmyk_to_rgb([1.0, 0.0, 0.0, 0.0], cms::Intent::RelativeColorimetric).map(|v| (v * 255.0).round() as u8); // Collected as results, so that a failure still restores the process-wide settings first. let mut read_back = vec![]; for notation in ["hex", "rgb", "hsl", "oklch"] { @@ -1080,6 +1081,8 @@ fn color_format_writes_every_css_form_through_the_intent() { assert!(wide.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{wide:?}"); assert!(intents_differ, "absolute and relative colorimetric give cyan the same RGB"); let hex = read_back[0].1.clone().unwrap(); + let [r, g, b] = absolute; + assert_eq!(hex, format!("#{r:02x}{g:02x}{b:02x}"), "hex is the absolute colorimetric RGB"); for (notation, text, back) in read_back { assert_eq!(back, Ok(json!(hex)), "{notation}: {text:?}"); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 696ab895e5..ef1178e3b8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1645,7 +1645,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. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`), and `color.parse` reads every form but the CMYK values back to the same color. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.rs`. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity where that row is not gray (where it is gray, only the color is applied). `oklch()` is taken only while the working RGB space is sRGB. `color.parse {text}` answers the color, its hex and the alpha. VectorCraft's own Copy Color As in the same menu puts the color on the clipboard as hex, hex with an alpha, CSS `rgb()`, `hsl()` or `oklch()`, or its CMYK values through the color settings (`color.format {color, opacity?, notation}`; `oklch()` only while the working RGB space is sRGB), and `color.parse` reads every form but the CMYK values back to the same color. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` and the `format_` tests in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs` and `tests_color_wheel_copy.rs`. Scores and estimates are unchanged. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. The item is gray, and `ui.colorWheel` answers an error, while the working RGB space is not sRGB. `color.convert {to: "oklch"}` answers the same L, C and H. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **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"). From b54ff2d9db3c0c12f3fd5bbab40b94d883193fdd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:15:12 -0800 Subject: [PATCH 004/153] i18n: French row takes a no-break space before the colon --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6d6e8448e3..122c25c51f 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6707,7 +6707,7 @@ axis Y Axis Axe Y @msg `opacity` must be a number `opacity` doit être un nombre @msg `opacity` must be a number from 0 to 100 `opacity` doit être un nombre compris entre 0 et 100 @msg `opacity` must be true or false `opacity` doit valoir true ou false -@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect @msg an object selected in a symbol instance has no fill or stroke opacity of its own un objet sélectionné dans une occurrence de symbole n’a pas d’opacité de fond ou de contour propre @msg no target has that fill or stroke to take the opacity aucune cible n’a ce fond ou ce contour pour recevoir l’opacité @msg `type` must be "path" or "compound" `type` doit valoir "path" ou "compound" From 9a85690da0c7e3733e910da60e15361d3dbd5021 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 23:59:28 -0800 Subject: [PATCH 005/153] Color: color.format docs say the opacity suffix follows the rounded percentage The CSS forms add ` / opacity%` only when the opacity, rounded to two decimal places, is under 100, so 99.999 writes no suffix. The color.format help and docs/mcp.md now say so. --- 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 7783e46514..2740b1d27c 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -150,7 +150,7 @@ pub fn specs() -> Vec { "Format Color", [], None, - "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity is under 100, hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", always, format_color ), diff --git a/docs/mcp.md b/docs/mcp.md index 6eae5c3b6f..9222ae8f5b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -730,7 +730,7 @@ color parameters of the other commands still refuse `#rrggbbaa` and `#rgba`. `color.format {"color": "#336699", "opacity": 50, "notation": "rgb"}` answers `{"text": "rgb(51 102 153 / 50%)"}`. `notation` is `hex` (`#336699`), `hexAlpha` (`#33669980`, and `#336699ff` at 100 % or without `opacity`), `rgb`, `hsl` (`hsl(210 50% 40% / 50%)`), `oklch` (`oklch(49.93% 0.0987 250.43 / 50%)`) or `cmyk` (`C=87 M=61 Y=19 K=0` with the -default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity is under 100; +default color settings). The CSS forms are space-separated and add ` / opacity%` when the opacity, rounded to two decimal places, is under 100 (`99.999` writes no suffix); `hex` and `cmyk` leave the opacity out. Every notation but `cmyk` writes the working RGB numbers, the same numbers the Color panel's hex field shows, with lowercase hex digits; `oklch` is an error while the working RGB space is not sRGB. `hsl()` and `oklch()` give their numbers to two decimal places (chroma to four), and `oklch()` takes up to two From 8c56faed9ec3a8d57a181385c0d90733131e2e2d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 12:26:21 -0800 Subject: [PATCH 006/153] Color: color.format help gives the extra OKLCH decimal places The help for color.format now says oklch() takes up to two more decimal places where fewer would read back to another color, as docs/mcp.md does. --- crates/engine/src/cmd/colorcmds.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 2740b1d27c..6d658241eb 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -150,7 +150,7 @@ pub fn specs() -> Vec { "Format Color", [], None, - "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four); cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", + "{color (#rrggbbaa and #rgba are refused), opacity?: 0..100 (100), notation: \"hex\"|\"hexAlpha\"|\"rgb\"|\"hsl\"|\"oklch\"|\"cmyk\"} the color as text → {text}: hex is #rrggbb and hexAlpha #rrggbbaa (ff at 100) of the working RGB numbers, the same numbers the Color panel's hex field shows, in lowercase; rgb, hsl and oklch are CSS Color 4's rgb(), hsl() and oklch() of the same numbers (https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), each in the space-separated form with ` / opacity%` added when the opacity rounded to two decimal places is under 100 (99.999 writes no suffix), hsl() and oklch() to two decimal places (chroma to four), and oklch() takes up to two more where fewer would read back to another color; cmyk is \"C=0 M=50 Y=100 K=0\", as a new swatch is named, of the color in the working CMYK space through the color settings (a CMYK color keeps its own values); hex and cmyk leave the opacity out. color.parse reads every notation but cmyk back to the same #rrggbb; oklch is an error while the working RGB space is not sRGB", always, format_color ), From 4e7ab22b9fc9631fb55d28847ebdc24fd253bcec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 19:16:52 -0800 Subject: [PATCH 007/153] Color Wheel: the panel menu lists Show Opacity once --- crates/ui-egui/src/panels/color_wheel.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index daee73d390..96a3e81963 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -385,9 +385,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } }); }); - if menu_item(ui, tl!("Show Opacity"), true, set.opacity) { - command(app, &json!({ "opacity": !set.opacity })).ok(); - } if menu_item(ui, tl!("Show Color Vision Preview"), true, set.vision) { command(app, &json!({ "vision": !set.vision })).ok(); } From d43d3c0e3af4dd2c9387e5916d1d653e4b790b14 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 20 Nov 2026 12:17:09 +0500 Subject: [PATCH 008/153] Smart Guides: objects past the anchor budget keep their edges and centre (#8531) Targets::collect_inner stopped visiting objects once its 20,000-anchor budget was spent, so in a document with more anchors the objects visited last (the topmost, newest ones) gave no edges or centre either, and a ruler guide, a move, a scale or a drawn point did not snap to them. The anchor budget now caps only the anchors and the segment budget only the segments; every visible object gives its bounds, up to a separate cap of 100,000 objects. --- crates/tools/src/guides/targets.rs | 28 ++++++++++++++++++++-------- crates/tools/src/guides/tests.rs | 23 +++++++++++++++++++++++ crates/tools/src/lib.rs | 15 +++++++++++++++ crates/tools/src/rulerguide/tests.rs | 15 +++++++++++++++ docs/roadmap.md | 5 +++-- docs/target-app-parity.md | 4 +++- docs/ui-parity.md | 5 +++-- 7 files changed, 82 insertions(+), 13 deletions(-) diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 94344aab2c..ec36ef3f46 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -66,6 +66,11 @@ pub struct Targets { /// How many anchors, and how many segments, the targets gather at most. pub(super) const BUDGET: usize = 20_000; +/// How many objects give their edges and centre as targets at most: every object of the 50,000 +/// path performance document, while on a document of millions gathering them stays bounded +/// (about 35 MB and some tens of milliseconds at the cap) (#8531). +pub(super) const BOUNDS_BUDGET: usize = 100_000; + /// What [`Targets::collect_inner`] gathers from each path besides its anchors and bounds. #[derive(Clone, Copy, PartialEq)] enum Gather { @@ -628,9 +633,12 @@ impl Targets { add_rect(&mut t, doc.setup.bleed_rect(ab.rect), Kind::Bleed); } } - let (mut budget, mut segment_budget) = (BUDGET, BUDGET); + let (mut budget, mut segment_budget, mut bounds_budget) = (BUDGET, BUDGET, BOUNDS_BUDGET); walk_but(&doc.layers, &exclude.iter().copied().collect(), &mut |n| { - if budget == 0 || n.is_container() || !n.visible { + // The anchors and segments running out does not end the walk: the objects visited + // after that (the topmost, newest ones) still give their edges and centre (#8531), + // up to their own, larger budget. + if bounds_budget == 0 || n.is_container() || !n.visible { return; } let Some(b) = n.geometric_bounds() else { return }; @@ -641,13 +649,16 @@ impl Targets { return; } if let NodeKind::Path { path, .. } = &n.kind { - for (_, _, a) in path.anchors() { - if gather == Gather::Drawing { - t.push_anchor(a.p); - } else { - t.points.push((a.p, Kind::Anchor)); + // A path begun within the budget gives all its anchors. + if budget > 0 { + for (_, _, a) in path.anchors() { + if gather == Gather::Drawing { + t.push_anchor(a.p); + } else { + t.points.push((a.p, Kind::Anchor)); + } + budget = budget.saturating_sub(1); } - budget = budget.saturating_sub(1); } if gather != Gather::Bounds { for sp in &path.subpaths { @@ -656,6 +667,7 @@ impl Targets { } } add_rect(&mut t, b, Kind::Edge); + bounds_budget -= 1; }); t.index() } diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 0406ea5f77..071398f959 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -11,6 +11,29 @@ fn artboard_bleed_is_a_target() { assert_eq!(t.snap_point(Point::new(512.0, 300.0), 4.0).0.x, 510.0); } +/// #8531: once the anchors gathered reach their budget, the objects after them still give their +/// edges and centres, for a ruler guide, a moved selection and a drawn point. Their anchors stay +/// capped. +#[test] +fn objects_past_the_anchor_budget_keep_their_edges_and_centre() { + let (d, rect) = doc_with_rect_over_many_anchors(); + let t = Targets::collect(&d, &[], None); + assert_eq!(t.points.iter().filter(|(_, k)| *k == Kind::Anchor).count(), targets::BUDGET); + assert_eq!(t.snap_guide(false, 301.0, 4.0).0, 300.0, "the bottom edge"); + assert_eq!(t.snap_guide(true, 398.0, 4.0).0, 400.0, "the right edge"); + let (p, ov) = t.snap_point(Point::new(302.0, 201.0), 4.0); + assert_eq!(p, Point::new(300.0, 200.0)); + assert!(matches!(&ov[0], Overlay::Label { text, .. } if text == "center"), "{ov:?}"); + // A box moved next to it lines up with its top edge. + let other = Targets::collect(&d, &[rect], None); + let (s, pt) = (Selection::default(), paint()); + let moving = Targets::for_move(&cx(&d, &s, &pt), &[]); + assert_eq!(moving.snap_rect(Rect::new(420.0, 102.0, 450.0, 130.0), 4.0).0.y, -2.0); + assert_eq!(other.snap_rect(Rect::new(420.0, 102.0, 450.0, 130.0), 4.0).0.y, 0.0, "without the rectangle, nothing near"); + let drawn = Targets::for_drawing(&d, &[], None, None); + assert_eq!(drawn.snap_point(Point::new(450.0, 298.0), 4.0).0.y, 300.0); +} + #[test] fn snaps_to_anchor_and_alignment() { let (d, _) = doc_with_rect(); diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 688f295478..79fc429b89 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -468,6 +468,21 @@ pub(crate) mod testutil { (d, id) } + /// #8531: 21 polygons of 1000 sides at (40, 30)–(80, 70), 21,000 anchors (more than the + /// snap targets gather), drawn first, and over them a rectangle (200, 100)–(400, 300): the + /// document and the rectangle. + pub fn doc_with_rect_over_many_anchors() -> (Document, NodeId) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + for i in 0..21 { + let id = d.alloc_id(); + d.insert(Some(l), i, Node::path(id, shapes::polygon(Point::new(60.0, 50.0), 20.0, 1000, 0.0), Appearance::default_art())).unwrap(); + } + let id = d.alloc_id(); + d.insert(Some(l), 21, Node::path(id, shapes::rectangle(Rect::new(200.0, 100.0, 400.0, 300.0)), Appearance::default_art())).unwrap(); + (d, id) + } + /// A live 100 × 100 rectangle at (100, 100)–(200, 200) with no paint: its centre point /// (Attributes › Show Center) is at (150, 150), and a press in the middle of it hits no art. pub fn doc_with_live_rect() -> (Document, NodeId) { diff --git a/crates/tools/src/rulerguide/tests.rs b/crates/tools/src/rulerguide/tests.rs index b4b7c256d3..5777acca9e 100644 --- a/crates/tools/src/rulerguide/tests.rs +++ b/crates/tools/src/rulerguide/tests.rs @@ -108,6 +108,21 @@ fn a_new_guide_snaps_to_the_art_and_the_artboard() { assert_eq!(drag(true, 320.0), (320.0, None), "nothing within reach"); } +/// #8531: in a document with more anchors than the snap targets gather, a guide dragged out of +/// the top ruler still lands on the edge of the rectangle drawn last, over all of them. +#[test] +fn a_new_guide_snaps_to_the_newest_object_over_many_anchors() { + let (d, _) = doc_with_rect_over_many_anchors(); + let (s, p) = (Selection::default(), paint()); + let c = cx(&d, &s, &p); + let m = Mods::default(); + let mut g = NewGuide::new(&c, false, None); + assert_eq!(g.pointer(&c, &ev(PointerKind::Drag, 300.0, -5.0, m), false), vec![], "still over the ruler"); + let a = g.pointer(&c, &ev(PointerKind::Drag, 300.0, 301.0, m), true); + assert_eq!(a.last(), Some(&Action::Preview("guide.add".into(), json!({"vertical": false, "pos": 300.0}))), "onto the bottom edge: {a:?}"); + assert_eq!(g.pointer(&c, &ev(PointerKind::Up, 300.0, 301.0, m), true), vec![Action::Commit]); +} + /// Preferences › Smart Guides (#394) reach a guide dragged out of a ruler: Snapping /// Tolerance sets how far a target pulls it, Anchor/Path Labels and Measurement Labels what /// shows by it. diff --git a/docs/roadmap.md b/docs/roadmap.md index a518e3a35a..47382c10e5 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-20 · **Change:** minor (M1: 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: M11: 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: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; 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: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected 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: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; 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: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: 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); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; 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: 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: 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-20 · **Change:** minor (M2: Smart Guides: in a document with more than 20,000 anchors, the objects gathered after the anchors run out (the topmost, newest ones) still give their edges and centre as snap targets for ruler guides, moves, scaling and drawing (#8531); scores and estimates unchanged; previously: M1: 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: M11: 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: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; 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: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected 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: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; 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: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: 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); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; 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: 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: 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). > @@ -179,7 +179,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; 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 (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #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); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 | +| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #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); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors every object still gives its edges and centre as Smart Guides targets (#8531) | 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) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; 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; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `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; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | @@ -235,6 +235,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | M2: Smart Guides: in a document with more than 20,000 anchors, the objects gathered after the anchors run out (the topmost, newest ones) still give their edges and centre as snap targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. | | 2026-11-19 | minor | M1: Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | M11: View › 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; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b1d981428a..44e940d1a1 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-20 · **Change:** minor (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: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; 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: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; 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); 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: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected 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: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; 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: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; 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: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: 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); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; 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: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; 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: 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: 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-20 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the objects gathered after the anchors run out (the topmost, newest ones) still give their edges and centre as snap targets for ruler guides, moves, scaling and drawing (#8531); 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: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; 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: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; 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); 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: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected 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: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; 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: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; 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: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: 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); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; 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: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; 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: 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: 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). > @@ -75,6 +75,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Smart Guides: in a document with more than 20,000 anchors, the objects gathered after the anchors run out (the topmost, newest ones) still give their edges and centre as snap targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible around a smaller appearance dot, so the four looks (not targeted, targeted, with an appearance, both) differ (#8711). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | @@ -846,6 +847,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **New ruler guides (G1):** Alt swaps orientation while dragging from either ruler, following the [public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). Preview, snapping and final placement use the current axis. Tool and egui event tests exercise both rulers, modifier changes, cancellation and one-step Undo/Redo; existing-guide Alt-copy and ruler-origin gestures are unchanged. - **Artboard guides with Cmd/Ctrl + ruler drag:** VectorCraft's own option, Preferences › Guides & Grid › Artboard Guides with Cmd/Ctrl + Ruler Drag (`cmdRulerDragArtboardGuides`), off by default. With it on, Cmd/Ctrl held when a drag leaves a ruler makes a guide of the active artboard, and with the Artboard tool a canvas guide; the key is read when the drag starts. The guide is made only where it lies within the active artboard. The documented way to limit a guide to one artboard, dragging it out with the Artboard tool ([Align objects with guides](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/align-graphic-objects-with-guides.html)), is unchanged when the option is off. Tests `rulerguide::tests::a_guide_within_its_artboard_is_made_only_inside_it`, `tests::menucmds::cmd_ruler_drags_make_guides_of_the_active_artboard_when_the_preference_is_on` and `canvas::tests::cmd_ruler_drags_make_artboard_guides_with_the_preference_on`. +- **Smart Guides targets in documents with many anchors (#8531):** every visible object gives its edges and centre as snap targets for a dragged ruler guide, a moved, scaled or drawn object and the other gestures that gather the art's targets, also after the 20,000 anchors and 20,000 path segments they gather have run out (they used to stop with the anchors, so in a document with more anchors the objects visited last, the topmost and newest, gave no targets at all). Edges and centres have their own cap of 100,000 objects. On the 50,000-path document of the deep `vectorcraft-cli perf` run, "smart guide targets in view" went from 1.9 ms to 22.9 ms, gathered once when a gesture begins; the hit test and the per-move rows are unchanged. Tests: `a_new_guide_snaps_to_the_newest_object_over_many_anchors` in `crates/tools/src/rulerguide/tests.rs` and `objects_past_the_anchor_budget_keep_their_edges_and_centre` in `crates/tools/src/guides/tests.rs`. - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions 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. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 911f08d192..5d7f53ed2e 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-20 · **Change:** minor (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) · **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-20 · **Change:** minor (Smart Guides: in a document with more than 20,000 anchors, the objects gathered after the anchors run out (the topmost, newest ones) still give their edges and centre as snap targets for ruler guides, moves, scaling and drawing (#8531); 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) · **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). > @@ -280,7 +280,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| -| Snap to anchors, centres, edges, artboards, bleed and ruler guides with magenta lines | done | `guides.rs` kinds: Anchor, Center, Edge, Artboard, Bleed, Guide | +| Snap to anchors, centres, edges, artboards, bleed and ruler guides with magenta lines | done | `guides.rs` kinds: Anchor, Center, Edge, Artboard, Bleed, Guide; every visible object gives its edges and centre, also once the 20,000 anchors gathered have run out in a heavy document (#8531; up to 100,000 objects) | | Anchor/Path labels ("anchor", "center", "path", "align") | done | | | "intersect" label and snapping to path intersections | partial | #1658 (part of #1602): a point drawn with the Pen, the shape tools or the other drawing tools and an anchor dragged with Direct Selection snap to where paths and ruler guides cross; a moved selection's own anchors and the Width tool don't | | Construction guides at preference angles while drawing | done | #506 | @@ -626,6 +626,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-20 | minor | Smart Guides: in a document with more than 20,000 anchors, the objects gathered after the anchors run out (the topmost, newest ones) still give their edges and centre as snap targets for ruler guides, moves, scaling and drawing (#8531). Scores and estimates unchanged. | | 2026-11-19 | minor | Layers: a target circle whose item is targeted and has an appearance of its own keeps its inner ring visible, with a smaller appearance dot inside it and a gap between them, so not targeted, targeted, with an appearance and both look different, as the target icons in [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) (Targeting items for appearance attributes) do. Before, the dot covered the ring and a targeted item with an appearance looked untargeted, #8711. Scores and estimates unchanged. | | 2026-11-19 | minor | View › 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 until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | | 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | From 3c6b879d443bc9a6786915b55d627a07d53c1685 Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 20 Nov 2026 12:36:30 +0500 Subject: [PATCH 009/153] fix(guides): cap only bounds targets with the bounds budget An object past the bounds budget still gives its anchors and segments. The walk stops only when all three budgets are spent. --- crates/tools/src/guides/targets.rs | 35 ++++++++++++++++++++++++------ crates/tools/src/guides/tests.rs | 8 +++++++ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index ec36ef3f46..06dddbbeaa 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -613,6 +613,24 @@ impl Targets { } fn collect_inner(doc: &Document, exclude: &[NodeId], skip_artboard: Option, visible: Option, gather: Gather) -> Self { + Self::collect_capped(doc, exclude, skip_artboard, visible, gather, BOUNDS_BUDGET) + } + + /// [`Self::collect`] with at most `bounds_budget` objects giving their edges and centre, so a + /// test can spend that budget without a document of [`BOUNDS_BUDGET`] objects. + #[cfg(test)] + pub(super) fn collect_bounds_capped(doc: &Document, bounds_budget: usize) -> Self { + Self::collect_capped(doc, &[], None, None, Gather::Bounds, bounds_budget) + } + + fn collect_capped( + doc: &Document, + exclude: &[NodeId], + skip_artboard: Option, + visible: Option, + gather: Gather, + bounds_budget: usize, + ) -> Self { let mut t = Targets::default(); let add_rect = |t: &mut Targets, r: Rect, kind: Kind| { let c = r.center(); @@ -633,12 +651,13 @@ impl Targets { add_rect(&mut t, doc.setup.bleed_rect(ab.rect), Kind::Bleed); } } - let (mut budget, mut segment_budget, mut bounds_budget) = (BUDGET, BUDGET, BOUNDS_BUDGET); + let (mut budget, mut segment_budget, mut bounds_budget) = (BUDGET, BUDGET, bounds_budget); walk_but(&doc.layers, &exclude.iter().copied().collect(), &mut |n| { - // The anchors and segments running out does not end the walk: the objects visited - // after that (the topmost, newest ones) still give their edges and centre (#8531), - // up to their own, larger budget. - if bounds_budget == 0 || n.is_container() || !n.visible { + // Each budget caps only its own targets: the anchors and segments running out leave + // the objects visited after that (the topmost, newest ones) their edges and centre + // (#8531), and the bounds running out leaves later paths their anchors and segments. + let spent = budget == 0 && segment_budget == 0 && bounds_budget == 0; + if spent || n.is_container() || !n.visible { return; } let Some(b) = n.geometric_bounds() else { return }; @@ -666,8 +685,10 @@ impl Targets { } } } - add_rect(&mut t, b, Kind::Edge); - bounds_budget -= 1; + if bounds_budget > 0 { + add_rect(&mut t, b, Kind::Edge); + bounds_budget -= 1; + } }); t.index() } diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 071398f959..2067062c6f 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -34,6 +34,14 @@ fn objects_past_the_anchor_budget_keep_their_edges_and_centre() { assert_eq!(drawn.snap_point(Point::new(450.0, 298.0), 4.0).0.y, 300.0); } +#[test] +fn objects_past_the_bounds_budget_keep_their_anchors() { + let (d, _) = doc_with_rect(); + let t = Targets::collect_bounds_capped(&d, 0); + assert_eq!(t.snap_point(Point::new(102.0, 99.0), 4.0).0, Point::new(100.0, 100.0), "the corner anchor"); + assert_eq!(t.snap_guide(false, 101.0, 4.0).0, 100.0, "the anchors line up a guide"); +} + #[test] fn snaps_to_anchor_and_alignment() { let (d, _) = doc_with_rect(); From 0d8e8a25a65d93e6105deb84e9fee4baa1e08d2e Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 20 Nov 2026 12:45:18 +0500 Subject: [PATCH 010/153] perf(guides): start a bounds walk with no segment budget A bounds walk gathers no segments, so its unspent segment budget kept the walk measuring every object after its anchors and bounds ran out. --- crates/tools/src/guides/targets.rs | 11 +++++++++-- crates/tools/src/guides/tests.rs | 6 ++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 06dddbbeaa..fdb76832cb 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -73,7 +73,7 @@ pub(super) const BOUNDS_BUDGET: usize = 100_000; /// What [`Targets::collect_inner`] gathers from each path besides its anchors and bounds. #[derive(Clone, Copy, PartialEq)] -enum Gather { +pub(super) enum Gather { /// Nothing more: a moved or resized selection lines up with bounds. Bounds, /// Its segments, which a dragged anchor lands on. @@ -82,6 +82,13 @@ enum Gather { Drawing, } +/// The anchor, segment and bounds budgets a walk starts with. A walk that gathers no segments +/// starts with none to spend, so it stops once its anchors and bounds run out. +pub(super) fn start_budgets(gather: Gather, bounds_budget: usize) -> (usize, usize, usize) { + let segment_budget = if gather == Gather::Bounds { 0 } else { BUDGET }; + (BUDGET, segment_budget, bounds_budget) +} + /// The entries of `sorted` (ascending by `key`) whose key is within `tol` of `v`, found by /// bisection. fn within(sorted: &[T], key: impl Fn(&T) -> f64, v: f64, tol: f64) -> &[T] { @@ -651,7 +658,7 @@ impl Targets { add_rect(&mut t, doc.setup.bleed_rect(ab.rect), Kind::Bleed); } } - let (mut budget, mut segment_budget, mut bounds_budget) = (BUDGET, BUDGET, bounds_budget); + let (mut budget, mut segment_budget, mut bounds_budget) = start_budgets(gather, bounds_budget); walk_but(&doc.layers, &exclude.iter().copied().collect(), &mut |n| { // Each budget caps only its own targets: the anchors and segments running out leave // the objects visited after that (the topmost, newest ones) their edges and centre diff --git a/crates/tools/src/guides/tests.rs b/crates/tools/src/guides/tests.rs index 2067062c6f..656863ce42 100644 --- a/crates/tools/src/guides/tests.rs +++ b/crates/tools/src/guides/tests.rs @@ -34,6 +34,12 @@ fn objects_past_the_anchor_budget_keep_their_edges_and_centre() { assert_eq!(drawn.snap_point(Point::new(450.0, 298.0), 4.0).0.y, 300.0); } +#[test] +fn a_bounds_walk_has_no_segment_budget_to_keep_it_going() { + assert_eq!(super::targets::start_budgets(super::targets::Gather::Bounds, 7), (super::targets::BUDGET, 0, 7)); + assert_eq!(super::targets::start_budgets(super::targets::Gather::Segments, 7).1, super::targets::BUDGET); +} + #[test] fn objects_past_the_bounds_budget_keep_their_anchors() { let (d, _) = doc_with_rect(); From 054d183842916742bc0d490676c7f0745ea3f1d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 21:44:20 -0800 Subject: [PATCH 011/153] 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/153] 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 971997f18cabcfc7eef9633553094686a03b8d8b Mon Sep 17 00:00:00 2001 From: HassanKhan Date: Fri, 20 Nov 2026 22:23:30 +0500 Subject: [PATCH 013/153] docs: state the 100,000-object cap in the roadmap's Smart Guides line (#8531) --- docs/roadmap.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/roadmap.md b/docs/roadmap.md index 8af76b1290..98c0aaa3f4 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -182,7 +182,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (a targeted Layers item with an appearance of its own shows its inner ring around a smaller appearance dot (#8711); path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; 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 (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #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); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors every object still gives its edges and centre as Smart Guides targets (#8531) | 12–18 | +| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #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); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655); in a document with more than 20,000 anchors every object still gives its edges and centre as Smart Guides targets, up to 100,000 objects (#8531) | 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) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; 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; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `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; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | From c2e61ac55e6eb4f6152a90c14930d7885d422e7a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:50:09 -0800 Subject: [PATCH 014/153] 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 015/153] 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 016/153] 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 017/153] 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 018/153] 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 019/153] 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 020/153] 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 021/153] 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 022/153] 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 023/153] 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 43813db855a6be9ff0bede754595cd181d24c0cd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 10:46:44 -0800 Subject: [PATCH 024/153] Scripts: paths, path points and colors for scripts Document.pathItems lists a document's paths and makes empty paths, rectangles, rounded rectangles, ellipses, polygons and stars with the parameter order and defaults of the PathItems help page. A PathItem reads and changes its points, closed state, fill rule, area, length, fill and stroke colors, stroke options and overprint, and translates, rotates and resizes. PathPoints and PathPoint read and set each point's anchor, handles and type. RGBColor, CMYKColor, GrayColor, LabColor and NoColor make colors; a gradient, spot or pattern paint reads as GradientColor, SpotColor or PatternColor. Each change runs an existing command (path.create, the shape.* commands, path.setAnchors, path.close, path.setFillRule, paint.setFill, paint.setStroke, stroke.set, object.setOverprint, object.move, object.rotate, object.scale) inside the run's one undo step, and puts back the selection and the paint for new art. A value that changes nothing runs no command; a bad value throws and changes nothing. path.setAnchors now makes an anchor a corner when it is given `smooth: false`; before, the key was ignored and handles in line made it smooth. --- crates/engine/src/cmd/create.rs | 3 +- crates/engine/src/cmd/path.rs | 2 +- crates/engine/src/script/dom.rs | 22 +- crates/engine/src/script/dom/colors.rs | 154 +++ crates/engine/src/script/dom/paths.rs | 1223 +++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_dom.rs | 8 +- crates/engine/src/tests/script_dom_paths.rs | 602 ++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 39 +- docs/mcp.md | 50 +- docs/target-app-parity.md | 3 +- 11 files changed, 2090 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/script/dom/colors.rs create mode 100644 crates/engine/src/script/dom/paths.rs create mode 100644 crates/engine/src/tests/script_dom_paths.rs diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 0ce38be40b..103eb44f8d 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -850,7 +850,8 @@ pub(crate) fn anchor_from_json(v: &Value, cmd: &str) -> Result { }; let mut anchor = Anchor::with_handles(p, handle("in")?, handle("out")?); match v.get("smooth").filter(|b| !b.is_null()) { - None | Some(Value::Bool(false)) => {} + None => {} + Some(Value::Bool(false)) => anchor.kind = AnchorKind::Corner, Some(Value::Bool(true)) => anchor.kind = AnchorKind::Smooth, Some(_) => return Err(bad(cmd, "anchor `smooth` must be true or false")), } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d32594d92d..d747f34989 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Set Anchors", [], None, - "{id, subpaths: [{anchors: [{x,y,in?,out?}], closed}]} replace a path's geometry", + "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry", has_doc, set_anchors ), diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b986dfcf2d..03b236c0e1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -38,6 +38,9 @@ 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 colors; +mod paths; + /// 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. @@ -91,6 +94,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; pub(super) struct State { coords: Cell, items: RefCell>, + /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. + paths: RefCell>, saving: Cell, } @@ -151,7 +156,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 path point `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 +167,12 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM "Document" => { doc_of(&h, arg(&a, 0), "Document")?; } - "PageItem" => { + "PageItem" | "PathItem" => { item_of(&h, arg(&a, 0))?; } + "PathPoint" => { + paths::this_point(&h, &a)?; + } _ => {} } Err(HostError::Error(message.clone())) @@ -1740,9 +1748,10 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("selection", property(l, doc_selection, doc_set_selection)), + ("pathItems", get(l, paths::doc_path_items)), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); @@ -1809,7 +1818,12 @@ 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().map(|c| class(c, Some("PageItem"), if *c == "PathItem" { paths::path_item_members(l) } else { Vec::new() }, None)), + ); + classes.extend(paths::classes(l)); + classes.extend(colors::classes(l)); + paths::install_enums(realm)?; 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/colors.rs b/crates/engine/src/script/dom/colors.rs new file mode 100644 index 0000000000..40421c5d38 --- /dev/null +++ b/crates/engine/src/script/dom/colors.rs @@ -0,0 +1,154 @@ +//! The color classes of the script object model, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! A color is plain data: `new RGBColor()` gives an object with `typename` and its components, +//! which the script can change, and reading `fillColor` or `strokeColor` gives a new one each time. +//! Components are checked when a color is assigned to an object, and a value out of range throws a +//! `RangeError` with nothing changed. +//! +//! VectorCraft's own rules, which the help pages do not state: components left out count as 0; +//! `new cmykColor()` is the same as `new CMYKColor()`; `LabColor.l` is 0 to 100 and `a` and `b` +//! are -128 to 128. `GrayColor.gray` runs from 0 (black) to 100 (white), as the GrayColor page +//! says. `GradientColor`, `SpotColor` and `PatternColor` can be read from an object but not +//! assigned yet. + +use std::rc::Rc; + +use serde_json::Value; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; + +use super::{Link, current, num, text}; + +/// The classes whose objects can be read from a fill or stroke but not assigned yet. +const LATER: &[&str] = &["GradientColor", "SpotColor", "PatternColor"]; + +/// The components of each color class, with the value `new` gives them. +const CLASSES: &[(&str, &[&str])] = &[ + ("RGBColor", &["red", "green", "blue"]), + ("CMYKColor", &["cyan", "magenta", "yellow", "black"]), + ("GrayColor", &["gray"]), + ("LabColor", &["l", "a", "b"]), + ("NoColor", &[]), + ("GradientColor", &[]), + ("SpotColor", &["tint"]), + ("PatternColor", &[]), +]; + +fn color_object(class: &str, values: &[(&str, f64)]) -> Data { + let mut items = vec![("typename".to_string(), text(class))]; + items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v)))); + Data::Object(items) +} + +/// A component as the script sees it: `v` times `scale`, rounded to 4 decimals. +fn shown(v: f32, scale: f64) -> f64 { + (f64::from(v) * scale * 1e4).round() / 1e4 +} + +/// The color object for a solid color. +fn of_color(c: &Color) -> Data { + match *c { + Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), + Color::Cmyk { c, m, y, k } => color_object( + "CMYKColor", + &[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))], + ), + Color::Gray { k } => color_object("GrayColor", &[("gray", shown(1.0 - k, 100.0))]), + Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]), + } +} + +/// What reading `fillColor` or `strokeColor` gives for `paint`: a new color object, a `SpotColor` +/// with its `tint` for a color linked to a global or spot swatch. +pub(super) fn of_paint(paint: &Paint) -> Data { + match paint { + Paint::None => color_object("NoColor", &[]), + Paint::Solid { swatch: Some(_), tint, .. } => color_object("SpotColor", &[("tint", shown(*tint, 100.0))]), + Paint::Solid { color, .. } => of_color(color), + Paint::Gradient(_) => color_object("GradientColor", &[]), + Paint::Pattern { .. } => color_object("PatternColor", &[]), + } +} + +/// The component `key` of color object `o`, from `min` to `max` (0 when it is left out). +fn component(o: &[(String, Data)], class: &str, key: &str, min: f64, max: f64) -> std::result::Result { + match o.iter().find(|(k, _)| k == key).map(|(_, v)| v) { + None | Some(Data::Undefined) => Ok(0.0), + Some(Data::Number(n)) if n.is_finite() && (min..=max).contains(n) => Ok(*n), + Some(Data::Number(_)) => Err(HostError::Range(format!("{class}.{key} must be from {min} to {max}"))), + Some(_) => Err(HostError::Type(format!("{class}.{key} must be a number"))), + } +} + +#[allow(clippy::cast_possible_truncation)] +fn unit(v: f64, scale: f64) -> f32 { + (v / scale) as f32 +} + +/// The color a script assigned, checked: `None` for a `NoColor`. `what` names the property. +pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result, HostError> { + let Data::Object(o) = d else { return Err(HostError::Type(format!("{what} must be a color object"))) }; + let class = match o.iter().find(|(k, _)| k == "typename").map(|(_, v)| v) { + Some(Data::String(s)) => s.as_str(), + _ => return Err(HostError::Type(format!("{what} must be a color object"))), + }; + let c = |key: &str, min: f64, max: f64| component(o, class, key, min, max); + Ok(Some(match class { + "NoColor" => return Ok(None), + "RGBColor" => { + Color::Rgb { r: unit(c("red", 0.0, 255.0)?, 255.0), g: unit(c("green", 0.0, 255.0)?, 255.0), b: unit(c("blue", 0.0, 255.0)?, 255.0) } + } + "CMYKColor" => Color::Cmyk { + c: unit(c("cyan", 0.0, 100.0)?, 100.0), + m: unit(c("magenta", 0.0, 100.0)?, 100.0), + y: unit(c("yellow", 0.0, 100.0)?, 100.0), + k: unit(c("black", 0.0, 100.0)?, 100.0), + }, + "GrayColor" => Color::Gray { k: unit(100.0 - c("gray", 0.0, 100.0)?, 100.0) }, + "LabColor" => Color::Lab { l: unit(c("l", 0.0, 100.0)?, 1.0), a: unit(c("a", -128.0, 128.0)?, 1.0), b: unit(c("b", -128.0, 128.0)?, 1.0) }, + l if LATER.contains(&l) => return Err(HostError::Error(format!("assigning a {l} is not available yet"))), + _ => return Err(HostError::Type(format!("{what} must be a color object"))), + })) +} + +/// `color` as `paint.setFill` and `paint.setStroke` take it. +pub(super) fn param(color: &Color) -> Value { + serde_json::to_value(color).unwrap_or(Value::Null) +} + +/// The constructors of the color classes, and `cmykColor`. +pub(super) fn classes(link: &Link) -> Vec { + let make = |name: &str, components: &'static [&'static str]| { + let l = link.clone(); + let class = name.to_string(); + let f: HostFunction = Rc::new(move |_| { + current(&l)?.charge_call(64)?; + let zeros: Vec<(&str, f64)> = components.iter().map(|k| (*k, if *k == "tint" { 100.0 } else { 0.0 })).collect(); + Ok(color_object(&class, &zeros)) + }); + f + }; + let mut out: Vec = CLASSES + .iter() + .map(|(name, components)| HostClass { + name: (*name).into(), + parent: None, + members: Vec::new(), + index: None, + construct: Some(make(name, components)), + }) + .collect(); + out.push(HostClass { + name: "cmykColor".into(), + parent: None, + members: Vec::new(), + index: None, + construct: Some(make("CMYKColor", CLASSES[1].1)), + }); + out +} diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs new file mode 100644 index 0000000000..ac643ce370 --- /dev/null +++ b/crates/engine/src/script/dom/paths.rs @@ -0,0 +1,1223 @@ +//! Paths and their points in the script object model, as the help pages +//! , +//! , +//! and +//! describe them. +//! +//! A `PathPoints` object holds its path's handle, and a `PathPoint` the path's handle and the +//! point's index, counted across the path's subpaths in order. Each read looks the path up again. +//! Every change runs one command (`path.setAnchors` for the geometry), inside the run's one undo +//! step, and a change that changes nothing runs no command. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside +//! groups and compound paths included. +//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden +//! or locked layer or group, throws `Cannot edit` with nothing changed. +//! - A path in a compound path or compound shape reads that owner's paint, which the paint +//! commands change in its place. A paint or stroke change leaves the paint for new art, the +//! active proxy and the recent colors as they were. +//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes +//! them all. +//! - `pathItems.add()` makes a path with no points on top of the active layer, painted as new art +//! is. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds +//! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. +//! Removing the last points leaves the path, with no points. +//! - A point whose index is past the end of its path throws `Stale path point`. +//! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole +//! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that +//! says it is not available yet. `rotateAbout` and `scaleAbout` default to +//! `Transformation.CENTER`. +//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and +//! `changeStrokePattern` given as different values throw an error; gradients move with the art, +//! so `changeFillGradients` false throws an error that says it is not available yet. + +use std::rc::Rc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::pattern::pattern_paint; +use vectorcraft_doc::{GraphicStyle, LineCap, LineJoin}; +use vectorcraft_geom::path::{Anchor, AnchorKind, FillRule, PathData, SubPath}; +use vectorcraft_geom::{Point, Rect}; +use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, RunError, host_ref}; +use vectorcraft_tools::params::gradient_params; + +use super::{ + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, + float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, property, + this_doc, typename_of, whole, with_doc, +}; +use crate::{DocState, NodeId, NodeKind}; + +/// The error of a point whose index is past the end of its path. +pub const STALE_POINT: &str = "Stale path point"; +/// The most points `setEntirePath` takes. +pub const MAX_POINTS: usize = 100_000; +/// The most lengths `strokeDashes` takes. +pub const MAX_DASHES: usize = 64; +/// The largest stroke weight a script may set, in points. +pub const MAX_STROKE_WIDTH: f64 = 1000.0; + +/// The enumerations of paths, as frozen objects whose members are `"Name.MEMBER"` strings. +pub(super) const ENUMS: &[(&str, &[&str])] = &[ + ("PointType", &["CORNER", "SMOOTH"]), + ("PathPointSelection", &["ANCHORPOINT", "LEFTDIRECTION", "LEFTRIGHTPOINT", "NOSELECTION", "RIGHTDIRECTION"]), + ("StrokeCap", &["BUTTENDCAP", "PROJECTINGENDCAP", "ROUNDENDCAP"]), + ("StrokeJoin", &["BEVELENDJOIN", "MITERENDJOIN", "ROUNDENDJOIN"]), + ("PolarityValues", &["NEGATIVE", "POSITIVE"]), + ("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]), +]; + +/// Adds the enumerations of [`ENUMS`] 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(Data::String(format!("{name}.{m}"))))).collect(); + realm.define_host_object(name, items)?; + } + Ok(()) +} + +fn cannot_edit(id: NodeId) -> HostError { + HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0)) +} + +/// The path `d` names, which must still be in its document. +fn path_of(h: &super::Host, d: &Data) -> std::result::Result { + let item = item_of(h, d)?; + let is_path = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))); + if is_path { Ok(item) } else { Err(HostError::Type("this is not a PathItem".into())) } +} + +fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result { + path_of(h, arg(a, 0)) +} + +/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them. +fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result { + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + path_of(h, &path_ref(h, Item { doc, id })) +} + +/// Reads the path of `item` with `f`. +fn read_path(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::doc::Node, &PathData) -> T) -> std::result::Result { + with_doc(h, item.doc, |_, st| match st.doc.node(item.id) { + Some(n) => match n.path_data() { + Some(pd) => Ok(f(st, n, pd)), + None => Err(HostError::Type("this is not a PathItem".into())), + }, + None => Err(HostError::Error(STALE_ITEM.into())), + }) +} + +fn path_ref(h: &super::Host, item: Item) -> Data { + let [high, low] = id_parts(item.id); + host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) +} + +/// How many points a path has, across its subpaths. +fn point_count(pd: &PathData) -> usize { + pd.subpaths.iter().map(|sp| sp.anchors.len()).sum() +} + +/// The subpath and the place in it of point `i`. +fn locate(pd: &PathData, mut i: usize) -> Option<(usize, usize)> { + for (s, sp) in pd.subpaths.iter().enumerate() { + if i < sp.anchors.len() { + return Some((s, i)); + } + i -= sp.anchors.len(); + } + None +} + +fn anchor_json(a: &Anchor) -> Value { + json!({"x": a.p.x, "y": a.p.y, "in": [a.h_in.x, a.h_in.y], "out": [a.h_out.x, a.h_out.y], "smooth": a.kind == AnchorKind::Smooth}) +} + +/// Gives the path of `item` the subpaths `subs` with `path.setAnchors`, unless it has them. +fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { + let (same, ok) = read_path(h, item, |st, _, pd| (pd.subpaths == subs, editable(&st.doc, item.id)))?; + if same { + return Ok(()); + } + if !ok { + return Err(cannot_edit(item.id)); + } + let subpaths: Vec = + subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); + edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + Ok(()) +} + +/// Runs `id` with `params` and `ids: [item]` on the item, which must be one the user could edit. +/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the +/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put +/// back afterwards, so the edit changes only the path. +fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result { + let ok = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)); + if !ok { + return Err(cannot_edit(item.id)); + } + if let Some(o) = params.as_object_mut() { + o.insert("ids".into(), json!([item.id.0])); + } + keeping_paint(h, || edit_item(h, item, id, ¶ms)) +} + +/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color +/// and gradient and the recent colors as they were before it. +fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { + let kept = { + let s = h.session.borrow(); + (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()) + }; + let r = f(); + let mut s = h.session.borrow_mut(); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + r +} + +// ---- Document.pathItems ---- + +/// The ids of a document's paths, in the order of its page items. +fn path_items(h: &super::Host, st: &DocState) -> Rc> { + if let Some((uid, doc, ids)) = &*h.dom.paths.borrow() + && *uid == st.uid + && std::sync::Arc::ptr_eq(doc, &st.doc) + { + return ids.clone(); + } + let all = super::page_items(h, st); + let ids: Rc> = + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); + *h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + ids +} + +pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) +} + +fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "PathItems") +} + +fn items_length(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) +} + +fn items_parent(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) +} + +fn items_at(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + 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| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) +} + +fn items_by_name(h: &super::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())) }; + with_doc(h, doc, |_, st| { + let ids = path_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())); + id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) + }) +} + +fn items_index(h: &super::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), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked +/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let (ids, refused) = with_doc(h, doc, |_, st| { + let ids = path_items(h, st); + let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **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 paths: {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) +} + +/// The id in the result of a command that made an object. +fn made_id(r: &Data) -> std::result::Result { + let id = match r { + Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), + _ => None, + }; + id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +} + +/// Runs the command `id` that makes a path in `doc`, the selection kept, and reverses the new +/// path's direction when `reversed`. → the new path. +fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { + let made = on_doc(h, doc.uid, true, |h| { + let id = made_id(&command(h, id, params)?)?; + if reversed { + command(h, "path.reverse", &json!({"ids": [id.0]}))?; + } + Ok(id) + })?; + 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(super::item_ref(h, st, made)) +} + +/// Argument `i`, or `default` when it is left out. +fn number_or(a: &[Data], i: usize, default: f64, what: &str) -> std::result::Result { + given(arg(a, i)).map_or(Ok(default), |d| number(d, what)) +} + +/// A size or radius: finite and not negative. +fn size(a: &[Data], i: usize, default: Option, what: &str) -> std::result::Result { + let v = match (given(arg(a, i)), default) { + (Some(d), _) => number(d, what)?, + (None, Some(v)) => v, + (None, None) => return Err(HostError::Type(format!("{what} must be a finite number"))), + }; + if !(0.0..=super::MAX_SIZE).contains(&v) { + return Err(HostError::Range(format!("{what} must be from 0 to 3999856 points"))); + } + Ok(v) +} + +/// A whole number argument from `min` to `max`. +fn count(a: &[Data], i: usize, default: f64, min: f64, max: f64, what: &str) -> std::result::Result { + let v = number_or(a, i, default, what)?; + if v.fract() != 0.0 || !(min..=max).contains(&v) { + return Err(HostError::Range(format!("{what} must be a whole number from {min} to {max}"))); + } + Ok(v) +} + +fn flag(a: &[Data], i: usize, what: &str) -> std::result::Result { + given(arg(a, i)).map_or(Ok(false), |d| boolean(d, what)) +} + +/// The top-left corner, in document coordinates, of a box whose top-left corner the script gives. +fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result { + with_doc(h, doc, |_, st| Ok(frame(st)?.to_document(h.dom.coords.get(), [left, top]))) +} + +/// `rectangle(top, left, width, height, reversed?)`. +fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let top = coordinate(arg(a, 1), "top")?; + let left = coordinate(arg(a, 2), "left")?; + let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); + let reversed = flag(a, 5, "reversed")?; + let p = corner(h, doc, left, top)?; + make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) +} + +/// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the +/// page from the top of the left side. +fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { + const K: f64 = 0.552_284_749_830_793_4; + let (rx, ry) = (rx.min(r.width() / 2.0), ry.min(r.height() / 2.0)); + let (kx, ky) = (rx * K, ry * K); + let a = |p: Point, h_in: Point, h_out: Point| Anchor { p, h_in, h_out, kind: AnchorKind::Corner }; + let (x0, y0, x1, y1) = (r.x0, r.y0, r.x1, r.y1); + let mut out = vec![ + a(Point::new(x0, y0 + ry), Point::new(x0, y0 + ry), Point::new(x0, y0 + ry - ky)), + a(Point::new(x0 + rx, y0), Point::new(x0 + rx - kx, y0), Point::new(x0 + rx, y0)), + a(Point::new(x1 - rx, y0), Point::new(x1 - rx, y0), Point::new(x1 - rx + kx, y0)), + a(Point::new(x1, y0 + ry), Point::new(x1, y0 + ry - ky), Point::new(x1, y0 + ry)), + a(Point::new(x1, y1 - ry), Point::new(x1, y1 - ry), Point::new(x1, y1 - ry + ky)), + a(Point::new(x1 - rx, y1), Point::new(x1 - rx + kx, y1), Point::new(x1 - rx, y1)), + a(Point::new(x0 + rx, y1), Point::new(x0 + rx, y1), Point::new(x0 + rx - kx, y1)), + a(Point::new(x0, y1 - ry), Point::new(x0, y1 - ry + ky), Point::new(x0, y1 - ry)), + ]; + out.dedup_by(|b, a| { + b.p.distance(a.p) < 1e-9 && { + a.h_out = b.h_out; + true + } + }); + if out.len() > 1 + && out.first().zip(out.last()).is_some_and(|(f, l)| f.p.distance(l.p) < 1e-9) + && let Some(l) = out.pop() + && let Some(f) = out.first_mut() + { + f.h_in = l.h_in; + } + out +} + +/// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, +/// reversed = false)`: a closed path with `path.create`. +fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let top = coordinate(arg(a, 1), "top")?; + let left = coordinate(arg(a, 2), "left")?; + let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); + let (rx, ry) = (size(a, 5, Some(15.0), "horizontalRadius")?, size(a, 6, Some(20.0), "verticalRadius")?); + let reversed = flag(a, 7, "reversed")?; + let p = corner(h, doc, left, top)?; + let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); + make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) +} + +/// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. +fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; + let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; + let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); + let reversed = flag(a, 5, "reversed")?; + if flag(a, 6, "inscribed")? { + return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); + } + let p = corner(h, doc, left, top)?; + make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) +} + +/// The center of a polygon or star, in document coordinates. +fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result { + let x = given(arg(a, 1)).map_or(Ok(200.0), |d| coordinate(d, "centerX"))?; + let y = given(arg(a, 2)).map_or(Ok(300.0), |d| coordinate(d, "centerY"))?; + corner(h, doc, x, y) +} + +/// `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed = false)`. +fn items_polygon(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let c = center(h, doc, a)?; + let r = size(a, 3, Some(50.0), "radius")?; + let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; + let reversed = flag(a, 5, "reversed")?; + make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) +} + +/// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = +/// false)`. +fn items_star(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let c = center(h, doc, a)?; + let r1 = size(a, 3, Some(50.0), "radius")?; + let r2 = size(a, 4, Some(20.0), "innerRadius")?; + let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; + let reversed = flag(a, 6, "reversed")?; + make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) +} + +/// `pathItems.add()`: a path with no points, from `path.create` with empty path data, painted as +/// new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open +/// path is set back to none in the same step. +fn items_add(h: &super::Host, a: &[Data]) -> Answer { + let doc = items_doc(h, a)?; + let made = on_doc(h, doc.uid, true, |h| { + let unpainted = { + let ap = h.session.borrow().new_art(); + ap.fill_paint().is_none() && ap.stroke_paint().is_none() + }; + let id = made_id(&command(h, "path.create", &json!({"d": ""}))?)?; + if unpainted { + keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; + } + Ok(id) + })?; + 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(super::item_ref(h, st, made)) +} + +// ---- PathItem geometry ---- + +fn path_points(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + let [high, low] = id_parts(item.id); + Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low])) +} + +fn path_closed(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, _, pd| Data::Bool(!pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed))) +} + +fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { + let closed = boolean(arg(a, 1), "closed")?; + let item = this_path(h, a)?; + let subs = read_path(h, item, |_, _, pd| pd.subpaths.iter().map(|sp| SubPath { anchors: sp.anchors.clone(), closed }).collect())?; + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +/// Whether the path fills by the even-odd rule: its compound path's rule when it is a member of one, +/// as `path.setFillRule` sets it there. +fn path_evenodd(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |st, n, _| { + let owner = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n); + Data::Bool(matches!(owner.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. } | NodeKind::Compound { rule: FillRule::EvenOdd, .. })) + }) +} + +fn path_set_evenodd(h: &super::Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "evenodd")?; + let item = this_path(h, a)?; + if path_evenodd(h, a)? != Data::Bool(on) { + edit_path(h, item, "path.setFillRule", json!({"rule": if on { "evenOdd" } else { "nonZero" }}))?; + } + Ok(Data::Undefined) +} + +/// The area in square points: negative when the path runs counterclockwise on the page. +fn path_area(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, _, pd| num(pd.subpaths.iter().map(SubPath::signed_area).sum())) +} + +fn path_length(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, _, pd| num(pd.length())) +} + +fn path_guides(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { guide: true, .. }))) +} + +fn path_clipping(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { clipping: true, .. }))) +} + +/// `setEntirePath([[x, y], ...])`: corner points with no handles in place of every point, in one +/// subpath that stays closed when the path was. +fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + let Data::Array(list) = arg(a, 1) else { return Err(HostError::Type("setEntirePath needs an array of [x, y] points".into())) }; + if list.len() > MAX_POINTS { + return Err(HostError::Range(format!("setEntirePath takes at most {MAX_POINTS} points"))); + } + let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::>()?; + let (f, closed) = read_path(h, item, |st, _, pd| (frame(st), !pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed)))?; + let (f, c) = (f?, h.dom.coords.get()); + let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); + let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +// ---- PathItem paint ---- + +/// The top fill's paint and the top stroke's paint, width, cap, join, miter limit, dashes and +/// offset, and the overprint flags of both. +struct Look { + fill: Paint, + fill_overprint: bool, + stroke: Paint, + width: f64, + cap: LineCap, + join: LineJoin, + miter: f64, + dashes: Vec, + offset: f64, + stroke_overprint: bool, +} + +/// The look of `item`, read from its compound path or compound shape when it is a member of one, +/// since the paint commands paint that owner in its place. +fn look(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |st, n, _| { + let d = &st.doc; + let owner = d + .parent_of(item.id) + .and_then(|p| d.node(p)) + .filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()) + .unwrap_or(n); + let ap = &owner.appearance; + let fill = ap.fill(); + let stroke = ap.stroke(); + Look { + fill: fill.map_or(Paint::None, |f| f.paint.clone()), + fill_overprint: fill.is_some_and(|f| f.overprint), + stroke: stroke.map_or(Paint::None, |s| s.paint.clone()), + width: stroke.map_or(0.0, |s| s.width), + cap: stroke.map_or(LineCap::default(), |s| s.cap), + join: stroke.map_or(LineJoin::default(), |s| s.join), + miter: stroke.map_or(10.0, |s| s.miter_limit), + dashes: stroke.and_then(|s| s.dash.as_ref()).map_or_else(Vec::new, |d| d.pattern.clone()), + offset: stroke.and_then(|s| s.dash.as_ref()).map_or(0.0, |d| d.offset), + stroke_overprint: stroke.is_some_and(|s| s.overprint), + } + }) +} + +fn this_look(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, Look), HostError> { + let item = this_path(h, a)?; + Ok((item, look(h, item)?)) +} + +fn path_filled(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(!this_look(h, a)?.1.fill.is_none())) +} + +fn path_stroked(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(!this_look(h, a)?.1.stroke.is_none())) +} + +/// Sets the fill (`fill`) or the stroke to `color`, or to none, with `paint.setFill` or +/// `paint.setStroke`. +fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option) -> std::result::Result<(), HostError> { + let id = if fill { "paint.setFill" } else { "paint.setStroke" }; + let params = match color { + Some(c) => json!({"color": colors::param(&c)}), + None => json!({"none": true}), + }; + edit_path(h, item, id, params)?; + Ok(()) +} + +/// The paint new art gets for its fill or stroke, as `paint.setFill` or `paint.setStroke` params for +/// the path `item`: a solid color, linked to its global or spot swatch while the document has that +/// swatch; a gradient, a placed one moved onto the path's bounds as new art takes it; or a pattern. +/// A fill or stroke of none gives black. A pattern that its swatch does not give as new art has it +/// (its own placement, or a pattern the document does not have) throws an error. +fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Result { + let mut ap = h.session.borrow().new_art(); + let top = |ap: &vectorcraft_doc::Appearance| if fill { ap.fill_paint() } else { ap.stroke_paint() }; + let what = if fill { "filled" } else { "stroked" }; + let paint = top(&ap); + match &paint { + Paint::None => Ok(json!({"color": colors::param(&Color::BLACK)})), + Paint::Solid { color, swatch: Some(name), tint } => { + let linked = read_path(h, item, |st, _, _| st.doc.swatch(name).is_some())?; + Ok(match linked { + true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), + true => json!({"swatch": name}), + false => json!({"color": colors::param(color)}), + }) + } + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Gradient(g) => { + let mut g = g.clone(); + if g.geom.is_some() || g.freeform.is_some() { + match read_path(h, item, |_, n, _| n.geometric_bounds())? { + Some(b) => { + ap.rebase_gradients(GraphicStyle::UNIT_BOX, b); + if let Paint::Gradient(placed) = top(&ap) { + g = placed; + } + } + None => (g.geom, g.freeform) = (None, None), + } + } + Ok(json!({"gradient": gradient_params(&g), "keepModel": true})) + } + Paint::Pattern { pattern, .. } => { + let given = read_path(h, item, |st, _, _| { + let d = &st.doc; + d.swatch(pattern).map(|sw| sw.paint.clone()).or_else(|| d.pattern(pattern).map(|_| pattern_paint(pattern))) + })?; + match given { + Some(p) if p == paint => Ok(json!({"swatch": pattern})), + Some(_) => Err(HostError::Error(format!( + "Cannot set {what}: new art's pattern `{pattern}` has a placement of its own, which is not available yet" + ))), + None => Err(HostError::Error(format!("Cannot set {what}: new art's pattern `{pattern}` is not in this document"))), + } + } + } +} + +fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer { + let on = boolean(arg(a, 1), if fill { "filled" } else { "stroked" })?; + let (item, look) = this_look(h, a)?; + let now = if fill { !look.fill.is_none() } else { !look.stroke.is_none() }; + if now != on { + let params = if on { new_art_params(h, item, fill)? } else { json!({"none": true}) }; + edit_path(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?; + } + Ok(Data::Undefined) +} + +fn path_set_filled(h: &super::Host, a: &[Data]) -> Answer { + set_painted(h, a, true) +} + +fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer { + set_painted(h, a, false) +} + +fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer { + Ok(colors::of_paint(&this_look(h, a)?.1.fill)) +} + +fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer { + Ok(colors::of_paint(&this_look(h, a)?.1.stroke)) +} + +fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer { + let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?; + let (item, look) = this_look(h, a)?; + let now = if fill { &look.fill } else { &look.stroke }; + let same = match (&color, now) { + (None, Paint::None) => true, + (Some(c), Paint::Solid { color, swatch: None, .. }) => c == color, + _ => false, + }; + if !same { + set_paint(h, item, fill, color)?; + } + Ok(Data::Undefined) +} + +fn path_set_fill_color(h: &super::Host, a: &[Data]) -> Answer { + set_color(h, a, true) +} + +fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer { + set_color(h, a, false) +} + +/// Runs `stroke.set` with `params` on the path, unless `same`. +fn set_stroke_option(h: &super::Host, item: Item, same: bool, params: Value) -> Answer { + if !same { + edit_path(h, item, "stroke.set", params)?; + } + Ok(Data::Undefined) +} + +fn path_stroke_width(h: &super::Host, a: &[Data]) -> Answer { + Ok(num(this_look(h, a)?.1.width)) +} + +fn path_set_stroke_width(h: &super::Host, a: &[Data]) -> Answer { + let w = number(arg(a, 1), "strokeWidth")?; + if !(0.0..=MAX_STROKE_WIDTH).contains(&w) { + return Err(HostError::Range("strokeWidth must be from 0 to 1000 points".into())); + } + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, (look.width - w).abs() < 1e-9, json!({"weight": w})) +} + +const CAPS: &[(LineCap, &str, &str)] = &[ + (LineCap::Butt, "StrokeCap.BUTTENDCAP", "butt"), + (LineCap::Round, "StrokeCap.ROUNDENDCAP", "round"), + (LineCap::Square, "StrokeCap.PROJECTINGENDCAP", "square"), +]; + +const JOINS: &[(LineJoin, &str, &str)] = &[ + (LineJoin::Bevel, "StrokeJoin.BEVELENDJOIN", "bevel"), + (LineJoin::Round, "StrokeJoin.ROUNDENDJOIN", "round"), + (LineJoin::Miter, "StrokeJoin.MITERENDJOIN", "miter"), +]; + +fn path_stroke_cap(h: &super::Host, a: &[Data]) -> Answer { + let cap = this_look(h, a)?.1.cap; + Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into())) +} + +fn path_set_stroke_cap(h: &super::Host, a: &[Data]) -> Answer { + let found = match arg(a, 1) { + Data::String(s) => CAPS.iter().find(|c| c.1 == s), + _ => None, + }; + let Some(&(cap, _, name)) = found else { return Err(HostError::Type("strokeCap must be a StrokeCap value".into())) }; + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, look.cap == cap, json!({"cap": name})) +} + +fn path_stroke_join(h: &super::Host, a: &[Data]) -> Answer { + let join = this_look(h, a)?.1.join; + Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into())) +} + +fn path_set_stroke_join(h: &super::Host, a: &[Data]) -> Answer { + let found = match arg(a, 1) { + Data::String(s) => JOINS.iter().find(|j| j.1 == s), + _ => None, + }; + let Some(&(join, _, name)) = found else { return Err(HostError::Type("strokeJoin must be a StrokeJoin value".into())) }; + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, look.join == join, json!({"join": name})) +} + +fn path_miter(h: &super::Host, a: &[Data]) -> Answer { + Ok(num(this_look(h, a)?.1.miter)) +} + +fn path_set_miter(h: &super::Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "strokeMiterLimit")?; + if !(1.0..=500.0).contains(&v) { + return Err(HostError::Range("strokeMiterLimit must be from 1 to 500".into())); + } + let (item, look) = this_look(h, a)?; + set_stroke_option(h, item, (look.miter - v).abs() < 1e-9, json!({"miterLimit": v})) +} + +fn path_dashes(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Array(this_look(h, a)?.1.dashes.into_iter().map(num).collect())) +} + +/// `strokeDashes = [lengths]`: at most [`MAX_DASHES`] finite lengths that are not negative and +/// not all 0; `[]` or `{}` gives a solid line. +fn path_set_dashes(h: &super::Host, a: &[Data]) -> Answer { + let lengths: Vec = match arg(a, 1) { + Data::Object(o) if o.is_empty() => Vec::new(), + Data::Array(list) if list.len() > MAX_DASHES => return Err(HostError::Range(format!("strokeDashes takes at most {MAX_DASHES} lengths"))), + Data::Array(list) => list.iter().map(|d| number(d, "each dash length")).collect::>()?, + _ => return Err(HostError::Type("strokeDashes must be an array of lengths".into())), + }; + if lengths.iter().any(|l| !(0.0..=MAX_STROKE_WIDTH * 1000.0).contains(l)) { + return Err(HostError::Range("each dash length must be from 0 to 1000000 points".into())); + } + if !lengths.is_empty() && lengths.iter().all(|l| *l == 0.0) { + return Err(HostError::Range("strokeDashes needs a length that is not 0".into())); + } + let (item, look) = this_look(h, a)?; + let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) }; + set_stroke_option(h, item, look.dashes == lengths, json!({"dash": dash})) +} + +fn path_dash_offset(h: &super::Host, a: &[Data]) -> Answer { + Ok(num(this_look(h, a)?.1.offset)) +} + +fn path_set_dash_offset(h: &super::Host, a: &[Data]) -> Answer { + let v = number(arg(a, 1), "strokeDashOffset")?; + if v.abs() > MAX_STROKE_WIDTH * 1000.0 { + return Err(HostError::Range("strokeDashOffset must be from -1000000 to 1000000 points".into())); + } + let (item, look) = this_look(h, a)?; + if look.dashes.is_empty() && v != 0.0 { + return Err(HostError::Error("strokeDashOffset needs strokeDashes first".into())); + } + set_stroke_option(h, item, (look.offset - v).abs() < 1e-9, json!({"dashOffset": v})) +} + +fn path_fill_overprint(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(this_look(h, a)?.1.fill_overprint)) +} + +fn path_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { + Ok(Data::Bool(this_look(h, a)?.1.stroke_overprint)) +} + +fn set_overprint(h: &super::Host, a: &[Data], fill: bool) -> Answer { + let key = if fill { "fill" } else { "stroke" }; + let on = boolean(arg(a, 1), if fill { "fillOverprint" } else { "strokeOverprint" })?; + let (item, look) = this_look(h, a)?; + let (now, paint) = if fill { (look.fill_overprint, &look.fill) } else { (look.stroke_overprint, &look.stroke) }; + if now != on { + if paint.is_none() { + return Err(HostError::Error(format!("the path has no {key} to overprint"))); + } + edit_path(h, item, "object.setOverprint", json!({key: on}))?; + } + Ok(Data::Undefined) +} + +fn path_set_fill_overprint(h: &super::Host, a: &[Data]) -> Answer { + set_overprint(h, a, true) +} + +fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { + set_overprint(h, a, false) +} + +// ---- PathItem transforms ---- + +/// The point of the path's geometric bounds `r`, in document coordinates, that a `Transformation` +/// value names (left out: the center). +fn about(h: &super::Host, item: Item, d: &Data, r: Rect) -> std::result::Result { + let name = match d { + Data::Undefined => "Transformation.CENTER", + Data::String(s) => s.as_str(), + _ => return Err(HostError::Type("give a Transformation value".into())), + }; + let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); + Ok(match name.strip_prefix("Transformation.").unwrap_or("") { + "CENTER" => Point::new(cx, cy), + "TOP" => Point::new(cx, r.y0), + "BOTTOM" => Point::new(cx, r.y1), + "LEFT" => Point::new(r.x0, cy), + "RIGHT" => Point::new(r.x1, cy), + "TOPLEFT" => Point::new(r.x0, r.y0), + "TOPRIGHT" => Point::new(r.x1, r.y0), + "BOTTOMLEFT" => Point::new(r.x0, r.y1), + "BOTTOMRIGHT" => Point::new(r.x1, r.y1), + "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(Coords::Document, [0.0, 0.0])))?, + _ => return Err(HostError::Type("give a Transformation value".into())), + }) +} + +/// The `objects` and `patterns` options of a transform command from the four flags from `i`: +/// objects, fill patterns, fill gradients and stroke patterns, each left out or true or false. +fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::Result<(), HostError> { + let names = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; + let mut flags = [None; 4]; + for (k, name) in names.iter().enumerate() { + flags[k] = given(arg(a, i + k)).map(|d| boolean(d, name)).transpose()?; + } + if flags[2] == Some(false) { + return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2]))); + } + if let (Some(f), Some(s)) = (flags[1], flags[3]) + && f != s + { + return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); + } + if let Some(o) = params.as_object_mut() { + if let Some(b) = flags[0] { + o.insert("objects".into(), json!(b)); + } + if let Some(b) = flags[1].or(flags[3]) { + o.insert("patterns".into(), json!(b)); + } + } + Ok(()) +} + +/// `translate(deltaX = 0, deltaY = 0, transformObjects?, transformFillPatterns?, ...)`. +fn path_translate(h: &super::Host, a: &[Data]) -> Answer { + let dx = given(arg(a, 1)).map_or(Ok(0.0), |d| coordinate(d, "deltaX"))?; + let dy = given(arg(a, 2)).map_or(Ok(0.0), |d| coordinate(d, "deltaY"))?; + let item = this_path(h, a)?; + let mut params = json!({"dx": dx, "dy": if h.dom.coords.get() == Coords::Document { -dy } else { dy }}); + transform_options(a, 3, &mut params)?; + if dx != 0.0 || dy != 0.0 { + edit_path(h, item, "object.move", params)?; + } + Ok(Data::Undefined) +} + +/// `rotate(angle, changePositions?, ..., rotateAbout?)`: counterclockwise on the page for a +/// positive angle. +fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { + let angle = number(arg(a, 1), "angle")?; + let item = this_path(h, a)?; + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, arg(a, 6), r)?; + let mut params = json!({"angle": angle, "origin": [origin.x, origin.y]}); + transform_options(a, 2, &mut params)?; + if angle.rem_euclid(360.0) != 0.0 { + edit_path(h, item, "object.rotate", params)?; + } + Ok(Data::Undefined) +} + +/// `resize(scaleX, scaleY, changePositions?, ..., changeLineWidths?, scaleAbout?)`: 100 is 100%; +/// `changeLineWidths` scales the stroke weight by that percent. +fn path_resize(h: &super::Host, a: &[Data]) -> Answer { + let sx = number(arg(a, 1), "scaleX")?; + let sy = number(arg(a, 2), "scaleY")?; + if sx == 0.0 || sy == 0.0 || sx.abs() > 100_000.0 || sy.abs() > 100_000.0 { + return Err(HostError::Range("scaleX and scaleY must not be 0 and at most 100000 percent".into())); + } + let widths = given(arg(a, 7)).map(|d| number(d, "changeLineWidths")).transpose()?; + if widths.is_some_and(|w| !(0.0..=100_000.0).contains(&w)) { + return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); + } + let item = this_path(h, a)?; + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, arg(a, 8), r)?; + let mut params = json!({"sx": sx, "sy": sy, "origin": [origin.x, origin.y], "basis": "page", "strokes": false}); + transform_options(a, 3, &mut params)?; + let width = look(h, item)?.width; + let new_width = widths.map(|w| width * w / 100.0); + if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } + if sx != 100.0 || sy != 100.0 { + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(Data::Undefined) +} + +// ---- PathPoints ---- + +fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result { + let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) }; + let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) }; + path_at(h, *run, *uid, *high, *low) +} + +fn points_length(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + read_path(h, item, |_, _, pd| num(float(point_count(pd) as u64))) +} + +fn points_parent(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + Ok(path_ref(h, item)) +} + +fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { + let [high, low] = id_parts(item.id); + host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64)]) +} + +fn points_at(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + 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) }; + let n = read_path(h, item, |_, _, pd| point_count(pd))?; + Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) +} + +/// `index(key)`: the points are not named, so a key that is not a number throws `Not found`. +fn points_index(h: &super::Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::Number(_) => match points_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn points_add(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + let (mut subs, n, origin) = read_path(h, item, |st, _, pd| { + let origin = frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0])); + (pd.subpaths.clone(), point_count(pd), origin) + })?; + if n >= MAX_POINTS { + return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); + } + let p = match subs.iter().rev().find_map(|sp| sp.anchors.last()) { + Some(last) => last.p, + None => origin?, + }; + match subs.last_mut() { + Some(sp) => sp.anchors.push(Anchor::corner(p)), + None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), + } + write_path(h, item, subs)?; + Ok(point_ref(h, item, n)) +} + +fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { + let item = points_path(h, a)?; + write_path(h, item, Vec::new())?; + Ok(Data::Undefined) +} + +// ---- PathPoint ---- + +/// The path and the index of the point `this` names, which must still be in the path. +pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let [run, uid, high, low, i] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let item = path_at(h, *run, *uid, *high, *low)?; + let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + let n = read_path(h, item, |_, _, pd| point_count(pd))?; + if i >= n { + return Err(HostError::Error(STALE_POINT.into())); + } + Ok((item, i)) +} + +/// Reads the anchor `this` names with `f`, given the frame and the coordinate system. +fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { + let (item, i) = this_point(h, a)?; + let c = h.dom.coords.get(); + read_path(h, item, |st, _, pd| { + let fr = frame(st)?; + let anchor = locate(pd, i).and_then(|(s, j)| pd.subpaths.get(s).and_then(|sp| sp.anchors.get(j))); + anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) + })? +} + +/// Changes the anchor `this` names with `f`, given the point the script assigned in document +/// coordinates (for a point property) or the value itself. +fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { + let (item, i) = this_point(h, a)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { + f(an); + } + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +/// The point the script assigned to a point property, in document coordinates. +fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Result { + let p = point(arg(a, 1), what)?; + let (item, _) = this_point(h, a)?; + let fr = with_doc(h, item.doc, |_, st| frame(st))?; + Ok(fr.to_document(h.dom.coords.get(), p)) +} + +fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |f, c, an| pair(f.to_script(c, an.p))) +} + +fn pt_set_anchor(h: &super::Host, a: &[Data]) -> Answer { + let p = assigned_point(h, a, "anchor")?; + edit_point(h, a, |an| an.p = p) +} + +fn pt_left(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |f, c, an| pair(f.to_script(c, an.h_in))) +} + +fn pt_set_left(h: &super::Host, a: &[Data]) -> Answer { + let p = assigned_point(h, a, "leftDirection")?; + edit_point(h, a, |an| an.h_in = p) +} + +fn pt_right(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |f, c, an| pair(f.to_script(c, an.h_out))) +} + +fn pt_set_right(h: &super::Host, a: &[Data]) -> Answer { + let p = assigned_point(h, a, "rightDirection")?; + edit_point(h, a, |an| an.h_out = p) +} + +fn pt_type(h: &super::Host, a: &[Data]) -> Answer { + read_point(h, a, |_, _, an| Data::String(if an.kind == AnchorKind::Smooth { "PointType.SMOOTH" } else { "PointType.CORNER" }.into())) +} + +fn pt_set_type(h: &super::Host, a: &[Data]) -> Answer { + let kind = match arg(a, 1) { + Data::String(s) if s == "PointType.CORNER" => AnchorKind::Corner, + Data::String(s) if s == "PointType.SMOOTH" => AnchorKind::Smooth, + _ => return Err(HostError::Type("pointType must be a PointType value".into())), + }; + edit_point(h, a, |an| an.kind = kind) +} + +fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { + let (item, _) = this_point(h, a)?; + Ok(path_ref(h, item)) +} + +/// `remove()`: deletes the point; a subpath left with no points goes too. +fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { + let (item, i) = this_point(h, a)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; + if let Some(sp) = subs.get_mut(s) { + sp.anchors.remove(j); + if sp.anchors.is_empty() { + subs.remove(s); + } + } + write_path(h, item, subs)?; + Ok(Data::Undefined) +} + +// ---- Registration ---- + +/// The members `PathItem` adds to `PageItem`'s. +pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> { + let mut m = named(vec![ + ("pathPoints", get(l, path_points)), + ("closed", property(l, path_closed, path_set_closed)), + ("evenodd", property(l, path_evenodd, path_set_evenodd)), + ("area", get(l, path_area)), + ("length", get(l, path_length)), + ("guides", get(l, path_guides)), + ("clipping", get(l, path_clipping)), + ("setEntirePath", method(l, path_set_entire)), + ("filled", property(l, path_filled, path_set_filled)), + ("fillColor", property(l, path_fill_color, path_set_fill_color)), + ("fillOverprint", property(l, path_fill_overprint, path_set_fill_overprint)), + ("stroked", property(l, path_stroked, path_set_stroked)), + ("strokeColor", property(l, path_stroke_color, path_set_stroke_color)), + ("strokeOverprint", property(l, path_stroke_overprint, path_set_stroke_overprint)), + ("strokeWidth", property(l, path_stroke_width, path_set_stroke_width)), + ("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap)), + ("strokeJoin", property(l, path_stroke_join, path_set_stroke_join)), + ("strokeMiterLimit", property(l, path_miter, path_set_miter)), + ("strokeDashes", property(l, path_dashes, path_set_dashes)), + ("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset)), + ("translate", method(l, path_translate)), + ("rotate", method(l, path_rotate)), + ("resize", method(l, path_resize)), + ]); + m.extend(["selectedPathPoints", "polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); + m +} + +/// `PathItems`, `PathPoints` and `PathPoint`. +pub(super) fn classes(l: &Link) -> Vec { + vec![ + class( + "PathItems", + None, + named(vec![ + ("typename", typename_of("PathItems")), + ("length", get(l, items_length)), + ("parent", get(l, items_parent)), + ("index", method(l, items_index)), + ("getByName", method(l, items_by_name)), + ("removeAll", method(l, items_remove_all)), + ("add", method(l, items_add)), + ("rectangle", method(l, items_rectangle)), + ("roundedRectangle", method(l, items_rounded_rectangle)), + ("ellipse", method(l, items_ellipse)), + ("polygon", method(l, items_polygon)), + ("star", method(l, items_star)), + ]), + Some(super::function(l, items_at)), + ), + class( + "PathPoints", + None, + named(vec![ + ("typename", typename_of("PathPoints")), + ("length", get(l, points_length)), + ("parent", get(l, points_parent)), + ("index", method(l, points_index)), + ("add", method(l, points_add)), + ("removeAll", method(l, points_remove_all)), + ]), + Some(super::function(l, points_at)), + ), + class( + "PathPoint", + None, + { + let mut m = named(vec![ + ("typename", typename_of("PathPoint")), + ("parent", get(l, pt_parent)), + ("anchor", property(l, pt_anchor, pt_set_anchor)), + ("leftDirection", property(l, pt_left, pt_set_left)), + ("rightDirection", property(l, pt_right, pt_set_right)), + ("pointType", property(l, pt_type, pt_set_type)), + ("remove", method(l, pt_remove)), + ]); + m.push(later(l, "PathPoint", "selected")); + m + }, + None, + ), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..a611da1857 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -173,6 +173,7 @@ mod script_console; mod script_dialogs; mod script_dollar; mod script_dom; +mod script_dom_paths; mod script_engines; mod script_folder; mod script_include; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 67bd373e2d..fc2cd6ce67 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -646,9 +646,11 @@ fn a_startup_preset_alone_gives_its_first_size() { #[test] fn page_item_members_not_built_yet_throw_on_read_and_assignment() { let (mut s, _, _) = doc(); - for source in - ["app.activeDocument.pageItems[0].blendingMode;", "app.activeDocument.pageItems[0].uuid = 'x';", "app.activeDocument.pageItems[0].rotate(5);"] - { + for source in [ + "app.activeDocument.pageItems[0].blendingMode;", + "app.activeDocument.pageItems[0].uuid = 'x';", + "app.activeDocument.pageItems[0].transform(5);", + ] { assert!(failure(&mut s, source).contains("is not available yet"), "{source}"); } assert!(failure(&mut s, "app.activeDocument.layers = 1;").contains("Document.layers is not available yet")); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs new file mode 100644 index 0000000000..9d9c0c5f7a --- /dev/null +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -0,0 +1,602 @@ +//! The script object model's paths, path points and colors. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{LineCap, LineJoin}; +use vectorcraft_geom::path::AnchorKind; + +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 rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap()) +} + +/// A 400 × 300 pt document with two rectangles. +fn doc() -> (Session, NodeId, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + s.execute("select.none", &json!({})).unwrap(); + (s, a, b) +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// The layers of the active document, to show that a failed run changed nothing. +fn art(s: &Session) -> String { + format!("{:?}", s.active().unwrap().doc.layers) +} + +fn node(s: &Session, id: NodeId) -> crate::doc::Node { + s.active().unwrap().doc.node(id).unwrap().clone() +} + +/// Each number of `v` rounded to 3 decimals, in place. +fn rounded(v: &Value) -> Value { + match v { + Value::Number(n) => { + let r = (n.as_f64().unwrap() * 1000.0).round() / 1000.0; + if r.fract() == 0.0 { json!(r as i64) } else { json!(r) } + } + Value::Array(a) => Value::Array(a.iter().map(rounded).collect()), + v => v.clone(), + } +} + +#[test] +fn path_items_are_live_and_list_only_paths() { + let (mut s, a, b) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "name": "first"})).unwrap(); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pathItems;\ + vc.log(p.length); vc.log(d.pageItems.length); vc.log(p.typename); vc.log(p.parent.typename);\ + vc.log(p[0].typename); vc.log(p[1].parent.typename); vc.log(p.getByName('first').name);\ + vc.log(p[2] === undefined && p[-1] === undefined);\ + var r = p.rectangle(100, 10, 5, 5); vc.log(p.length); vc.log(p[2].typename);", + ); + let expected = [json!(2), json!(4), json!("PathItems"), json!("Document"), json!("PathItem"), json!("GroupItem"), json!("first"), json!(true)]; + assert_eq!(out[..8], expected); + assert_eq!(out[8..], [json!(3), json!("PathItem")]); + assert!(failure(&mut s, "app.activeDocument.pathItems.getByName('none');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pathItems.index('none');").contains("Not found")); +} + +#[test] +fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let before = art(&s); + let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert!(e.contains("hidden or locked paths"), "{e}"); + assert_eq!(art(&s), before); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": false})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.removeAll();"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]); +} + +#[test] +fn shape_creators_use_documented_defaults_and_y_up() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems;\ + vc.log(p.rectangle(250, 10, 30, 40).geometricBounds);\ + vc.log(p.ellipse().geometricBounds);\ + var g = p.polygon(); vc.log(g.pathPoints.length); var b = g.geometricBounds; vc.log([(b[0] + b[2]) / 2, b[1]]);\ + vc.log(p.star().pathPoints.length); vc.log(p.star(0, 0, 10, 5, 7).pathPoints.length);\ + var r = p.roundedRectangle(250, 10, 100, 60); vc.log(r.pathPoints.length); vc.log(r.geometricBounds); vc.log(r.closed);\ + vc.log(p.roundedRectangle(250, 10, 100, 60, 0, 0).pathPoints.length);\ + vc.log(p.length);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out[0], json!([10, 250, 40, 210])); + assert_eq!(out[1], json!([100, 100, 150, 0])); + assert_eq!(out[2], json!(8)); + assert_eq!(out[3], json!([200, 350]), "the polygon is centered on (200, 300) and reaches 50 pt up"); + assert_eq!(out[4], json!(10)); + assert_eq!(out[5], json!(14)); + assert_eq!(out[6], json!(8)); + assert_eq!(out[7], json!([10, 250, 110, 190])); + assert_eq!(out[8], json!(true)); + assert_eq!(out[9], json!(4), "corners of radius 0 leave four points"); + assert_eq!(out[10], json!(7)); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + assert!(s.active().unwrap().selection.objects.is_empty(), "the selection stays as it was"); +} + +#[test] +fn shape_creators_reject_bad_sizes_without_change() { + let (mut s, _, _) = doc(); + let before = art(&s); + let steps = undo_steps(&s); + for (source, part) in [ + ("app.activeDocument.pathItems.rectangle(10, 10, -5, 10);", "width"), + ("app.activeDocument.pathItems.rectangle(10, 10, 5);", "height"), + ("app.activeDocument.pathItems.rectangle();", "top"), + ("app.activeDocument.pathItems.ellipse(0, 0, NaN);", "finite"), + ("app.activeDocument.pathItems.polygon(0, 0, 10, 2);", "sides"), + ("app.activeDocument.pathItems.polygon(0, 0, 10, 5.5);", "sides"), + ("app.activeDocument.pathItems.star(0, 0, 10, 5, 1001);", "points"), + ("app.activeDocument.pathItems.star(0, 0, 10, -5);", "innerRadius"), + ("app.activeDocument.pathItems.roundedRectangle(0, 0, 10, 10, -1);", "horizontalRadius"), + ("app.activeDocument.pathItems.rectangle(0, 0, 10, 10, 'yes');", "reversed"), + ("app.activeDocument.pathItems.rectangle(1e12, 0, 10, 10);", "outside the canvas"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); + assert_eq!(undo_steps(&s), steps); +} + +#[test] +fn set_entire_path_replaces_points_and_keeps_closed() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0];\ + p.setEntirePath([[0, 0], [10, 0], [10, 10]]); vc.log(p.pathPoints.length); vc.log(p.closed); vc.log(p.pathPoints[2].anchor);\ + var n = app.activeDocument.pathItems.add(); vc.log(n.pathPoints.length); vc.log(n.closed);\ + n.setEntirePath([[50, 50], [60, 50]]); vc.log(n.pathPoints.length); vc.log(n.closed); vc.log(n.length);\ + n.closed = true; vc.log(n.closed);", + ); + assert_eq!(out, vec![json!(3), json!(true), json!([10, 10]), json!(0), json!(false), json!(2), json!(false), json!(10), json!(true)]); + let n = node(&s, a); + let pd = n.path_data().unwrap(); + assert_eq!(pd.subpaths.len(), 1); + assert!(pd.subpaths[0].closed); + assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); +} + +#[test] +fn hostile_set_entire_path_input_is_bounded() { + let (mut s, _, _) = doc(); + let before = art(&s); + for (source, part) in [ + ("var a = []; for (var i = 0; i < 100001; i++) a.push([i % 100, 1]); app.activeDocument.pathItems[0].setEntirePath(a);", "at most"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [NaN, 1]]);", "finite"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1]]);", "two numbers"), + ("app.activeDocument.pathItems[0].setEntirePath('0,0');", "array"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 1e13]]);", "outside the canvas"), + ( + "var o = {}; Object.defineProperty(o, 0, {get: function () { return 1; }}); app.activeDocument.pathItems[0].setEntirePath([o]);", + "two numbers", + ), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); +} + +#[test] +fn path_point_setters_edit_one_anchor() { + let (mut s, a, _) = doc(); + let anchors_before = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints, q = pp[1];\ + vc.log(pp.length); vc.log(pp.typename); vc.log(q.typename); vc.log(q.parent.typename); vc.log(q.anchor);\ + q.anchor = [45, 285]; vc.log(q.anchor); vc.log(q.leftDirection); vc.log(q.rightDirection);\ + q.rightDirection = [55, 285]; q.leftDirection = [35, 285]; vc.log(q.pointType);\ + q.pointType = PointType.SMOOTH; vc.log(q.pointType); q.pointType = PointType.CORNER; vc.log(q.pointType);\ + vc.log(pp.index(1).anchor);", + ); + assert_eq!(out[0], json!(4)); + assert_eq!(out[1], json!("PathPoints")); + assert_eq!(out[2], json!("PathPoint")); + assert_eq!(out[3], json!("PathItem")); + assert_eq!(out[5], json!([45, 285])); + assert_eq!(out[6], json!([40, 280]), "moving the anchor leaves its handles"); + assert_eq!(out[8], json!("PointType.CORNER"), "moving handles leaves the point type"); + assert_eq!(out[9], json!("PointType.SMOOTH")); + assert_eq!(out[10], json!("PointType.CORNER"), "a corner with handles in line stays a corner"); + assert_eq!(out[11], json!([45, 285])); + let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + for i in [0, 2, 3] { + assert_eq!(anchors[i], anchors_before[i], "point {i} did not change"); + } + assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints.index('a');").contains("Not found")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].pointType = 'SMOOTH';").contains("PointType")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 'x'];").contains("finite")); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints.getByName === undefined);"), vec![json!(true)]); +} + +#[test] +fn path_point_wrapper_goes_stale_after_remove() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints, last = pp[3];\ + pp[0].remove(); vc.log(pp.length); vc.log(pp[0].anchor);\ + try { last.anchor; } catch (e) { vc.log(e.message); } try { last.selected; } catch (e) { vc.log(e.message); }\ + var n = pp.add(); vc.log(pp.length); vc.log(n.anchor);\ + pp.removeAll(); vc.log(pp.length); vc.log(app.activeDocument.pathItems.length);\ + p.remove(); try { pp.length; } catch (e) { vc.log(e.message); } try { p.closed; } catch (e) { vc.log(e.message); }\ + try { p.polarity; } catch (e) { vc.log(e.message); }", + ); + assert_eq!( + out, + vec![ + json!(3), + json!([40, 280]), + json!("Stale path point"), + json!("Stale path point"), + json!(4), + json!([10, 240]), + json!(0), + json!(2), + json!("Stale page item"), + json!("Stale page item"), + json!("Stale page item") + ] + ); +} + +#[test] +fn fill_color_round_trips_rgb_cmyk_gray_lab() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); vc.log(c.typename); vc.log([c.red, c.green, c.blue]);\ + c.red = 255; c.blue = 128; p.fillColor = c; var f = p.fillColor; vc.log([f.typename, f.red, f.green, f.blue]);\ + var k = new cmykColor(); k.cyan = 10; k.black = 50; p.strokeColor = k; var t = p.strokeColor; vc.log([t.typename, t.cyan, t.black]);\ + var g = new GrayColor(); g.gray = 25; p.fillColor = g; vc.log([p.fillColor.typename, p.fillColor.gray]);\ + var l = new LabColor(); l.l = 50; l.a = -20; l.b = 30; p.strokeColor = l; vc.log([p.strokeColor.l, p.strokeColor.a, p.strokeColor.b]);", + ); + assert_eq!(out[0], json!("RGBColor")); + assert_eq!(out[1], json!([0, 0, 0])); + assert_eq!(rounded(&out[2]), json!(["RGBColor", 255, 0, 128])); + assert_eq!(rounded(&out[3]), json!(["CMYKColor", 10, 50])); + assert_eq!(rounded(&out[4]), json!(["GrayColor", 25])); + assert_eq!(rounded(&out[5]), json!([50, -20, 30])); + let n = node(&s, a); + match n.appearance.fill_paint() { + Paint::Solid { color: Color::Gray { k }, .. } => assert!((k - 0.75).abs() < 1e-6, "gray 25 is 75% black ink, got {k}"), + p => panic!("fill is {p:?}"), + } +} + +#[test] +fn no_color_unfills_and_unstrokes() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; vc.log([p.filled, p.stroked]);\ + p.fillColor = new NoColor(); p.stroked = false; vc.log([p.filled, p.stroked, p.fillColor.typename]);\ + p.filled = true; vc.log(p.filled);", + ); + assert_eq!(out, vec![json!([true, true]), json!([false, false, "NoColor"]), json!(true)]); + let n = node(&s, a); + assert!(n.appearance.stroke_paint().is_none()); + assert!(!n.appearance.fill_paint().is_none()); +} + +#[test] +fn path_paint_edits_leave_new_art_and_recent_colors() { + let (mut s, _, _) = doc(); + let (paint, active, last, recent) = (s.paint.clone(), s.fill_active, s.last_solid, s.recent_colors.clone()); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7; p.strokeCap = StrokeCap.ROUNDENDCAP; p.filled = false;", + ); + assert_eq!(s.paint, paint, "the paint for new art"); + assert_eq!(s.fill_active, active); + assert_eq!(s.last_solid, last); + assert_eq!(s.recent_colors, recent); +} + +#[test] +fn compound_path_members_read_the_paint_they_are_given() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; p.fillColor = c; p.strokeWidth = 4;\ + vc.log([p.fillColor.red, p.fillColor.green, p.strokeWidth]); vc.log(app.activeDocument.pathItems[1].fillColor.red);\ + p.evenodd = true; vc.log([p.evenodd, app.activeDocument.pathItems[1].evenodd]);", + ); + assert_eq!(rounded(&out[0]), json!([200, 0, 4])); + assert_eq!(rounded(&out[1]), json!(200), "the compound path paints every member"); + assert_eq!(out[2], json!([true, true]), "the compound path holds the fill rule"); +} + +#[test] +fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() { + let (mut s, a) = doc_with_paints(); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Ink", "tint": 40})).unwrap(); + let before = node(&s, a).appearance.fill_paint(); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.fillColor.typename, p.fillColor.tint]);"); + assert_eq!(rounded(&out[0]), json!(["SpotColor", 40])); + assert!(failure(&mut s, "var p = app.activeDocument.pathItems[0]; p.fillColor = p.fillColor;").contains("SpotColor is not available yet")); + assert_eq!(node(&s, a).appearance.fill_paint(), before, "the fill stays linked to its swatch"); +} + +#[test] +fn filled_true_on_a_filled_path_runs_no_command() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.filled = true; p.stroked = true; p.fillColor = p.fillColor;\ + p.strokeWidth = p.strokeWidth; p.strokeCap = p.strokeCap; p.closed = true; p.evenodd = false; p.strokeDashes = [];\ + p.pathPoints[0].anchor = p.pathPoints[0].anchor; p.translate(0, 0); p.rotate(360); p.resize(100, 100);", + ); + assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); +} + +#[test] +fn an_added_point_follows_the_last_point_before_an_empty_subpath() { + let (mut s, a, _) = doc(); + let subpaths = json!([{"anchors": [{"x": 10, "y": 20}, {"x": 40, "y": 20}], "closed": false}, {"anchors": [], "closed": false}]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); + assert!(node(&s, a).path_data().is_some_and(|pd| pd.subpaths.len() == 2), "the empty subpath is kept"); + let out = log( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints; var n = pp.add(); vc.log(pp.length); vc.log(n.anchor); vc.log(pp[1].anchor);", + ); + assert_eq!(out[0], json!(3)); + assert_eq!(out[1], out[2], "the new point is at the last point"); +} + +#[test] +fn transforms_change_the_path_and_not_the_selected_one() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let (before_a, before_b) = (node(&s, a).geometric_bounds(), node(&s, b).geometric_bounds()); + log(&mut s, "var p = app.activeDocument.pathItems[0]; p.translate(5, 0); p.rotate(90); p.resize(50, 50);"); + assert_ne!(node(&s, a).geometric_bounds(), before_a, "the path the script named changes"); + assert_eq!(node(&s, b).geometric_bounds(), before_b, "the selected path stays"); + assert_eq!(s.active().unwrap().selection.objects, [b], "the selection stays"); +} + +#[test] +fn an_added_path_takes_new_art_without_a_fill_or_stroke() { + let (mut s, _, _) = doc(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + let unpainted = |s: &Session| { + let ap = s.new_art(); + matches!(ap.fill_paint(), Paint::None) && matches!(ap.stroke_paint(), Paint::None) + }; + assert!(unpainted(&s)); + let (steps, recent) = (undo_steps(&s), s.recent_colors.clone()); + let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.filled); vc.log(n.stroked); vc.log(n.pathPoints.length);"); + assert_eq!(out, [json!(false), json!(false), json!(0)]); + assert_eq!(undo_steps(&s), steps + 1, "one step for the run"); + assert!(unpainted(&s), "new art keeps no fill and no stroke"); + assert_eq!(s.recent_colors, recent); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + let out = log(&mut s, "var n = app.activeDocument.pathItems.add(); vc.log(n.filled); vc.log(n.stroked); vc.log(n.strokeColor.red);"); + assert_eq!(out, [json!(false), json!(true), json!(255)], "a new-art stroke stays"); +} + +/// [`doc`] with pattern `Dots` and spot swatch `Ink`, and path `a` with no fill or stroke. +fn doc_with_paints() -> (Session, NodeId) { + let (mut s, a, _) = doc(); + let dot = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + s.execute("object.pattern.make", &json!({"ids": [dot.0], "name": "Dots", "width": 20, "height": 20, "edit": false})).unwrap(); + s.execute("select.set", &json!({"ids": [dot.0]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#2a6fb0", "spot": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + (s, a) +} + +#[test] +fn filled_and_stroked_true_give_the_new_art_paint() { + let kinds = [ + json!({"color": "#00ff00"}), + json!({"swatch": "Ink", "tint": 40}), + json!({"gradient": {"kind": "radial", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}), + json!({"swatch": "Dots"}), + ]; + for fill in [true, false] { + for params in &kinds { + let (mut s, a) = doc_with_paints(); + s.execute(if fill { "paint.setFill" } else { "paint.setStroke" }, params).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + assert!(!matches!(want, Paint::None), "{params}: new art takes the paint"); + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + let got = if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }; + assert_eq!(crate::cmd::gradient::unplaced(&got), want, "fill {fill}, {params}"); + } + } +} + +#[test] +fn filled_true_throws_for_a_new_art_pattern_it_cannot_give() { + let placed = vectorcraft_color::Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::scale(2.0) }; + for (paint, says) in [(placed, "placement of its own"), (vectorcraft_doc::pattern::pattern_paint("Gone"), "not in this document")] { + for fill in [true, false] { + let (mut s, _) = doc_with_paints(); + if fill { + s.paint.fill = paint.clone(); + } else { + (s.paint.stroke, s.paint.stroke_width) = (paint.clone(), 1.0); + } + let (before, steps) = (art(&s), undo_steps(&s)); + let e = failure( + &mut s, + if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }, + ); + assert!(e.contains(says), "{e}"); + assert_eq!((art(&s), undo_steps(&s)), (before, steps), "nothing changes"); + } + } +} + +#[test] +fn stroke_options_map_to_stroke_set() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0];\ + p.strokeWidth = 4; p.strokeCap = StrokeCap.ROUNDENDCAP; p.strokeJoin = StrokeJoin.BEVELENDJOIN; p.strokeMiterLimit = 7;\ + p.strokeDashes = [6, 3]; p.strokeDashOffset = 2; p.evenodd = true; p.fillOverprint = true;\ + vc.log([p.strokeWidth, p.strokeCap, p.strokeJoin, p.strokeMiterLimit, p.strokeDashes, p.strokeDashOffset, p.evenodd, p.fillOverprint]);\ + p.strokeDashes = {}; vc.log(p.strokeDashes);", + ); + assert_eq!(out[0], json!([4, "StrokeCap.ROUNDENDCAP", "StrokeJoin.BEVELENDJOIN", 7, [6, 3], 2, true, true])); + assert_eq!(out[1], json!([])); + let n = node(&s, a); + let st = n.appearance.stroke().unwrap(); + assert_eq!((st.width, st.cap, st.join, st.miter_limit, st.dash.is_none()), (4.0, LineCap::Round, LineJoin::Bevel, 7.0, true)); + for (source, part) in [ + ("app.activeDocument.pathItems[0].strokeMiterLimit = 600;", "strokeMiterLimit"), + ("app.activeDocument.pathItems[0].strokeCap = 'round';", "StrokeCap"), + ("app.activeDocument.pathItems[0].strokeJoin = StrokeCap.ROUNDENDCAP;", "StrokeJoin"), + ("app.activeDocument.pathItems[0].strokeWidth = -1;", "strokeWidth"), + ("app.activeDocument.pathItems[0].strokeDashes = [0, 0];", "not 0"), + ("app.activeDocument.pathItems[0].strokeDashes = [1, -2];", "dash length"), + ("var d = []; for (var i = 0; i < 65; i++) d.push(1); app.activeDocument.pathItems[0].strokeDashes = d;", "at most 64"), + ("app.activeDocument.pathItems[0].strokeDashOffset = 3;", "strokeDashes first"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } +} + +#[test] +fn bad_color_components_throw_and_change_nothing() { + let (mut s, _, _) = doc(); + let before = art(&s); + for (source, part) in [ + ("var c = new RGBColor(); c.red = 300; app.activeDocument.pathItems[0].fillColor = c;", "RGBColor.red"), + ("var c = new CMYKColor(); c.cyan = NaN; app.activeDocument.pathItems[0].fillColor = c;", "finite"), + ("var c = new CMYKColor(); c.cyan = -1; app.activeDocument.pathItems[0].fillColor = c;", "CMYKColor.cyan"), + ("var c = new GrayColor(); c.gray = '5'; app.activeDocument.pathItems[0].fillColor = c;", "GrayColor.gray"), + ("var c = new LabColor(); c.a = 200; app.activeDocument.pathItems[0].strokeColor = c;", "LabColor.a"), + ("app.activeDocument.pathItems[0].fillColor = {typename: 'Foo'};", "color object"), + ("app.activeDocument.pathItems[0].fillColor = 5;", "color object"), + ("app.activeDocument.pathItems[0].fillColor = new GradientColor();", "not available yet"), + ("app.activeDocument.pathItems[0].strokeColor = new SpotColor();", "not available yet"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); +} + +#[test] +fn locked_paths_and_wrong_objects_are_refused() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let before = art(&s); + for (source, part) in [ + ("app.activeDocument.pathItems[0].fillColor = new NoColor();", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"), + ("app.activeDocument.pathItems[0].translate(5, 5);", "Cannot edit PathItem"), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); + s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[2]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); + assert!(e.contains("not a PathItem"), "{e}"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(PathPoint.prototype, 'anchor').get.call({});"); + assert!(e.contains("not a PathPoint"), "{e}"); +} + +#[test] +fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.setEntirePath([[100, 100], [110, 100]]);\ + n.rotate(90, true, true, true, true, Transformation.LEFT); vc.log(n.pathPoints[1].anchor);\ + n.translate(5, 10); vc.log(n.pathPoints[0].anchor);\ + var r = app.activeDocument.pathItems.rectangle(250, 10, 30, 40); r.strokeWidth = 2;\ + r.resize(200, 50, true, true, true, true, 300, Transformation.TOPLEFT); vc.log(r.geometricBounds); vc.log(r.strokeWidth);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out[0], json!([100, 110]), "a positive angle turns counterclockwise"); + assert_eq!(out[1], json!([105, 110]), "translate moves up for a positive deltaY"); + assert_eq!(out[2], json!([10, 250, 70, 230])); + assert_eq!(out[3], json!(6)); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX")); + assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("changePositions")); + let before = art(&s); + for (source, part) in [ + ("app.activeDocument.pathItems[0].translate(1, 2, true, true, false);", "changeFillGradients false"), + ("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"), + ("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"), + ( + "var ps = app.activeDocument.pathItems;\ + for (var i = 0; i < ps.length; i++) { if (ps[i].strokeWidth == 6) ps[i].resize(150, 100, true, true, true, true, 20000); }", + "more than 1000 points", + ), + ] { + let e = failure(&mut s, source); + assert!(e.contains(part), "{source}: {e}"); + } + assert_eq!(art(&s), before); +} + +#[test] +fn area_sign_follows_direction() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [10, 0], [10, 10], [0, 10]]); n.closed = true;\ + vc.log(n.area); vc.log(n.length);\ + var r = app.activeDocument.pathItems.rectangle(100, 0, 10, 10), q = app.activeDocument.pathItems.rectangle(100, 0, 10, 10, true);\ + vc.log(r.area + q.area); vc.log(Math.abs(r.area));", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out, vec![json!(-100), json!(40), json!(0), json!(100)]); +} + +#[test] +fn many_path_edits_are_one_undo_step() { + let (mut s, a, b) = doc(); + let steps = undo_steps(&s); + log( + &mut s, + "var p = app.activeDocument.pathItems, c = new RGBColor(); c.green = 200;\ + for (var i = 0; i < p.length; i++) { p[i].fillColor = c; p[i].strokeWidth = 3; p[i].pathPoints[0].anchor = [0, 0]; }", + ); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + for id in [a, b] { + assert!((node(&s, id).appearance.stroke_width() - 1.0).abs() < 1e-9); + } +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..828a97f585 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -75,7 +75,8 @@ const INSIDE: &[(&str, &str)] = &[ "", "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ - PageItems RulerUnits ZOrderMethod", + PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType PolarityValues RulerUnits StrokeCap \ + StrokeJoin Transformation ZOrderMethod", ), ("Application.", "prototype"), ( @@ -89,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= \ + groupItems groupItems= height layers layers= name pageItems parent pathItems rulerOrigin rulerOrigin= \ rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \ views views= width", ), @@ -107,6 +108,25 @@ const INSIDE: &[(&str, &str)] = &[ transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), + ("PathItems.", "prototype"), + ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"), + ("PathItem.", "prototype"), + ( + "PathItem.prototype.", + "area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \ + filled= guides length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \ + selectedPathPoints= setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \ + strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \ + strokeWidth strokeWidth= stroked stroked= translate", + ), + ("PathPoints.", "prototype"), + ("PathPoints.prototype.", "add constructor index length parent removeAll typename"), + ("PathPoint.", "prototype"), + ( + "PathPoint.prototype.", + "anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \ + rightDirection= selected selected= typename", + ), ("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"), ("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"), ("DocumentColorSpace.", "CMYK RGB"), @@ -119,14 +139,21 @@ const INSIDE: &[(&str, &str)] = &[ TransparencyGridNone TransparencyGridOrange TransparencyGridPurple TransparencyGridRed", ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), + ("PathPointSelection.", "ANCHORPOINT LEFTDIRECTION LEFTRIGHTPOINT NOSELECTION RIGHTDIRECTION"), + ("PointType.", "CORNER SMOOTH"), + ("PolarityValues.", "NEGATIVE POSITIVE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"), + ("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"), + ("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; -/// 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"; +/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`, +/// the page item types other than `PathItem`, and the color classes. +const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem DocumentPreset EnvelopeItem GradientColor GraphItem GrayColor GroupItem \ + IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \ + SymbolItem TextFrame cmykColor"; /// 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 c305916f6f..44d375ae2c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2675,7 +2675,55 @@ app through the global object `vc`, and writes to the Script Console and runs ot Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and `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`. + themselves, such as a text frame's `contents`, are not defined yet and read as `undefined`. +- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the + order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`, + `getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new + art has no fill and no stroke, the path has neither), and the shape creators + `rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15, + verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`, + `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed?)` and `star(centerX = 200, centerY = 300, + radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, + `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new + art is painted. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, + `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, + `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, + `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)` (counterclockwise for a + positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through + `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through + `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms + through `object.move`, `object.rotate` and `object.scale`. `pathPoints` + (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and + `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, + `leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `parent` and + `remove()`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 + white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes + the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` + and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. + VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is + closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner + points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and + `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point + whose index is past the end of its path throws `Stale path point`. Color components left out count as 0, `new + cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of + range throws a `RangeError` when the color is assigned, with nothing changed. Reading `fillColor` or `strokeColor` + gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a + global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new + art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the + stroke; a new-art pattern with a placement of its own, or one missing from the document, throws an error. Sizes and + radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, + `strokeWidth` 0 to 1000 points (a `changeLineWidths` that would scale it past 1000 throws), `strokeDashes` at most + 64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to + `Transformation.CENTER`. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and + `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with + `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path + that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing + changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or + shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new + art, the active Fill or Stroke proxy and Recent Colors as they were. `selectedPathPoints`, `PathPoint.selected`, + `transform`, `polarity`, the gradient stops and the document's default paint are 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..81abb83e94 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, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.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 55f615d0c92ae33ecd0ab754806a4efc5889e5d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:32:25 -0800 Subject: [PATCH 025/153] Scripts: write path point edits with one command, keep colors exact - Changes to a path's points (closed, setEntirePath, pathPoints and each PathPoint) wait in the object model and are written by one path.setAnchors before any other member or command, before another path's points change, and when the script ends. A loop over 2,000 points now runs one command and makes one undo step. A path aligned to the pixel grid is written at each change so its points read snapped. - A color component reads with the fewest decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path unchanged (RGB, CMYK, Gray and Lab, fill and stroke). - add() and the shape creators put the new path on top of the active layer whatever the drawing mode, and leave the mode as it was. - fillOverprint and strokeOverprint change the top fill or stroke only. - filled = true on a compound path member places the new-art gradient on the compound path's bounds. - An identity rotate or resize checks its arguments and runs no command, on an empty path too. - Tests for each of these, and for setAnchors reading smooth false as a corner. Docs: docs/mcp.md, docs/gaps.md, docs/roadmap.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 39 ++- crates/engine/src/script/dom/colors.rs | 21 +- crates/engine/src/script/dom/paths.rs | 288 +++++++++++++------- crates/engine/src/script/mod.rs | 24 +- crates/engine/src/tests/script_dom_paths.rs | 220 ++++++++++++++- docs/gaps.md | 7 +- docs/mcp.md | 21 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 9 files changed, 504 insertions(+), 120 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 03b236c0e1..c33b3cd47f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -88,14 +88,17 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, the point changes of a path not written yet, +/// and whether a call's own savepoint ([`atomically`]) is open. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. paths: RefCell>, + /// A path and its subpaths with the point changes the run has made to it and not written yet + /// ([`flush`]). + pending: RefCell)>>, saving: Cell, } @@ -134,15 +137,34 @@ type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. type Member = fn(&Host, &[Data]) -> Answer; +/// A member function that first writes the point changes waiting in [`State`] ([`flush`]). fn function(link: &Link, f: Member) -> HostFunction { + call(link, f, true) +} + +/// A member function of the points of a path, which reads and adds to the point changes waiting in +/// [`State`] instead of writing them first. +fn point_function(link: &Link, f: Member) -> HostFunction { + call(link, f, false) +} + +fn call(link: &Link, f: Member, flushing: bool) -> HostFunction { let l = link.clone(); Rc::new(move |a: Vec| { let h = current(&l)?; h.charge_call(16 + a.iter().map(data_size).sum::())?; + if flushing { + flush(&h)?; + } f(&h, &a) }) } +/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]). +pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { + paths::flush(h) +} + fn get(link: &Link, f: Member) -> HostMember { HostMember::Get(function(link, f)) } @@ -155,6 +177,19 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]). +fn point_get(link: &Link, f: Member) -> HostMember { + HostMember::Get(point_function(link, f)) +} + +fn point_property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: point_function(link, g), set: point_function(link, s) } +} + +fn point_method(link: &Link, f: Member) -> HostMember { + HostMember::Method(point_function(link, f)) +} + /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document, page item or path point `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 40421c5d38..34c1496054 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -45,9 +45,24 @@ fn color_object(class: &str, values: &[(&str, f64)]) -> Data { Data::Object(items) } -/// A component as the script sees it: `v` times `scale`, rounded to 4 decimals. +/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that +/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read +/// from an object gives that object the same color. +fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 { + let mut scale = 1e4; + for _ in 4..=9 { + let r = (exact * scale).round() / scale; + if back(r) == v { + return r; + } + scale *= 10.0; + } + exact +} + +/// A component stored as `v`, from 0 to 1, that the script sees times `scale`. fn shown(v: f32, scale: f64) -> f64 { - (f64::from(v) * scale * 1e4).round() / 1e4 + shown_as(f64::from(v) * scale, v, |r| unit(r, scale)) } /// The color object for a solid color. @@ -58,7 +73,7 @@ fn of_color(c: &Color) -> Data { "CMYKColor", &[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))], ), - Color::Gray { k } => color_object("GrayColor", &[("gray", shown(1.0 - k, 100.0))]), + Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]), Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]), } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ac643ce370..29b0c909be 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -6,8 +6,10 @@ //! //! A `PathPoints` object holds its path's handle, and a `PathPoint` the path's handle and the //! point's index, counted across the path's subpaths in order. Each read looks the path up again. -//! Every change runs one command (`path.setAnchors` for the geometry), inside the run's one undo -//! step, and a change that changes nothing runs no command. +//! Every change runs one command inside the run's one undo step, and a change that changes nothing +//! runs no command. Changes to the points of one path wait in the run's [`super::State`] and are +//! written together with one `path.setAnchors` ([`flush`]) before any other member, command or +//! path's points are read or changed, and when the script ends. //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside @@ -15,12 +17,14 @@ //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, throws `Cannot edit` with nothing changed. //! - A path in a compound path or compound shape reads that owner's paint, which the paint -//! commands change in its place. A paint or stroke change leaves the paint for new art, the -//! active proxy and the recent colors as they were. +//! commands change in its place, and a gradient that `filled = true` gives it is placed on that +//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and +//! the recent colors as they were. `fillOverprint` and `strokeOverprint` read and change the top +//! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` makes a path with no points on top of the active layer, painted as new art -//! is. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever +//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -28,7 +32,8 @@ //! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole //! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that //! says it is not available yet. `rotateAbout` and `scaleAbout` default to -//! `Transformation.CENTER`. +//! `Transformation.CENTER`. A transform that leaves the path where it is (`rotate(360)`, +//! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -46,8 +51,8 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, property, - this_doc, typename_of, whole, with_doc, + float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, + point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -117,14 +122,14 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path has, across its subpaths. -fn point_count(pd: &PathData) -> usize { - pd.subpaths.iter().map(|sp| sp.anchors.len()).sum() +/// How many points a path with the subpaths `subs` has. +fn point_count(subs: &[SubPath]) -> usize { + subs.iter().map(|sp| sp.anchors.len()).sum() } -/// The subpath and the place in it of point `i`. -fn locate(pd: &PathData, mut i: usize) -> Option<(usize, usize)> { - for (s, sp) in pd.subpaths.iter().enumerate() { +/// The subpath and the place in it of point `i`, among the subpaths `subs`. +fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { + for (s, sp) in subs.iter().enumerate() { if i < sp.anchors.len() { return Some((s, i)); } @@ -137,14 +142,69 @@ fn anchor_json(a: &Anchor) -> Value { json!({"x": a.p.x, "y": a.p.y, "in": [a.h_in.x, a.h_in.y], "out": [a.h_out.x, a.h_out.y], "smooth": a.kind == AnchorKind::Smooth}) } -/// Gives the path of `item` the subpaths `subs` with `path.setAnchors`, unless it has them. -fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { - let (same, ok) = read_path(h, item, |st, _, pd| (pd.subpaths == subs, editable(&st.doc, item.id)))?; - if same { - return Ok(()); +fn same_path(a: Item, b: Item) -> bool { + a.doc.uid == b.doc.uid && a.id == b.id +} + +/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. +fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result { + if let Some((waiting, subs)) = &*h.dom.pending.borrow() + && same_path(*waiting, item) + { + return Ok(f(subs)); } - if !ok { - return Err(cannot_edit(item.id)); + read_path(h, item, |_, _, pd| f(&pd.subpaths)) +} + +/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with +/// the path's other point changes until [`flush`] writes them. The first change of a path writes +/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or +/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// that is, is written at once, so that its points read as the grid snaps them. +fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { + if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() + && same_path(*waiting, item) + { + return Ok(f(subs)); + } + flush(h)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let r = f(&mut subs); + let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let d = &st.doc; + let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); + (pd.subpaths == subs, editable(d, item.id), aligned) + })?; + if !same { + if !ok { + return Err(cannot_edit(item.id)); + } + *h.dom.pending.borrow_mut() = Some((item, subs)); + if aligned { + flush(h)?; + } + } + Ok(r) +} + +/// Gives the path of `item` the subpaths `subs` ([`edit_points`]). +fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { + edit_points(h, item, |s| *s = subs) +} + +/// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless +/// the path has those points already. +pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { + let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) }; + let same = { + let s = h.session.borrow(); + let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id)); + node.and_then(|n| n.path_data()).map(|pd| pd.subpaths == subs) + }; + match same { + Some(true) => return Ok(()), + Some(false) => {} + None => return Err(HostError::Error(STALE_ITEM.into())), } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); @@ -152,7 +212,23 @@ fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::R Ok(()) } -/// Runs `id` with `params` and `ids: [item]` on the item, which must be one the user could edit. +/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape +/// when it is a member of one, since the paint commands paint that owner in its place. +fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { + d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) +} + +/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active +/// layer, then puts the drawing mode back. +fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { + let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); + let r = f(); + h.session.borrow_mut().draw_mode = kept; + r +} + +/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which +/// must be one the user could edit. /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. @@ -162,7 +238,7 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r return Err(cannot_edit(item.id)); } if let Some(o) = params.as_object_mut() { - o.insert("ids".into(), json!([item.id.0])); + o.entry("ids").or_insert_with(|| json!([item.id.0])); } keeping_paint(h, || edit_item(h, item, id, ¶ms)) } @@ -273,11 +349,11 @@ fn made_id(r: &Data) -> std::result::Result { id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc`, the selection kept, and reverses the new -/// path's direction when `reversed`. → the new path. +/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, +/// and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&command(h, id, params)?)?; + let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -426,8 +502,8 @@ fn items_star(h: &super::Host, a: &[Data]) -> Answer { make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points, from `path.create` with empty path data, painted as -/// new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open +/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with +/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open /// path is set back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; @@ -436,7 +512,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&command(h, "path.create", &json!({"d": ""}))?)?; + let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -457,14 +533,13 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer { fn path_closed(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - read_path(h, item, |_, _, pd| Data::Bool(!pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed))) + read_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.iter().all(|sp| sp.closed))) } fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - let subs = read_path(h, item, |_, _, pd| pd.subpaths.iter().map(|sp| SubPath { anchors: sp.anchors.clone(), closed }).collect())?; - write_path(h, item, subs)?; + edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -517,8 +592,9 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Range(format!("setEntirePath takes at most {MAX_POINTS} points"))); } let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::>()?; - let (f, closed) = read_path(h, item, |st, _, pd| (frame(st), !pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed)))?; - let (f, c) = (f?, h.dom.coords.get()); + let f = with_doc(h, item.doc, |_, st| frame(st))?; + let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; + let c = h.dom.coords.get(); let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; @@ -546,13 +622,7 @@ struct Look { /// since the paint commands paint that owner in its place. fn look(h: &super::Host, item: Item) -> std::result::Result { read_path(h, item, |st, n, _| { - let d = &st.doc; - let owner = d - .parent_of(item.id) - .and_then(|p| d.node(p)) - .filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()) - .unwrap_or(n); - let ap = &owner.appearance; + let ap = &paint_owner(&st.doc, item.id, n).appearance; let fill = ap.fill(); let stroke = ap.stroke(); Look { @@ -597,7 +667,8 @@ fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option) -> s /// The paint new art gets for its fill or stroke, as `paint.setFill` or `paint.setStroke` params for /// the path `item`: a solid color, linked to its global or spot swatch while the document has that -/// swatch; a gradient, a placed one moved onto the path's bounds as new art takes it; or a pattern. +/// swatch; a gradient, a placed one moved onto the bounds of the path or of the compound path or +/// compound shape whose paint it shows, as new art takes it; or a pattern. /// A fill or stroke of none gives black. A pattern that its swatch does not give as new art has it /// (its own placement, or a pattern the document does not have) throws an error. fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Result { @@ -619,7 +690,7 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { - match read_path(h, item, |_, n, _| n.geometric_bounds())? { + match read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).geometric_bounds())? { Some(b) => { ap.rebase_gradients(GraphicStyle::UNIT_BOX, b); if let Paint::Gradient(placed) = top(&ap) { @@ -827,10 +898,15 @@ fn set_overprint(h: &super::Host, a: &[Data], fill: bool) -> Answer { let (item, look) = this_look(h, a)?; let (now, paint) = if fill { (look.fill_overprint, &look.fill) } else { (look.stroke_overprint, &look.stroke) }; if now != on { - if paint.is_none() { + // The top fill or stroke of the object `look` reads, as `item` names it to the command. + let top = read_path(h, item, |st, n, _| { + let owner = paint_owner(&st.doc, item.id, n); + owner.appearance.items.iter().rposition(|i| i.is_fill() == fill).map(|index| (owner.id, index)) + })?; + let (Some((owner, index)), false) = (top, paint.is_none()) else { return Err(HostError::Error(format!("the path has no {key} to overprint"))); - } - edit_path(h, item, "object.setOverprint", json!({key: on}))?; + }; + edit_path(h, item, "object.setOverprint", json!({key: on, "item": index, "ids": [owner.0]}))?; } Ok(Data::Undefined) } @@ -845,16 +921,23 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { // ---- PathItem transforms ---- -/// The point of the path's geometric bounds `r`, in document coordinates, that a `Transformation` -/// value names (left out: the center). -fn about(h: &super::Host, item: Item, d: &Data, r: Rect) -> std::result::Result { +/// The member of `Transformation` that `d` names (left out: `CENTER`). +fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> { let name = match d { Data::Undefined => "Transformation.CENTER", Data::String(s) => s.as_str(), _ => return Err(HostError::Type("give a Transformation value".into())), }; + let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m); + let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m)); + member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into())) +} + +/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation` +/// member `name` ([`about_name`]) names. +fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result { let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); - Ok(match name.strip_prefix("Transformation.").unwrap_or("") { + Ok(match name { "CENTER" => Point::new(cx, cy), "TOP" => Point::new(cx, r.y0), "BOTTOM" => Point::new(cx, r.y1), @@ -914,11 +997,13 @@ fn path_translate(h: &super::Host, a: &[Data]) -> Answer { fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { let angle = number(arg(a, 1), "angle")?; let item = this_path(h, a)?; - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, arg(a, 6), r)?; - let mut params = json!({"angle": angle, "origin": [origin.x, origin.y]}); + let place = about_name(arg(a, 6))?; + let mut params = json!({"angle": angle}); transform_options(a, 2, &mut params)?; if angle.rem_euclid(360.0) != 0.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.rotate", params)?; } Ok(Data::Undefined) @@ -937,9 +1022,8 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); } let item = this_path(h, a)?; - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, arg(a, 8), r)?; - let mut params = json!({"sx": sx, "sy": sy, "origin": [origin.x, origin.y], "basis": "page", "strokes": false}); + let place = about_name(arg(a, 8))?; + let mut params = json!({"sx": sx, "sy": sy, "basis": "page", "strokes": false}); transform_options(a, 3, &mut params)?; let width = look(h, item)?.width; let new_width = widths.map(|w| width * w / 100.0); @@ -947,6 +1031,9 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } if sx != 100.0 || sy != 100.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.scale", params)?; } if let Some(w) = new_width @@ -967,7 +1054,7 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_path(h, item, |_, _, pd| num(float(point_count(pd) as u64))) + read_points(h, item, |subs| num(float(point_count(subs) as u64))) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -984,7 +1071,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; 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) }; - let n = read_path(h, item, |_, _, pd| point_count(pd))?; + let n = read_points(h, item, point_count)?; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1001,22 +1088,19 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; - let (mut subs, n, origin) = read_path(h, item, |st, _, pd| { - let origin = frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0])); - (pd.subpaths.clone(), point_count(pd), origin) - })?; + let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); + let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } - let p = match subs.iter().rev().find_map(|sp| sp.anchors.last()) { - Some(last) => last.p, + let p = match last { + Some(p) => p, None => origin?, }; - match subs.last_mut() { + edit_points(h, item, |subs| match subs.last_mut() { Some(sp) => sp.anchors.push(Anchor::corner(p)), None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), - } - write_path(h, item, subs)?; + })?; Ok(point_ref(h, item, n)) } @@ -1034,7 +1118,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It let [run, uid, high, low, i] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; let item = path_at(h, *run, *uid, *high, *low)?; let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_path(h, item, |_, _, pd| point_count(pd))?; + let n = read_points(h, item, point_count)?; if i >= n { return Err(HostError::Error(STALE_POINT.into())); } @@ -1045,9 +1129,9 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { let (item, i) = this_point(h, a)?; let c = h.dom.coords.get(); - read_path(h, item, |st, _, pd| { - let fr = frame(st)?; - let anchor = locate(pd, i).and_then(|(s, j)| pd.subpaths.get(s).and_then(|sp| sp.anchors.get(j))); + let fr = with_doc(h, item.doc, |_, st| frame(st))?; + read_points(h, item, |subs| { + let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1056,12 +1140,13 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, i) = this_point(h, a)?; - let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; - let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { - f(an); - } - write_path(h, item, subs)?; + edit_points(h, item, |subs| { + if let Some((s, j)) = locate(subs, i) + && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) + { + f(an); + } + })?; Ok(Data::Undefined) } @@ -1121,15 +1206,16 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; - let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - if let Some(sp) = subs.get_mut(s) { - sp.anchors.remove(j); - if sp.anchors.is_empty() { - subs.remove(s); + edit_points(h, item, |subs| { + if let Some((s, j)) = locate(subs, i) + && let Some(sp) = subs.get_mut(s) + { + sp.anchors.remove(j); + if sp.anchors.is_empty() { + subs.remove(s); + } } - } - write_path(h, item, subs)?; + })?; Ok(Data::Undefined) } @@ -1138,14 +1224,14 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { /// The members `PathItem` adds to `PageItem`'s. pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> { let mut m = named(vec![ - ("pathPoints", get(l, path_points)), - ("closed", property(l, path_closed, path_set_closed)), + ("pathPoints", point_get(l, path_points)), + ("closed", point_property(l, path_closed, path_set_closed)), ("evenodd", property(l, path_evenodd, path_set_evenodd)), ("area", get(l, path_area)), ("length", get(l, path_length)), ("guides", get(l, path_guides)), ("clipping", get(l, path_clipping)), - ("setEntirePath", method(l, path_set_entire)), + ("setEntirePath", point_method(l, path_set_entire)), ("filled", property(l, path_filled, path_set_filled)), ("fillColor", property(l, path_fill_color, path_set_fill_color)), ("fillOverprint", property(l, path_fill_overprint, path_set_fill_overprint)), @@ -1193,13 +1279,13 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", typename_of("PathPoints")), - ("length", get(l, points_length)), - ("parent", get(l, points_parent)), - ("index", method(l, points_index)), - ("add", method(l, points_add)), - ("removeAll", method(l, points_remove_all)), + ("length", point_get(l, points_length)), + ("parent", point_get(l, points_parent)), + ("index", point_method(l, points_index)), + ("add", point_method(l, points_add)), + ("removeAll", point_method(l, points_remove_all)), ]), - Some(super::function(l, points_at)), + Some(super::point_function(l, points_at)), ), class( "PathPoint", @@ -1207,12 +1293,12 @@ pub(super) fn classes(l: &Link) -> Vec { { let mut m = named(vec![ ("typename", typename_of("PathPoint")), - ("parent", get(l, pt_parent)), - ("anchor", property(l, pt_anchor, pt_set_anchor)), - ("leftDirection", property(l, pt_left, pt_set_left)), - ("rightDirection", property(l, pt_right, pt_set_right)), - ("pointType", property(l, pt_type, pt_set_type)), - ("remove", method(l, pt_remove)), + ("parent", point_get(l, pt_parent)), + ("anchor", point_property(l, pt_anchor, pt_set_anchor)), + ("leftDirection", point_property(l, pt_left, pt_set_left)), + ("rightDirection", point_property(l, pt_right, pt_set_right)), + ("pointType", point_property(l, pt_type, pt_set_type)), + ("remove", point_method(l, pt_remove)), ]); m.push(later(l, "PathPoint", "selected")); m diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..37c4b8711d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1309,6 +1309,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { + // Point changes that wait in the object model are written before any command runs. + dom::flush(host)?; let id = id.to_string(); let params = params.clone(); let session = host.session.clone(); @@ -1352,6 +1354,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( /// 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 { + dom::flush(host)?; let s = host.session.borrow(); let Some(st) = s.active() else { return Ok(Data::Null) }; let ids: Vec = st.selection.objects.iter().take(1_000).map(|i| i.0).collect(); @@ -2472,6 +2475,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result std::result::Result RunError { + let message = match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m, + HostError::Marked { error, .. } => return end_flush_error(*error), + HostError::Wait => "a host function waited for its result where the run cannot pause".into(), + }; + RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false } +} + /// Tests: removes the session's running job while the session keeps its hold on it. → whether a /// job was removed. #[cfg(test)] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 9d9c0c5f7a..004c02f4fc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -344,13 +344,229 @@ fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() { fn filled_true_on_a_filled_path_runs_no_command() { let (mut s, _, _) = doc(); let steps = undo_steps(&s); - log( + let r = run( &mut s, "var p = app.activeDocument.pathItems[0]; p.filled = true; p.stroked = true; p.fillColor = p.fillColor;\ p.strokeWidth = p.strokeWidth; p.strokeCap = p.strokeCap; p.closed = true; p.evenodd = false; p.strokeDashes = [];\ p.pathPoints[0].anchor = p.pathPoints[0].anchor; p.translate(0, 0); p.rotate(360); p.resize(100, 100);", - ); + ) + .unwrap(); assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + assert_eq!(r["slowestCommands"], json!([]), "and run no command"); +} + +#[test] +fn identity_transforms_of_an_empty_path_do_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.rotate(360); n.rotate(0, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(100, 100); n.resize(100, 100, true, true, true, true, 100, Transformation.BOTTOM); n.translate(0, 0);", + ); + for source in [ + "app.activeDocument.pathItems[0].rotate(360, true, true, true, true, 'CENTER');", + "app.activeDocument.pathItems[0].resize(100, 100, true, true, true, true, 100, 'x');", + ] { + assert!(failure(&mut s, source).contains("Transformation"), "{source}"); + } +} + +/// The paint of the fill (`fill`) or stroke of `id`. +fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { + let n = node(s, id); + if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() } +} + +#[test] +fn a_color_read_from_a_path_assigns_back_unchanged() { + let colors = [ + "var c = new RGBColor(); c.red = 0.00001; c.green = 200.123456789; c.blue = 1 / 3;", + "var c = new CMYKColor(); c.cyan = 100 / 3; c.magenta = 0.00001; c.yellow = 99.99999; c.black = 12.3456789;", + "var c = new GrayColor(); c.gray = 100 / 3;", + "var c = new GrayColor(); c.gray = 99.99999;", + "var c = new LabColor(); c.l = 12.3456789; c.a = -0.00001; c.b = 127.99999;", + ]; + for color in colors { + for prop in ["fillColor", "strokeColor"] { + let (mut s, a, _) = doc(); + log(&mut s, &format!("{color} app.activeDocument.pathItems[0].{prop} = c;")); + let (before, steps) = (paint_of(&s, a, prop == "fillColor"), undo_steps(&s)); + let r = run(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.{prop} = p.{prop};")).unwrap(); + assert_eq!(paint_of(&s, a, prop == "fillColor"), before, "{color} {prop}"); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "{color} {prop}"); + } + } + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 0.5; p.fillColor = c;\ + var g = new GrayColor(); g.gray = 25; p.strokeColor = g; vc.log([p.fillColor.red, p.fillColor.green, p.strokeColor.gray]);", + ); + assert_eq!(out, vec![json!([200, 0.5, 25])], "whole and short values read as they were given"); +} + +#[test] +fn many_point_edits_run_one_command() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let anchors: Vec = (0..2000).map(|i| json!({"x": f64::from(i) * 0.1, "y": 100})).collect(); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let r = run( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ + for (var i = 0; i < pp.length; i++) { var a = pp[i].anchor; pp[i].rightDirection = [a[0] + 1, a[1]]; pp[i].anchor = [a[0], a[1] + 5]; }\ + vc.log(pp[1999].anchor); vc.log(pp[1999].rightDirection); pp[0].remove(); vc.log(pp.length); vc.log(p.pathPoints[0].anchor);", + ) + .unwrap(); + let out: Vec = r["log"].as_array().unwrap().iter().map(rounded).collect(); + assert_eq!(out, vec![json!([199.9, 205]), json!([200.9, 200]), json!(1999), json!([0.1, 205])]); + assert_eq!( + r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), + Some(vec![(json!("path.setAnchors"), json!(1))]), + "one command writes every point" + ); + let pd = node(&s, id).path_data().unwrap().clone(); + assert_eq!(pd.subpaths[0].anchors.len(), 1999); + assert!(pd.subpaths[0].anchors.iter().all(|a| (a.h_out.x - a.p.x - 1.0).abs() < 1e-9 && (a.h_out.y - a.p.y - 5.0).abs() < 1e-9)); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn point_edits_are_written_before_the_next_other_member_reads() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ + p.pathPoints[0].anchor = [0, 300]; vc.log(p.geometricBounds); q.pathPoints[0].anchor = [90, 210];\ + p.pathPoints[1].anchor = [50, 300]; vc.log(q.geometricBounds); vc.log(p.geometricBounds);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out, vec![json!([0, 300, 40, 240]), json!([90, 210, 150, 150]), json!([0, 300, 50, 240])]); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, vectorcraft_geom::Point::new(50.0, 0.0)); +} + +#[test] +fn closed_and_set_entire_path_join_the_point_edits_in_one_command() { + let (mut s, a, _) = doc(); + let r = run( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 300], [40, 300], [40, 240]]); p.closed = false;\ + p.pathPoints[1].anchor = [50, 300]; vc.log(p.closed); p.closed = true; p.setEntirePath([[0, 300], [60, 300], [60, 240]]); vc.log(p.closed);", + ) + .unwrap(); + assert_eq!(r["log"], json!([false, true])); + assert_eq!( + r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), + Some(vec![(json!("path.setAnchors"), json!(1))]), + "one command writes every change" + ); + let pd = node(&s, a).path_data().unwrap().clone(); + assert!(pd.subpaths[0].closed); + assert_eq!(pd.subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(), vec![(0.0, 0.0), (60.0, 0.0), (60.0, 60.0)]); +} + +#[test] +fn point_edits_of_a_pixel_aligned_path_read_as_the_grid_snaps_them() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[10.3, 280.3], [40.3, 280.3], [40.3, 240.3], [10.3, 240.3]]);\ + vc.log(p.pathPoints[0].anchor); p.pathPoints[1].anchor = [40.4, 280.3]; vc.log(p.pathPoints[1].anchor);", + ); + let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + let stored = |i: usize| rounded(&json!([anchors[i].p.x, 300.0 - anchors[i].p.y])); + assert_ne!(rounded(&out[0]), json!([10.3, 280.3]), "the grid moves the point"); + assert_eq!((rounded(&out[0]), rounded(&out[1])), (stored(0), stored(1)), "points read as the path has them"); +} + +#[test] +fn added_paths_go_on_top_of_the_layer_whatever_the_drawing_mode() { + for mode in ["behind", "inside"] { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let drawing = s.draw_mode; + log( + &mut s, + "var d = app.activeDocument; d.pathItems.add().name = 'n'; d.pathItems.rectangle(10, 10, 5, 5).name = 'r';\ + d.pathItems.roundedRectangle(10, 10, 5, 5).name = 'q';", + ); + let st = s.active().unwrap(); + let children = st.doc.layers[0].children().unwrap(); + let names: Vec> = children.iter().rev().take(3).map(|c| c.name.as_deref()).collect(); + assert_eq!(names, [Some("q"), Some("r"), Some("n")], "{mode}: the new paths are on top of the layer"); + assert_eq!(s.draw_mode, drawing, "{mode}: the drawing mode stays"); + } +} + +#[test] +fn overprint_changes_the_top_fill_or_stroke_only() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.addStroke", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.fillOverprint = true; p.strokeOverprint = true; vc.log([p.fillOverprint, p.strokeOverprint]);", + ); + assert_eq!(out, vec![json!([true, true])]); + let items = node(&s, a).appearance.items.clone(); + for fill in [true, false] { + let flags: Vec = items.iter().filter(|i| i.is_fill() == fill).map(|i| i.overprint()).collect(); + assert!(flags.len() >= 2, "{flags:?}"); + let (top, lower) = flags.split_last().unwrap(); + assert!(*top && lower.iter().all(|f| !f), "fill {fill}: only the top row overprints: {flags:?}"); + } +} + +#[test] +fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() { + for member in 0..2 { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "stops": stops}})).unwrap(); + if let Paint::Gradient(g) = &mut s.paint.fill { + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(0.0, 0.5), + end: vectorcraft_geom::Point::new(1.0, 0.5), + aspect: 1.0, + focal: None, + }); + } + log(&mut s, &format!("app.activeDocument.pathItems[{member}].filled = true;")); + let b = node(&s, compound).geometric_bounds().unwrap(); + let Paint::Gradient(g) = node(&s, compound).appearance.fill_paint() else { panic!("member {member}: the compound has a gradient") }; + let geom = g.geom.unwrap(); + assert!((geom.start.x - b.x0).abs() < 1e-6 && (geom.end.x - b.x1).abs() < 1e-6, "member {member}: {geom:?} spans {b:?}"); + } +} + +#[test] +fn set_anchors_reads_smooth_false_as_a_corner() { + let (mut s, a, _) = doc(); + let anchor = |smooth: Value| { + let mut v = json!({"x": 20, "y": 20, "in": [10, 20], "out": [30, 20]}); + if !smooth.is_null() { + v["smooth"] = smooth; + } + v + }; + for (smooth, kind, read) in [(json!(false), AnchorKind::Corner, "PointType.CORNER"), (Value::Null, AnchorKind::Smooth, "PointType.SMOOTH")] { + let subpaths = json!([{"anchors": [anchor(smooth.clone()), {"x": 60, "y": 20}], "closed": false}]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[0].kind, kind, "smooth {smooth}"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].pointType);"), vec![json!(read)], "smooth {smooth}"); + } } #[test] diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..d8184b1a9b 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, type, the selected path + points, gradient stops 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, and `Document.pathItems` + makes paths and reads and changes their points, colors, stroke options and transforms. 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 44d375ae2c..6c5e64789d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2685,7 +2685,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed?)` and `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new - art is painted. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing + mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, @@ -2693,7 +2694,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms - through `object.move`, `object.rotate` and `object.scale`. `pathPoints` + through `object.move`, `object.rotate` and `object.scale`. Changes to the points of a path (`closed`, + `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the + script uses any other member or command, or the points of another path, and when the script ends; a path aligned + to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. + `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, `leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `parent` and @@ -2708,15 +2713,19 @@ app through the global object `vc`, and writes to the Script Console and runs ot `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point whose index is past the end of its path throws `Stale path point`. Color components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of - range throws a `RangeError` when the color is assigned, with nothing changed. Reading `fillColor` or `strokeColor` - gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a + range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest + decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it + was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the - stroke; a new-art pattern with a placement of its own, or one missing from the document, throws an error. Sizes and + stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. + `fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, `strokeWidth` 0 to 1000 points (a `changeLineWidths` that would scale it past 1000 throws), `strokeDashes` at most 64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to - `Transformation.CENTER`. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and + `Transformation.CENTER`. A transform that leaves the path where it is, such as `rotate(360)` or + `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..28192e13b9 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, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, type, the selected path points, gradient stops 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 81abb83e94..72ed713051 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, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.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 1548547fc1cc9579cf89bca212c29dbcfa0aaf09 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:42:22 -0800 Subject: [PATCH 026/153] Scripts: ask before keeping a run whose last point changes pass the growth allowance Point changes a script leaves waiting are written when its script ends. When that write went past the growth allowance in a run that can ask, the run was kept at once without asking. The run now waits with its script finished: Continue keeps it, and Stop puts every document back as a stopped run does. --- crates/engine/src/script/mod.rs | 69 ++++++++++++++++++++------- crates/engine/src/tests/script_run.rs | 50 ++++++++++++++++++- 2 files changed, 101 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 37c4b8711d..82d013e076 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1093,6 +1093,8 @@ struct Job { name: String, /// The file-access scope `script.run` came in, which every slice runs in. scope: crate::file_access::ScopeHandle, + /// The script has ended, and the run waits for the person's growth answer before it is kept. + finished: bool, } /// The `Data` for a JSON value, within `limits`. When it does not fit, the error is the place in @@ -1888,7 +1890,7 @@ impl Session { if h.waiting.replace(false) { h.continues.set(h.continues.get() + 1); h.allowance_objects.set(h.allowance_objects.get().saturating_add(growth_objects())); - h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(GROWTH_BYTES)); + h.allowance_bytes.set(h.allowance_bytes.get().saturating_add(growth_bytes())); } }); } @@ -2026,7 +2028,7 @@ impl Session { bytes_kept: Cell::new(0), bridge: Cell::new(0), allowance_objects: Cell::new(growth_objects()), - allowance_bytes: Cell::new(GROWTH_BYTES), + allowance_bytes: Cell::new(growth_bytes()), continues: Cell::new(0), waiting: Cell::new(false), log: RefCell::new(Vec::new()), @@ -2130,7 +2132,7 @@ impl Session { } let scope = crate::file_access::ScopeHandle::capture(); let (run, line_name) = (host.run, host.name.clone()); - let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope }; + let job = Job { realm, host, link, engine, world: World::working(self), start_uids: open, name: name.clone(), scope, finished: false }; let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed); JOBS.with(|jobs| jobs.borrow_mut().insert(id, job)); self.script_key = Some(JobKey { id, run, name: line_name }); @@ -2159,6 +2161,17 @@ impl Session { self.script_key = Some(key); return None; } + // A run whose script ended past its growth allowance is kept once the person lets it go on, + // and put back when they stop it. + if job.finished { + if self.script_stop.is_set() { + let kind = LimitKind::Interrupted; + let e = + RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; + return Some(self.script_failed(job, &e)); + } + return Some(self.script_ended(job)); + } // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. if job.realm.waits() { let kind = LimitKind::Interrupted; @@ -2178,24 +2191,35 @@ impl Session { self.script_key = Some(key); None } - Ok(Ok(Progress::Done(_))) if job.host.dialogs.unused() > 0 => { - let n = job.host.dialogs.unused(); - let kind = LimitKind::Host; - let message = if n == 1 { - format!("`answers` has {n} answer the script did not use") - } else { - format!("`answers` has {n} answers the script did not use") - }; - Some(self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false })) - } - Ok(Ok(Progress::Done(_))) => { - let r = self.script_commit(job); - self.trim_histories(); - Some(r) + // The point changes written as the script ended went past the growth allowance. + Ok(Ok(Progress::Done(_))) if job.host.waiting.get() => { + job.finished = true; + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + None } + Ok(Ok(Progress::Done(_))) => Some(self.script_ended(job)), } } + /// Ends the run whose script has ended: it fails when answers it was given went unused, and is + /// kept otherwise. + fn script_ended(&mut self, job: Job) -> Result { + let n = job.host.dialogs.unused(); + if n > 0 { + let kind = LimitKind::Host; + let message = if n == 1 { + format!("`answers` has {n} answer the script did not use") + } else { + format!("`answers` has {n} answers the script did not use") + }; + return self.script_failed(job, &RunError { kind: RunErrorKind::Limit(kind), message, line: 0, column: 0, authored: false }); + } + let r = self.script_commit(job); + self.trim_histories(); + r + } + fn script_failed(&mut self, job: Job, e: &RunError) -> Result { job.host.dialogs.stopped(); job.host.disk.borrow_mut().picker = None; @@ -2531,6 +2555,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The bytes of new document data a run may keep before it is asked to continue or stop. +fn growth_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_GROWTH_BYTES.with(Cell::get) { + return n; + } + GROWTH_BYTES +} + /// The limits of a command's result on its way to the script. fn result_limits() -> DataLimits { #[cfg(test)] @@ -2548,6 +2581,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the bytes a run may keep in place of [`GROWTH_BYTES`]. + pub(crate) static TEST_GROWTH_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 02176c38c9..48f4aa02f9 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -5,7 +5,7 @@ use std::cell::Cell; use serde_json::{Value, json}; -use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_RESULT_BYTES}; +use crate::script::{PANIC_IN_SLICE, TEST_GROWTH, TEST_GROWTH_BYTES, TEST_RESULT_BYTES}; use crate::*; fn rect(x: i64) -> Value { @@ -1020,6 +1020,54 @@ fn a_person_can_let_a_growing_run_go_on_or_stop_it() { assert_eq!(state(&s), before); } +#[test] +fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() { + // The point change waits in the object model until the script ends. + let source = "app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, -4];"; + let mut s = two_docs(); + let start = s.documents()[1].doc.clone(); + assert_eq!(run(&mut s, source).unwrap()["ok"], true); + let added = start.retained_bytes_each(&s.documents()[1].doc).1 as u64; + assert!(added >= 3, "{added}"); + // The change goes past this allowance and stays within twice it. + TEST_GROWTH_BYTES.with(|g| g.set(Some(added * 2 / 3))); + let run_to_the_question = |s: &mut Session| { + s.script_frames = true; + run(s, source).unwrap(); + for _ in 0..1_000 { + if s.script_waiting() { + break; + } + assert!(s.script_pump().is_none()); + } + assert!(s.script_waiting()); + assert!(s.script_pump().is_none()); + assert!(s.script_running()); + }; + let mut s = two_docs(); + let before = state(&s); + let undo = s.documents()[1].history.undo.len(); + run_to_the_question(&mut s); + assert_eq!(state(&s), before); + s.script_continue(); + assert!(!s.script_waiting()); + let done = s.script_pump().expect("the run ends once it may go on"); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(s.documents()[1].history.undo.len(), undo + 1); + assert_ne!(state(&s), before); + + let mut s = two_docs(); + let before = state(&s); + run_to_the_question(&mut s); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + let ended = s.script_pump().expect("a stopped run ends"); + TEST_GROWTH_BYTES.with(|g| g.set(None)); + assert!(ended.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "stopped"); + assert!(!s.script_running()); + assert_eq!(state(&s), before); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); From 07d673898f156ffa517319b02cb3cc3a97966697 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:14:52 -0800 Subject: [PATCH 027/153] Scripts: a path point read before its path's points are removed is stale A PathPoint kept its index, so after `remove()` of an earlier point it read and changed the point that moved into its place. A point read before the script removed a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`) now throws `Stale path point`. --- crates/engine/src/script/dom.rs | 6 +++- crates/engine/src/script/dom/paths.rs | 33 +++++++++++++++++---- crates/engine/src/tests/script_dom_paths.rs | 26 ++++++++++++++++ docs/mcp.md | 4 ++- 4 files changed, 62 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 456d9d88b1..2e09f8cb5d 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -89,7 +89,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, the point changes of a path not written yet, -/// and whether a call's own savepoint ([`atomically`]) is open. +/// how many times it removed or replaced each path's points, and whether a call's own savepoint +/// ([`atomically`]) is open. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -99,6 +100,9 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, + /// How many times the run has removed or replaced points of each path, by document uid and + /// path id ([`paths`]). + point_cuts: RefCell>, saving: Cell, } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 29b0c909be..44c2304b38 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -28,7 +28,9 @@ //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. -//! - A point whose index is past the end of its path throws `Stale path point`. +//! - A point whose index is past the end of its path throws `Stale path point`, and so does a +//! point read before the run removed a point of its path or replaced its points +//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`). //! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole //! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that //! says it is not available yet. `rotateAbout` and `scaleAbout` default to @@ -56,7 +58,8 @@ use super::{ }; use crate::{DocState, NodeId, NodeKind}; -/// The error of a point whose index is past the end of its path. +/// The error of a point whose index is past the end of its path, or that was read before the run +/// removed or replaced points of its path. pub const STALE_POINT: &str = "Stale path point"; /// The most points `setEntirePath` takes. pub const MAX_POINTS: usize = 100_000; @@ -598,6 +601,7 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; + cut_points(h, item); Ok(Data::Undefined) } @@ -1064,7 +1068,20 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer { fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { let [high, low] = id_parts(item.id); - host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64)]) + host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) +} + +/// How many times the run has removed or replaced points of `item`. +fn point_cuts(h: &super::Host, item: Item) -> u64 { + h.dom.point_cuts.borrow().get(&(item.doc.uid, item.id.0)).copied().unwrap_or(0) +} + +/// Notes that the run removed or replaced points of `item`, which makes the points read before +/// stale. +fn cut_points(h: &super::Host, item: Item) { + let mut cuts = h.dom.point_cuts.borrow_mut(); + let n = cuts.entry((item.doc.uid, item.id.0)).or_insert(0); + *n = n.saturating_add(1); } fn points_at(h: &super::Host, a: &[Data]) -> Answer { @@ -1107,16 +1124,21 @@ fn points_add(h: &super::Host, a: &[Data]) -> Answer { fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; write_path(h, item, Vec::new())?; + cut_points(h, item); Ok(Data::Undefined) } // ---- PathPoint ---- -/// The path and the index of the point `this` names, which must still be in the path. +/// The path and the index of the point `this` names, which must still be in the path, with no +/// point of the path removed or replaced since `this` was read. pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) }; - let [run, uid, high, low, i] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; + let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; let item = path_at(h, *run, *uid, *high, *low)?; + if whole(*cuts) != Some(point_cuts(h, item)) { + return Err(HostError::Error(STALE_POINT.into())); + } let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; let n = read_points(h, item, point_count)?; if i >= n { @@ -1216,6 +1238,7 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { } } })?; + cut_points(h, item); Ok(Data::Undefined) } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 004c02f4fc..5aff4e48d1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -258,6 +258,32 @@ fn path_point_wrapper_goes_stale_after_remove() { ); } +#[test] +fn points_read_before_a_removal_or_replacement_go_stale() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ + var second = p.pathPoints[1], other = q.pathPoints[1]; p.pathPoints[0].remove();\ + try { second.anchor = [0, 0]; } catch (e) { vc.log(e.message); } try { second.anchor; } catch (e) { vc.log(e.message); }\ + vc.log(other.anchor); var first = p.pathPoints[0]; vc.log(first.anchor);\ + p.setEntirePath([[1, 1], [2, 2], [3, 3]]); try { first.anchor; } catch (e) { vc.log(e.message); }\ + var again = p.pathPoints[0]; vc.log(again.anchor); p.pathPoints.removeAll(); try { again.anchor; } catch (e) { vc.log(e.message); }", + ); + assert_eq!( + out, + vec![ + json!("Stale path point"), + json!("Stale path point"), + json!([150, 200]), + json!([40, 280]), + json!("Stale path point"), + json!([1, 1]), + json!("Stale path point") + ] + ); +} + #[test] fn fill_color_round_trips_rgb_cmyk_gray_lab() { let (mut s, a, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 7d1ff6defe..4b82232fb6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2715,7 +2715,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point - whose index is past the end of its path throws `Stale path point`. Color components left out count as 0, `new + whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed + a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`). Color components left out + count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it From bd945697e8088dc8e167787b7b91d183b7003465 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:06:28 -0800 Subject: [PATCH 028/153] Scripts: a path point read before a command changes its path is stale A PathPoint read before vc.run('path.setAnchors', ...) replaced its path's points stayed valid, so a later write changed the replacement's point at the same index. The object model now keeps each path whose points the script read and checks it after every command and when a point is used. When the path's points differ from the ones it last saw, or the path is gone, the points read before throw `Stale path point`. This covers any command run with vc.run, an undo, and a change that a later command reverses. Points stay valid through the object model's own changes to the path or to an object that holds it, such as translate(). docs/mcp.md and the module doc state the rule. --- crates/engine/src/script/dom.rs | 32 ++++-- crates/engine/src/script/dom/paths.rs | 106 +++++++++++++++++++- crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests/script_dom_paths.rs | 38 +++++++ docs/mcp.md | 5 +- 5 files changed, 173 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 2e09f8cb5d..dd47eb00f3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -89,8 +89,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's /// page items, kept while that document is unchanged, the point changes of a path not written yet, -/// how many times it removed or replaced each path's points, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// how many times each path's points went stale and each path as the run last saw its points, and +/// whether a call's own savepoint ([`atomically`]) is open. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -100,9 +100,18 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, - /// How many times the run has removed or replaced points of each path, by document uid and - /// path id ([`paths`]). + /// How many times the points the run read of each path went stale, by document uid and path id + /// ([`paths`]). point_cuts: RefCell>, + /// Each path whose points the run read, as the run last saw it, by document uid and path id + /// ([`paths`]). + point_nodes: RefCell>>, + /// Each document, by uid, as it was when the run last looked at all the paths in it whose + /// points it read ([`paths`]). + point_docs: RefCell>>, + /// The item the object model is changing ([`edit_item`]), whose points stay valid through the + /// change. + editing: Cell>, saving: Cell, } @@ -169,6 +178,12 @@ pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { paths::flush(h) } +/// Notes the changes a command made to the points of the paths the run has read +/// ([`paths::see_all_points`]). +pub(super) fn see_points(h: &Host) { + paths::see_all_points(h) +} + fn get(link: &Link, f: Member) -> HostMember { HostMember::Get(function(link, f)) } @@ -621,9 +636,14 @@ fn on_doc( Ok(v) } -/// Runs `id` with `params` on the item's document, its selection kept. +/// Runs `id` with `params` on the item's document, its selection kept. The points the run read of +/// the item's paths stay valid through the change ([`paths::see_all_points`]). 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)) + paths::see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = on_doc(h, item.doc.uid, true, |h| command(h, id, params)); + h.dom.editing.set(kept); + r } /// Reads the document of `doc` with `f`. diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 44c2304b38..32401db1d0 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -30,7 +30,10 @@ //! Removing the last points leaves the path, with no points. //! - A point whose index is past the end of its path throws `Stale path point`, and so does a //! point read before the run removed a point of its path or replaced its points -//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`). +//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`), or before anything other +//! than the object model changed the path's points (a command run with `vc.run`, such as +//! `path.setAnchors`, `object.move` or `edit.undo`). Points stay valid through the object +//! model's other changes to the path or to an object that holds it, such as `translate()`. //! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole //! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that //! says it is not available yet. `rotateAbout` and `scaleAbout` default to @@ -41,6 +44,7 @@ //! so `changeFillGradients` false throws an error that says it is not available yet. use std::rc::Rc; +use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; @@ -1071,19 +1075,113 @@ fn point_ref(h: &super::Host, item: Item, i: usize) -> Data { host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))]) } -/// How many times the run has removed or replaced points of `item`. +/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change +/// made to them since the run last saw them. fn point_cuts(h: &super::Host, item: Item) -> u64 { - h.dom.point_cuts.borrow().get(&(item.doc.uid, item.id.0)).copied().unwrap_or(0) + let key = (item.doc.uid, item.id.0); + see_points(h, key, || false); + h.dom.point_cuts.borrow().get(&key).copied().unwrap_or(0) } /// Notes that the run removed or replaced points of `item`, which makes the points read before /// stale. fn cut_points(h: &super::Host, item: Item) { + cut_key(h, (item.doc.uid, item.id.0)); +} + +/// [`cut_points`] for the path of document uid and path id `key`. +fn cut_key(h: &super::Host, key: (u64, u64)) { let mut cuts = h.dom.point_cuts.borrow_mut(); - let n = cuts.entry((item.doc.uid, item.id.0)).or_insert(0); + let n = cuts.entry(key).or_insert(0); *n = n.saturating_add(1); } +/// The node of `id` in `d`, as the document holds it. +fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc> { + let at = d.index_path(id)?; + let (first, rest) = at.split_first()?; + let mut cur = d.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur) +} + +/// Keeps the path of document uid and path id `key` as it is now, the first time the run reads its +/// points and after each later look. When its points differ from the ones the run last saw, the +/// points read before go stale, unless `own`: the object model made the change +/// ([`see_all_points`]), which `own` is asked only after a change. The kept node is shared with +/// the document, so a node whose pointer is unchanged has unchanged points, and any change to it +/// makes a new node. +fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) { + let node = { + let s = h.session.borrow(); + s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned()) + }; + // A path that is gone makes its points stale, so that an undo that brings it back leaves them + // stale. + let Some(node) = node else { + if h.dom.point_nodes.borrow_mut().remove(&key).is_some() { + cut_key(h, key); + } + return; + }; + let changed = match h.dom.point_nodes.borrow_mut().insert(key, node.clone()) { + Some(old) => !Arc::ptr_eq(&old, &node) && old.path_data().map(|pd| &pd.subpaths) != node.path_data().map(|pd| &pd.subpaths), + None => false, + }; + if changed && !own() { + cut_key(h, key); + } +} + +/// [`see_points`] for each path whose points the run has read, after each command, so that a +/// change that a later command reverses still makes the points stale. Paths under the object that +/// the object model is changing ([`super::State`]), or that object itself, take the change as the +/// object model's own, and their points stay valid. A document that is the one the run last looked +/// at is skipped, as are its paths. +pub(super) fn see_all_points(h: &super::Host) { + let keys: Vec<(u64, u64)> = { + let seen = h.dom.point_nodes.borrow(); + if seen.is_empty() { + return; + } + let s = h.session.borrow(); + let mut docs = h.dom.point_docs.borrow_mut(); + // The documents that changed since the last look, kept as they are now. + let mut changed = std::collections::HashSet::new(); + for (uid, _) in seen.keys() { + if changed.contains(uid) { + continue; + } + match s.documents().iter().find(|d| d.uid == *uid) { + Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => {} + Some(st) => { + docs.insert(*uid, st.doc.clone()); + changed.insert(*uid); + } + None => { + docs.remove(uid); + changed.insert(*uid); + } + } + } + seen.keys().copied().filter(|(uid, _)| changed.contains(uid)).collect() + }; + let editing = h.dom.editing.get(); + for (uid, id) in keys { + let own = || match editing { + Some(e) if e.doc.uid == uid => { + let s = h.session.borrow(); + let id = NodeId(id); + id == e.id || s.documents().iter().find(|d| d.uid == uid).and_then(|st| st.doc.ancestry(id)).is_some_and(|a| a.contains(&e.id)) + } + _ => false, + }; + see_points(h, (uid, id), own); + } +} + fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 82d013e076..3019b147b8 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1350,6 +1350,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + if crossed.is_ok() { + dom::see_points(host); + } crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 5aff4e48d1..2dbf3263b9 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -284,6 +284,44 @@ fn points_read_before_a_removal_or_replacement_go_stale() { ); } +#[test] +fn points_read_before_a_command_changes_the_path_go_stale() { + let (mut s, a, _) = doc(); + let source = format!( + "function A(x, y) {{ return {{x: x, y: y, in: [x, y], out: [x, y], smooth: false}}; }}\ + var p = app.activeDocument.pathItems[0], id = {id}, first = p.pathPoints[1];\ + vc.run('path.setAnchors', {{id: id, subpaths: [{{anchors: [A(0, 0), A(20, 0), A(20, 20), A(0, 20)], closed: true}}]}});\ + try {{ first.anchor = [1, 1]; }} catch (e) {{ vc.log(e.message); }} try {{ first.anchor; }} catch (e) {{ vc.log(e.message); }}\ + var second = p.pathPoints[1]; vc.log(second.anchor);\ + vc.run('stroke.set', {{ids: [id], weight: 3}}); vc.log(second.anchor);\ + p.translate(5, 0); vc.log(second.anchor);\ + vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); try {{ second.anchor; }} catch (e) {{ vc.log(e.message); }}\ + var third = p.pathPoints[1]; vc.log(third.anchor);\ + vc.run('object.move', {{ids: [id], dx: 5, dy: 0}}); vc.run('edit.undo');\ + try {{ third.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);\ + var fourth = p.pathPoints[1]; vc.run('edit.clear', {{ids: [id]}}); vc.run('edit.undo');\ + try {{ fourth.anchor; }} catch (e) {{ vc.log(e.message); }} vc.log(p.pathPoints.length);", + id = a.0 + ); + let out = log(&mut s, &source); + assert_eq!( + out, + vec![ + json!("Stale path point"), + json!("Stale path point"), + json!([20, 300]), + json!([20, 300]), + json!([25, 300]), + json!("Stale path point"), + json!([30, 300]), + json!("Stale path point"), + json!(4), + json!("Stale path point"), + json!(4) + ] + ); +} + #[test] fn fill_color_round_trips_rgb_cmyk_gray_lab() { let (mut s, a, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 4b82232fb6..9371a4857d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2716,7 +2716,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed - a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`). Color components left out + a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other + than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, + `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an + object that holds it, such as `translate()`. Color components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest From bb931b5df738740dfe129c5eb4e6df5e96ba6802 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:23:50 -0800 Subject: [PATCH 029/153] Scripts: file.new rejects rows that are not a whole number from 1 to 1000 artboardLayout.rows rounded a fractional count and lowered a count over 1000 to 1000, so file.new made a different grid from the one asked for. It now throws for both, and docs/mcp.md states the range. --- crates/engine/src/cmd/newdoc.rs | 18 +++++++++++++++--- crates/engine/src/tests/newdoc.rs | 2 ++ crates/engine/src/tests/script_dom.rs | 2 +- docs/mcp.md | 2 +- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..ee2767d1df 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -371,12 +371,24 @@ impl DocSettings { return Ok(()); } let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; - let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32); for (k, v) in o { match k.as_str() { "layout" => self.layout = v.as_str().and_then(ArtboardLayout::parse).ok_or_else(bad_layout)?, - "columns" => self.columns = count(v).ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))?, - "rows" => self.rows = count(v).ok_or_else(|| bad(cmd, "artboardLayout.rows must be 1 or more"))?, + "columns" => { + self.columns = v + .as_f64() + .filter(|c| c.is_finite() && *c >= 1.0) + .ok_or_else(|| bad(cmd, "artboardLayout.columns must be 1 or more"))? + .round() + .min(MAX_ARTBOARDS as f64) as u32 + } + "rows" => { + self.rows = v + .as_f64() + .filter(|r| r.fract() == 0.0 && (1.0..=MAX_ARTBOARDS as f64).contains(r)) + .map(|r| r as u32) + .ok_or_else(|| bad(cmd, format!("artboardLayout.rows must be a whole number from 1 to {MAX_ARTBOARDS}")))? + } "spacing" => { self.spacing = v .as_f64() diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index edf27aaf2a..a438430379 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -161,6 +161,8 @@ fn ppi_overprint_preview_and_bad_params() { json!({"artboardLayout": {"layout": "spiral"}}), json!({"artboardLayout": {"columns": 0}}), json!({"artboardLayout": {"rows": 0}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1.5}}), + json!({"artboardLayout": {"layout": "gridByColumn", "rows": 1001}}), json!({"artboardLayout": {"tiles": 2}}), json!({"units": "furlongs"}), json!({"width": 160000, "artboards": 1000}), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 774ff2b165..e1288b233c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -483,7 +483,7 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { assert_eq!((by_row.rows, by_row.to_json()["artboardLayout"].get("rows")), (0, None), "{layout}"); } let e = s.execute("file.new", &json!({"artboardLayout": {"layout": "gridByColumn", "rows": 0}})).unwrap_err().to_string(); - assert!(e.contains("rows must be 1 or more"), "{e}"); + assert!(e.contains("rows must be a whole number from 1 to 1000"), "{e}"); for layout in ["gridByRow", "row", "column"] { let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); diff --git a/docs/mcp.md b/docs/mcp.md index 9371a4857d..3b2ec0f6b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8918,7 +8918,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, -rows, spacing, rightToLeft}` (`rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is +rows, spacing, rightToLeft}` (`rows`, a whole number from 1 to 1000, gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes), From 74fefce46fdeaf76acb857d58f0bce7f77b71ba8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:50:26 -0800 Subject: [PATCH 030/153] Scripts: assigning selected keeps other objects' direct-selected anchors Setting a page item's `selected` rebuilt the selection with select.set, which selects every object whole, so the direct-selected anchors and segments of the other selected objects were lost. When another object has some, the selection is now rebuilt the way an edit restores it, with only the item added or removed. --- crates/engine/src/script/dom.rs | 22 +++++++++++++++++++++- crates/engine/src/tests/script_dom.rs | 15 +++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index dd47eb00f3..6544309c8c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1373,7 +1373,27 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer { } else { ids.retain(|i| *i != item.id); } - set_selection(h, item.doc, ids) + // The direct-selected anchors and segments of the other objects stay selected. + let partial = with_doc(h, item.doc, |_, st| { + let sel = &st.selection; + let plain = sel.target.is_none() && sel.symbol_part.is_none() && sel.on_path_member.is_none() && sel.slices.is_empty(); + (plain && ids.iter().any(|i| sel.anchors.contains_key(i) || sel.segments.contains_key(i))).then(|| { + let mut next = sel.clone(); + next.objects.clone_from(&ids); + next.anchors.retain(|i, _| ids.contains(i)); + next.segments.retain(|i, _| ids.contains(i)); + next.key = next.key.filter(|k| ids.contains(k)); + next.key_anchor = next.key_anchor.filter(|(k, _)| ids.contains(k)); + (st.doc.clone(), next) + }) + }); + match partial { + Some((doc, next)) => { + on_doc(h, item.doc.uid, false, |h| restore_selection(h, &doc, &next))?; + Ok(Data::Undefined) + } + None => set_selection(h, item.doc, ids), + } } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index e1288b233c..36a06aa78e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -536,6 +536,21 @@ fn an_edit_keeps_direct_selected_anchors() { assert!(s.journal.iter().any(|(id, _)| id == "select.anchorsMany"), "the journal holds the restore"); } +#[test] +fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.clone(); + assert!(anchors.contains_key(&a)); + log(&mut s, "app.activeDocument.pageItems[1].selected = false;"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone())); + log(&mut s, "app.activeDocument.pageItems[1].selected = true;"); + let sel = &s.active().unwrap().selection; + assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a))); +} + #[test] fn an_edit_keeps_the_order_of_a_mixed_selection() { let (mut s, a, b) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 3b2ec0f6b1..e59fa68b9d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2672,7 +2672,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + nothing changed. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other + selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, From 98535b70d478342c341e616e1c8988db22ce26db Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:07:39 -0800 Subject: [PATCH 031/153] 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 3de7547b2ab56ea255bb068212cc5b9c545ab3dd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:44:50 -0800 Subject: [PATCH 032/153] Clean Up: remove hairline slivers thinner than a set width Object > Path > Clean Up gets a Hairline Slivers option, off by default, with a Sliver Width (0.001 to 3 pt, 0.03 mm by default). It removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle that wide fits anywhere inside their fill: shapes that look like single lines in Outline view but have almost no area. Select > Object > Hairline Slivers... selects the objects Clean Up would remove, only inside the isolated group while one is isolated. - vectorcraft-pathops: thinner_than measures the largest circle that fits in a fill. Bounds, the area against the outline length, and the width of the convex hull settle most shapes; the rest go through a cell search on the path's edges and then on the resolved outline. thinner_than_within takes the search's work from a budget, and one budget covers a whole document, so a run over thousands of shapes ends in bounded time. - Shapes too complex to measure, and shapes still unmeasured when the budget runs out, are kept, and the reply's warning counts them. - A compound path is measured as one fill. Hidden, locked and template objects, art on locked artboards, guides, the clipping paths of groups and layers, and the members of live and generated art are left alone. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/pathops.rs | 162 ++++- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/select.rs | 28 + crates/engine/src/lib.rs | 2 +- crates/engine/src/tests/pathops.rs | 308 ++++++++++ crates/pathops/src/boolean.rs | 2 +- crates/pathops/src/lib.rs | 2 + crates/pathops/src/thickness.rs | 557 ++++++++++++++++++ crates/ui-egui/src/dialogs/command.rs | 15 +- crates/ui-egui/src/menus/tree.rs | 13 +- docs/mcp.md | 18 + docs/target-app-parity.md | 1 + 12 files changed, 1099 insertions(+), 10 deletions(-) create mode 100644 crates/pathops/src/thickness.rs diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 1793f17d5c..a3eaf08567 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -8,7 +8,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::BlendMode; use vectorcraft_doc::appearance::{AppearanceItem, StrokeLayer}; -use vectorcraft_doc::{AnchorRef, Appearance, Document, Node, NodeId, NodeKind, SegmentRef, TextObject}; +use vectorcraft_doc::{AnchorRef, Appearance, Document, LockedArtboards, Node, NodeId, NodeKind, SegmentRef, TextObject}; use vectorcraft_geom::{FillRule, PathData, SubPath}; use vectorcraft_pathops as po; use vectorcraft_pathops::{BoolOp, PathfinderOp}; @@ -190,7 +190,7 @@ pub fn specs() -> Vec { "Clean Up…", ["Object", "Path"], None, - "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true} → {removed}", + "{strayPoints?: true, unpaintedObjects?: true, emptyTextPaths?: true, hairlineSlivers?: false (closed paths and compound paths outside template layers with a visible fill, no visible stroke and no effect, whose fill no circle `sliverWidth` across fits inside; a compound path counts as one object, and guides, the clipping paths of groups and layers and the members of live and generated art stay), sliverWidth?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} remove them from the visible, unlocked objects (not those on a locked artboard), as one undo step → {removed, warning?: how many shapes hairlineSlivers could not measure (too complex, or past the run's limit of work) and left as they are}", has_doc, clean_up ), @@ -1662,12 +1662,150 @@ fn is_painted(a: &Appearance) -> bool { }) } +/// Hairline Slivers' width by default, in points: 0.03 mm, VectorCraft's own value. +pub const HAIRLINE_SLIVER_WIDTH: f64 = 0.03 * 72.0 / 25.4; +/// The widths Hairline Slivers takes, in points. +pub const HAIRLINE_SLIVER_WIDTH_RANGE: std::ops::RangeInclusive = 0.001..=3.0; + +/// The Hairline Slivers width `p` gives as `key` (by default [`HAIRLINE_SLIVER_WIDTH`]; a string +/// with a unit reads too): an error when it is not a distance in [`HAIRLINE_SLIVER_WIDTH_RANGE`]. +pub(crate) fn sliver_width(p: &Value, key: &str, cmd: &str) -> Result { + let w = length_given(p, key, cmd)?.unwrap_or(HAIRLINE_SLIVER_WIDTH); + if !HAIRLINE_SLIVER_WIDTH_RANGE.contains(&w) { + let (lo, hi) = (HAIRLINE_SLIVER_WIDTH_RANGE.start(), HAIRLINE_SLIVER_WIDTH_RANGE.end()); + return Err(bad(cmd, format!("`{key}` must be from {lo} to {hi} pt"))); + } + Ok(w) +} + +/// Hairline Slivers: is `n` a path or compound path (not a guide or clipping path) whose subpaths +/// are all closed, with a visible fill, no visible stroke and no effect (on the object or on a fill or stroke), +/// whose fill no circle `width` across fits inside? A compound path is measured as one fill. +/// `None` when the fill can't be measured with what is left of `budget` ([`po::thinner_than_within`]). +/// A hidden member of a compound path is measured too, since the compound path paints it. +fn is_hairline_sliver(n: &Node, width: f64, budget: &mut po::ThicknessBudget) -> Option { + // A shape with no fill that paints is left to Unpainted Objects. + if !n.appearance.has_drawn_fill() || draws_beyond_its_fill(&n.appearance) { + return Some(false); + } + let (subpaths, rule): (Vec<&SubPath>, FillRule) = match &n.kind { + NodeKind::Path { path, rule, guide: false, clipping: false, .. } => (path.subpaths.iter().collect(), *rule), + NodeKind::Compound { children, rule } => { + let mut all = vec![]; + for c in children { + let NodeKind::Path { path, guide: false, .. } = &c.kind else { return Some(false) }; + all.extend(path.subpaths.iter()); + } + (all, *rule) + } + _ => return Some(false), + }; + // Paths of one anchor are stray points, and open paths are lines. + if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed || sp.anchors.len() < 2) { + return Some(false); + } + po::thinner_than_within(&PathData::new(subpaths.into_iter().cloned().collect()), rule, width, budget) +} + +/// Does `a` paint anything beyond the fill of the geometry it is on: a stroke that draws, or an +/// effect on the object or on one of its fills and strokes? +fn draws_beyond_its_fill(a: &Appearance) -> bool { + a.has_drawn_stroke() || !a.effects.is_empty() || a.items.iter().any(|i| !i.effects().is_empty()) +} + +/// A group that stands for live or generated art (Live Paint, a graph, a dimension, a flare, a +/// tracing result, objects on a path, a compound shape, type's glyph outlines, the pieces a clipping +/// path paints and the like), as Artwork Cleanup's checks find most of them: Hairline Slivers +/// leaves its members alone. +fn holds_generated_art(n: &Node) -> bool { + let e = n.extras(); + vectorcraft_tools::builder::is_live_paint(n) + || e.type_outlines + || e.clip_pieces + || e.graph.is_some() + || e.shaper.is_some() + || e.dimension.is_some() + || e.flare.is_some() + || e.trace.is_some() + || e.objects_on_path.is_some() + || e.live_paint_gaps.is_some() + || e.compound_shape +} + +/// The objects Hairline Slivers finds in `d` for `width`. +pub(crate) struct Slivers { + pub ids: Vec, + /// Closed paths and compound paths whose fill couldn't be measured, which are left as they are. + pub unmeasured: Vec, +} + +/// The status-bar warning for `count` shapes Hairline Slivers couldn't measure, when there are any. +pub(crate) fn unmeasured_warning(count: usize) -> Option { + (count > 0).then(|| { + format!( + "Hairline Slivers: {count} shapes could not be measured (too complex, or past the limit of work for one run) and were left as they are" + ) + }) +} + +/// The hairline slivers ([`is_hairline_sliver`]) among the visible, unlocked objects of `d` (not +/// those on a locked artboard or in a template layer) for which `within` holds, in the layers and +/// groups of the whole document. A compound path counts as one object. The clipping paths of groups +/// and layers (and all of a clipping group used as one), the members of live and generated art, and +/// the members of groups and layers whose own stroke or effect paints them are left out. +pub(crate) fn hairline_slivers(d: &Document, width: f64, within: &dyn Fn(NodeId) -> bool) -> Slivers { + struct Walk<'a> { + width: f64, + locks: LockedArtboards<'a>, + within: &'a dyn Fn(NodeId) -> bool, + // One budget for the whole document, so that thousands of shapes that need a search take + // a bounded time; the shapes after it runs out count as unmeasured. + budget: po::ThicknessBudget, + out: Vec<(NodeId, Option)>, + } + fn visit(n: &Node, clip_path: bool, w: &mut Walk<'_>) { + if !n.visible || n.locked || n.is_template() || clip_path { + return; + } + match &n.kind { + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => { + if holds_generated_art(n) || draws_beyond_its_fill(&n.appearance) { + return; + } + let clips = n.clips(); + for (i, c) in children.iter().enumerate() { + visit(c, clips && i == 0, w); + } + } + // Art on a locked artboard, or outside `within`, is left out before it is measured. + NodeKind::Path { .. } | NodeKind::Compound { .. } if !w.locks.holds_id(n.id) && (w.within)(n.id) => { + match is_hairline_sliver(n, w.width, &mut w.budget) { + Some(false) => {} + found => w.out.push((n.id, found)), + } + } + _ => {} + } + } + let mut w = Walk { width, locks: d.locked_artboards(), within, budget: po::ThicknessBudget::document(), out: vec![] }; + for l in &d.layers { + visit(l, false, &mut w); + } + let mut found = w.out; + let editable = d.editable(); + found.retain(|(id, _)| editable(*id)); + let (sure, unsure): (Vec<_>, Vec<_>) = found.into_iter().partition(|(_, f)| f.is_some()); + Slivers { ids: sure.into_iter().map(|(id, _)| id).collect(), unmeasured: unsure.into_iter().map(|(id, _)| id).collect() } +} + fn clean_up(s: &mut Session, p: &Value) -> Result { const C: &str = "object.path.cleanUp"; let stray = switch_or(p, "strayPoints", true, C)?; let unpainted = switch_or(p, "unpaintedObjects", true, C)?; let empty_text = switch_or(p, "emptyTextPaths", true, C)?; - let found = { + let slivers = switch_or(p, "hairlineSlivers", false, C)?; + let width = sliver_width(p, "sliverWidth", C)?; + let (found, warning) = { let d = &s.doc()?.doc; let mut v = vec![]; fn visit(n: &Node, parent_compound: bool, parent_clip: bool, first: bool, v: &mut Vec, opts: (bool, bool, bool)) { @@ -1709,10 +1847,22 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } let editable = d.editable(); v.retain(|id| editable(*id)); - v + let mut warning = None; + if slivers { + let found = hairline_slivers(d, width, &|_| true); + let listed: BTreeSet = v.iter().copied().collect(); + // A shape another option removes isn't left as it is. + warning = unmeasured_warning(found.unmeasured.iter().filter(|id| !listed.contains(id)).count()); + v.extend(found.ids.into_iter().filter(|id| !listed.contains(id))); + } + (v, warning) + }; + let reply = |removed: usize| match &warning { + Some(w) => json!({ "removed": removed, "warning": w }), + None => json!({ "removed": removed }), }; if found.is_empty() { - return Ok(json!({ "removed": 0 })); + return Ok(reply(0)); } s.edit("Clean Up", |d, _| { let mut gone = Beside::replacing(d, &found); @@ -1723,7 +1873,7 @@ fn clean_up(s: &mut Session, p: &Value) -> Result { } gone.finish(d) })?; - Ok(json!({ "removed": found.len() })) + Ok(reply(found.len())) } // ---------- Divide Objects Below ---------- diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..0d6afae1c5 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -529,6 +529,7 @@ pub(super) const ALLOWED: &[&str] = &[ "select.object.brushStrokes", "select.object.clippingMasks", "select.object.directionHandles", + "select.object.hairlineSlivers", "select.object.notAlignedToPixelGrid", "select.object.pointText", "select.object.slices", diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index b7a6043a98..6379762535 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -9,6 +9,7 @@ use vectorcraft_tools::builder::is_live_paint; use super::object::can_align; use super::panelcmds::artboard_at; +use super::pathops::{hairline_slivers, sliver_width, unmeasured_warning}; use super::wand::{fill_of, stroke_of}; use super::{ CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index_opt, ok, str_param, @@ -196,6 +197,15 @@ pub fn specs() -> Vec { cmd!("select.object.strayPoints", "Stray Points", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| p.anchor_count() == 1))), + cmd!( + "select.object.hairlineSlivers", + "Hairline Slivers…", + ["Select", "Object"], + None, + "{width?: pt 0.001..3 (0.03 mm, VectorCraft's own default)} select, in the document or inside the isolated group, the closed paths and compound paths that object.path.cleanUp's hairlineSlivers removes with this sliverWidth: a visible fill, no visible stroke, no effect, and no circle `width` across fits inside the fill; a compound path counts as one object, and hidden and locked objects, template layers, clipping paths, guides and the members of live and generated art are left out → {count, warning?: how many shapes could not be measured (too complex, or past the run's limit of work) and were left out}", + has_doc, + select_hairline_slivers + ), cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n .path_data() .is_some_and(|p| !p.is_closed()))), @@ -1423,6 +1433,24 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result { Ok(json!({ "count": s.doc()?.selection.objects.len() })) } +/// Select › Object › Hairline Slivers: the objects Clean Up's Hairline Slivers removes +/// ([`hairline_slivers`]), inside the isolated group while one is isolated. +fn select_hairline_slivers(s: &mut Session, p: &Value) -> Result { + const C: &str = "select.object.hairlineSlivers"; + let width = sliver_width(p, "width", C)?; + let st = s.doc()?; + let (d, iso) = (&st.doc, st.isolation); + let locks = d.locked_artboards(); + let found = hairline_slivers(d, width, &|id| is_selectable(d, iso, &locks, id)); + let warning = unmeasured_warning(found.unmeasured.len()); + s.select(|_, sel| sel.set(found.ids))?; + let count = s.doc()?.selection.objects.len(); + Ok(match warning { + Some(w) => json!({ "count": count, "warning": w }), + None => json!({ "count": count }), + }) +} + /// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned /// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk /// does not look at the paths inside it. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..fafcf7e943 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -32,7 +32,7 @@ pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::flare::flare_settings; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; -pub use cmd::pathops::auto_simplify_level; +pub use cmd::pathops::{HAIRLINE_SLIVER_WIDTH, HAIRLINE_SLIVER_WIDTH_RANGE, auto_simplify_level}; pub use cmd::rasterfx::{export_pdf, flatten_raster_effects}; pub use cmd::select::{path_fingerprint, storable_selection, stored_path_params, stored_path_step}; pub use cmd::textwrap::TEXT_WRAP_OFFSET_RANGE; diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index 60f223334c..be57671884 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1066,6 +1066,314 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// A path drawn by `d`, filled black with no stroke. +fn filled(s: &mut Session, d: &str) -> NodeId { + let id = NodeId(s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()); + fill_only(s, id); + id +} + +fn fill_only(s: &mut Session, id: NodeId) { + s.edit("t", |d, _| { + d.node_mut(id).unwrap().appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0).into(); + Ok(()) + }) + .unwrap(); +} + +/// Hairline Slivers' test art: (the slivers, the shapes with a width). +fn sliver_art(s: &mut Session) -> (Vec, Vec) { + // A triangle whose third anchor lies 0.002 pt from its first: diagonal, so its bounds are wide + // and tall. A long one across the page. A compound path of two slivers. + let triangle = filled(s, "M10 10 L50 40 L10.001 10.0015 Z"); + let long = filled(s, "M20 500 L780 20 L20.0005 500.001 Z"); + let a = filled(s, "M300 300 L340 330 L300.001 300.0015 Z"); + let b = filled(s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let two = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, two); + // Kept: a diagonal strip 0.2 pt across (0.07 mm), a dot 0.3 pt round, a stroked sliver (it + // draws a line), an open path, and a compound path of a sliver and a square. + let strip = filled(s, "M100 100 L180 160 L180.12 159.84 L100.12 99.84 Z"); + let dot = NodeId(s.execute("shape.ellipse", &json!({"x": 400, "y": 400, "width": 0.3, "height": 0.3})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, dot); + let stroked = filled(s, "M200 10 L240 40 L200.001 10.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(stroked).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 1.0).into(); + Ok(()) + }) + .unwrap(); + let open = filled(s, "M500 10 L540 40 L500.001 10.0015"); + let c = filled(s, "M600 300 L640 330 L600.001 300.0015 Z"); + let square = filled(s, "M600 400 L620 400 L620 420 L600 420 Z"); + s.execute("select.set", &json!({"ids": [c.0, square.0]})).unwrap(); + let mixed = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + fill_only(s, mixed); + s.execute("select.none", &json!({})).unwrap(); + (vec![triangle, long, two], vec![strip, dot, stroked, open, mixed]) +} + +#[test] +fn clean_up_removes_hairline_slivers_and_keeps_shapes_with_a_width() { + let mut s = session(); + let (slivers, kept) = sliver_art(&mut s); + // Off by default. + assert_eq!(s.execute("object.path.cleanUp", &json!({})).unwrap()["removed"], 0); + // A sliver with no fill and no stroke is Unpainted Objects' to remove, and one whose fill is + // at 0 % opacity paints nothing either. + let unpainted = filled(&mut s, "M700 10 L740 40 L700.001 10.0015 Z"); + let clear = filled(&mut s, "M700 60 L740 90 L700.001 60.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(unpainted).unwrap().appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into(); + let mut a = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 0.0)), Paint::None, 0.0); + if let Some(vectorcraft_doc::AppearanceItem::Fill(f)) = a.items.first_mut() { + f.opacity = 0.0; + } + d.node_mut(clear).unwrap().appearance = a.into(); + Ok(()) + }) + .unwrap(); + let kept = [kept, vec![unpainted, clear]].concat(); + let undo = s.doc().unwrap().history.undo.len(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(slivers.iter().all(|id| d.node(*id).is_none()), "slivers left"); + for (k, id) in kept.iter().enumerate() { + assert!(d.node(*id).is_some(), "shape {k} with a width went"); + } + assert_eq!(r["removed"], slivers.len()); + // One undo step brings every sliver back. + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(slivers.iter().all(|id| s.doc().unwrap().doc.node(*id).is_some())); + // A wider width (0.255 pt) takes the 0.2 pt strip too, and still keeps the dot. + let wide = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": "0.09 mm"}); + assert_eq!(s.execute("object.path.cleanUp", &wide).unwrap()["removed"], slivers.len() + 1); + assert!(s.doc().unwrap().doc.node(kept[0]).is_none() && s.doc().unwrap().doc.node(kept[1]).is_some()); +} + +/// Select › Object › Hairline Slivers selects what Clean Up removes, and neither takes hidden or +/// locked slivers. +#[test] +fn select_hairline_slivers_selects_what_clean_up_removes() { + let mut s = session(); + let (slivers, _) = sliver_art(&mut s); + let hidden = filled(&mut s, "M10 200 L50 230 L10.001 200.0015 Z"); + let locked = filled(&mut s, "M10 250 L50 280 L10.001 250.0015 Z"); + s.edit("t", |d, _| { + d.node_mut(hidden).unwrap().visible = false; + d.node_mut(locked).unwrap().locked = true; + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], slivers.len()); + let mut selected: Vec = s.doc().unwrap().selection.objects.to_vec(); + selected.sort_unstable(); + let mut want = slivers.clone(); + want.sort_unstable(); + assert_eq!(selected, want); + // Inside an isolated group, only the slivers in it are selected. + let inner = filled(&mut s, "M10 300 L50 330 L10.001 300.0015 Z"); + let square = filled(&mut s, "M100 300 L120 300 L120 320 L100 320 Z"); + s.execute("select.set", &json!({"ids": [inner.0, square.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + // A sliver in a group is selected as Clean Up finds it. + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], slivers.len() + 1); + assert!(s.doc().unwrap().selection.objects.contains(&inner)); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 1); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![inner]); + s.execute("object.exitIsolation", &json!({})).unwrap(); + // A template layer that was unlocked afterward. + let template = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let traced = filled(&mut s, "M10 350 L50 380 L10.001 350.0015 Z"); + s.edit("t", |d, _| { + let n = d.node_mut(template).unwrap(); + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = true; + } + n.locked = false; + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(template).unwrap().is_template()); + s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert!(!s.doc().unwrap().selection.objects.contains(&traced)); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(hidden).is_some() && d.node(locked).is_some() && d.node(traced).is_some()); +} + +/// Hairline Slivers leaves alone a sliver with an effect on its fill, the members of a Live Paint +/// group and of type's glyph outlines, a sliver that its group's stroke draws along, and a layer's +/// clipping path; Clean Up's other options keep the layer's clipping path too. +#[test] +fn hairline_slivers_leave_effects_live_paint_and_clipping_layers_alone() { + let mut s = session(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let rough = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.execute("select.set", &json!({"ids": [rough.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 0})).unwrap(); + let a = filled(&mut s, "M100 100 L140 130 L100.001 100.0015 Z"); + let square = filled(&mut s, "M90 90 L150 90 L150 150 L90 150 Z"); + s.execute("select.set", &json!({"ids": [a.0, square.0]})).unwrap(); + s.execute("livePaint.make", &json!({})).unwrap(); + // A group's own 5 pt stroke draws along its member. + let member = filled(&mut s, "M200 200 L240 230 L200.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [member.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(group).unwrap().appearance = Appearance::basic(Paint::None, Paint::solid(Color::rgb(0.0, 0.0, 0.0)), 5.0).into(); + Ok(()) + }) + .unwrap(); + // A thin part of type's glyph outlines. + let glyph = filled(&mut s, "M300 200 L340 230 L300.001 200.0015 Z"); + s.execute("select.set", &json!({"ids": [glyph.0]})).unwrap(); + let outlines = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + d.node_mut(outlines).unwrap().extras_mut().type_outlines = true; + Ok(()) + }) + .unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + // A layer clipped by a thin compound path: neither Hairline Slivers nor Unpainted Objects + // removes the clipping path. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M300 300 L400 300 L400 400 L300 400 Z"); + let b = filled(&mut s, "M300 300 L340 330 L300.001 300.0015 Z"); + let c = filled(&mut s, "M300 350 L340 380 L300.001 350.0015 Z"); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let clip = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(clip).is_some(), "the layer's clipping path went"); + // A clip group whose clipping path is a sliver. + let art = filled(&mut s, "M300 500 L400 500 L400 600 L300 600 Z"); + let mask = filled(&mut s, "M300 500 L340 530 L300.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [art.0, mask.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + // A guide drawn as a sliver, and a sliver with an effect on its stroke. + let guide = filled(&mut s, "M400 10 L440 40 L400.001 10.0015 Z"); + let stroke_fx = filled(&mut s, "M450 10 L490 40 L450.001 10.0015 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { guide, .. } = &mut d.node_mut(guide).unwrap().kind { + *guide = true; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [stroke_fx.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "distort.roughen", "item": 1})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(mask).is_some(), "the clip group's clipping path went"); + assert!(d.node(guide).is_some() && d.node(stroke_fx).is_some(), "a guide or a sliver with a stroke effect went"); + // A layer clipped by a group (as an opened file can have it): its sliver member clips too. + let layer = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + filled(&mut s, "M500 500 L600 500 L600 600 L500 600 Z"); + let bare = filled(&mut s, "M500 500 L540 530 L500.001 500.0015 Z"); + s.execute("select.set", &json!({"ids": [bare.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.edit("t", |d, _| { + if let NodeKind::Layer { clip, children, .. } = &mut d.node_mut(layer).unwrap().kind { + *clip = true; + let i = children.iter().position(|c| c.id == g).unwrap(); + let c = children.remove(i); + children.insert(0, c); + } + Ok(()) + }) + .unwrap(); + assert!(s.doc().unwrap().doc.node(layer).unwrap().clips()); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + s.execute("object.path.cleanUp", &only).unwrap(); + assert!(s.doc().unwrap().doc.node(bare).is_some(), "the clipping group's member went"); +} + +/// A sliver on a locked artboard is left alone. +#[test] +fn hairline_slivers_leave_art_on_a_locked_artboard_alone() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + s.edit("t", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + assert_eq!(s.execute("select.object.hairlineSlivers", &json!({})).unwrap()["count"], 0); + assert_eq!(s.execute("object.path.cleanUp", &only).unwrap()["removed"], 0); + assert!(s.doc().unwrap().doc.node(sliver).is_some()); +} + +/// A shape too complex to measure is kept, and both commands say how many there were. +#[test] +fn hairline_slivers_keep_shapes_too_complex_to_measure_and_count_them() { + let mut s = session(); + let sliver = filled(&mut s, "M10 10 L50 40 L10.001 10.0015 Z"); + // A closed zigzag of more anchors than one shape is measured with. + let n = vectorcraft_pathops::MAX_THICKNESS_PIECES + 1; + let anchors = (0..n).map(|k| vectorcraft_geom::Anchor::corner(kurbo::Point::new(100.0 + k as f64 * 0.001, 100.0 + (k % 2) as f64))).collect(); + let huge = filled(&mut s, "M100 100 L110 100 L110 110 Z"); + s.edit("t", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(huge).unwrap().kind { + *path = PathData::single(vectorcraft_geom::SubPath::new(anchors, true)); + } + Ok(()) + }) + .unwrap(); + let r = s.execute("select.object.hairlineSlivers", &json!({})).unwrap(); + assert_eq!(r["count"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let only = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true}); + let r = s.execute("object.path.cleanUp", &only).unwrap(); + assert_eq!(r["removed"], 1); + assert!(r["warning"].as_str().is_some_and(|w| w.contains('1')), "{r}"); + let d = &s.doc().unwrap().doc; + assert!(d.node(sliver).is_none() && d.node(huge).is_some()); +} + +/// The width of Hairline Slivers is refused outside 0.001 to 3 pt, or when it is no number, and the +/// document, the selection and the undo history stay as they were. +#[test] +fn hairline_slivers_refuse_a_width_out_of_range() { + let mut s = session(); + sliver_art(&mut s); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + for w in [json!(0), json!(-1), json!(0.0005), json!(3.5), json!("thin"), json!(true)] { + for (cmd, key) in [("object.path.cleanUp", "sliverWidth"), ("select.object.hairlineSlivers", "width")] { + let mut p = serde_json::Map::new(); + p.insert(key.into(), w.clone()); + if cmd == "object.path.cleanUp" { + p.insert("hairlineSlivers".into(), json!(true)); + } + let r = s.execute(cmd, &Value::Object(p)); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(key)), "{cmd} {w}: {r:?}"); + assert!(state(&s) == before, "{cmd} {w} changed the document"); + } + } + // Both ends of the range are taken. + for w in [json!(0.001), json!(3), json!("3 pt")] { + assert!(s.execute("select.object.hairlineSlivers", &json!({ "width": w })).is_ok(), "{w}"); + let p = json!({"strayPoints": false, "unpaintedObjects": false, "emptyTextPaths": false, "hairlineSlivers": true, "sliverWidth": w}); + assert!(s.execute("object.path.cleanUp", &p).is_ok(), "{w}"); + } +} + /// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an /// error naming the param, and leave the document, the selection and the undo history as they were. /// Null keeps a param's default, and a distance still takes a string with a unit. diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index 60c2a8b296..e35e5e2664 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -21,7 +21,7 @@ thread_local! { /// The contour passes made over an arrangement on this thread, each of which walks all of it. pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The sweeps [`normalize_bez`] made on this thread. - static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + pub(crate) static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The input curves [`exact_merge`] tested on this thread. static EXACT_MERGE_CURVES: std::cell::Cell = const { std::cell::Cell::new(0) }; } diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index 0ff1b82594..d02e5a8a93 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -15,6 +15,7 @@ mod offset; mod pathfinder; mod planar; mod sweep_axis; +mod thickness; mod trap; pub use boolean::{ @@ -35,6 +36,7 @@ pub use planar::{ Adjacency, BuilderArrangement, MapEdge, MapFace, MapOutline, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, adjacency, cut_out, encloses_area, find_gaps, has_open_path, interior_point, live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap, }; +pub use thickness::{MAX_DOCUMENT_THICKNESS_WORK, MAX_THICKNESS_PIECES, ThicknessBudget, thinner_than, thinner_than_within}; pub use trap::{TRAP_HEIGHT_WIDTH_RANGE, TRAP_MAX_WIDTH, TRAP_MIN_WIDTH, trap_band}; /// Errors from fallible operations. diff --git a/crates/pathops/src/thickness.rs b/crates/pathops/src/thickness.rs new file mode 100644 index 0000000000..a4bffb998a --- /dev/null +++ b/crates/pathops/src/thickness.rs @@ -0,0 +1,557 @@ +//! The thickness of a filled shape: whether a circle of a given width fits anywhere inside its +//! fill (Clean Up's and Select › Object's Hairline Slivers). + +use std::cmp::Ordering; +use std::collections::BinaryHeap; + +use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _}; +use vectorcraft_geom::{FillRule, PathData}; + +use crate::boolean::{fill_bezpath, normalize_bez}; + +/// Most line pieces the outline of one shape is measured with. +pub const MAX_THICKNESS_PIECES: usize = 100_000; +/// Most cells one search for a wide enough spot looks at. +const MAX_CELLS: usize = 500_000; +/// Most distances from a point to a piece of outline one search measures. +const MAX_WORK: usize = 50_000_000; +/// Most distances from a point to a piece of outline the shapes of one document are measured +/// with, all together ([`ThicknessBudget::document`]). +pub const MAX_DOCUMENT_THICKNESS_WORK: usize = 1_000_000_000; +/// The resolved outline is measured as line pieces within `width / FINE_PARTS` of its curves. +const FINE_PARTS: f64 = 32.0; +/// The first, rough look measures the path as drawn with pieces within `width / ROUGH_PARTS`. +const ROUGH_PARTS: f64 = 8.0; + +/// Is the fill of `path` (every subpath closed, as a fill paints it) under `rule` thinner than +/// `width` everywhere: does no circle of diameter `width` fit inside it? A path with no fill is. +/// A shape within a small fraction of `width` of the limit is taken as thick enough. +/// +/// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't +/// finite, the fill can't be resolved into outlines, or measuring it would take more than +/// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long. +pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option { + thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK)) +} + +/// The work left for measuring shapes with [`thinner_than_within`]: a count of distances from a +/// point to a piece of outline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ThicknessBudget(usize); + +impl ThicknessBudget { + pub fn new(work: usize) -> Self { + Self(work) + } + /// The work all the shapes of one document may take: [`MAX_DOCUMENT_THICKNESS_WORK`]. + pub fn document() -> Self { + Self(MAX_DOCUMENT_THICKNESS_WORK) + } + /// The work left. + pub fn left(&self) -> usize { + self.0 + } +} + +/// [`thinner_than`], taking the search's work from `budget`: `None` as well when the search needs +/// more than is left. The quick checks take nothing from it, so they still settle shapes once it +/// runs out. +pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: &mut ThicknessBudget) -> Option { + let finite = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !(width.is_finite() && width > 0.0) + || !path.subpaths.iter().flat_map(|sp| &sp.anchors).all(|a| finite(a.p) && finite(a.h_in) && finite(a.h_out)) + { + return None; + } + // Every segment is at least one piece of outline, so a path of more anchors is too long to + // measure before its outline is built. + if path.subpaths.iter().map(|sp| sp.anchors.len()).sum::() > MAX_THICKNESS_PIECES { + return None; + } + let mut bp = fill_bezpath(path); + if bp.elements().is_empty() { + return Some(true); + } + // Measured from the corner of its bounds, so that a shape far from the origin measures as it + // does near it. + let corner = bp.bounding_box().origin(); + bp.apply_affine(Affine::translate(-corner.to_vec2())); + let b = bp.bounding_box(); + let (r, fine) = (width / 2.0, width / FINE_PARTS); + // A circle inside the fill is inside its bounds. Bounds within the fine measure's error of the + // width go on to that measure, which keeps them. + if b.width().min(b.height()) < width - 2.0 * fine { + return Some(true); + } + // Every point of a fill lies within the widest circle's radius r of its outline, and the points + // within r of a closed outline of length L cover at most 2rL + πr². A fill larger than that holds + // a circle of diameter `width`. Only one subpath filled nonzero that winds at most once around + // any point is measured so: the areas of several subpaths add up to more than their fill where + // they overlap, a path that runs around a spot twice counts its area there twice, and an + // even-odd fill of a path that runs around twice is empty. + if path.subpaths.len() == 1 + && rule == FillRule::NonZero + && winds_at_most_once(&bp) + && bp.area().abs() > 2.0 * r * bp.perimeter(1e-3) * 1.01 + std::f64::consts::PI * r * r + { + return Some(false); + } + // The circle lies between any two parallel lines that hold the path's points and handles too, + // which settles a long sliver lying on a slant. + if hull_width(&bp) < width - 2.0 * fine { + return Some(true); + } + // A rough look at the path as drawn: an edge running inside the fill is nearer than the fill's + // outline, so a spot this far from every edge (and from the rough pieces' error) is far enough. + let rough = width / ROUGH_PARTS; + let mut edges = vec![]; + if !flatten_into(&bp, rough, &mut edges) { + return None; + } + match search(&edges, b, rule, r + rough, rough, budget) { + Search::Found => return Some(false), + // Resolving the outlines takes time of its own, so it isn't started when what is left of + // the budget cut the rough look short. The rough look can run out where the resolved + // outline is much shorter, so one that ran out of its own share goes on. + Search::TooLong if budget.0 < MAX_WORK => return None, + _ => {} + } + // The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the + // fill are no outline of it. A spot within the fine pieces' error of the radius counts as one. + let contours = normalize_bez(&bp, rule).ok()?; + edges.clear(); + for c in contours.contours() { + if !flatten_into(&c.path, fine, &mut edges) { + return None; + } + } + if edges.is_empty() { + return Some(true); + } + match search(&edges, b, FillRule::EvenOdd, r - fine, fine, budget) { + Search::Found | Search::Unsure => Some(false), + Search::Absent => Some(true), + Search::TooLong => None, + } +} + +/// The points and handles of `bp`, in order. +fn control_points(bp: &BezPath) -> Vec { + bp.elements() + .iter() + .flat_map(|el| match *el { + PathEl::MoveTo(p) | PathEl::LineTo(p) => vec![p], + PathEl::QuadTo(a, p) => vec![a, p], + PathEl::CurveTo(a, b, p) => vec![a, b, p], + PathEl::ClosePath => vec![], + }) + .collect() +} + +/// Does `bp`, one closed subpath, wind at most once around every point? Every line through a point +/// that a curve winds around twice crosses it at least four times, so such a curve turns through +/// at least 4π in all. A Bézier curve turns no more than its control polygon, so a control polygon +/// that turns through less than 4π winds at most once. +fn winds_at_most_once(bp: &BezPath) -> bool { + let mut pts = control_points(bp); + pts.dedup(); + while pts.len() > 1 && pts.first() == pts.last() { + pts.pop(); + } + if pts.len() < 3 { + return true; + } + let turned: f64 = pts + .iter() + .zip(pts.iter().cycle().skip(1)) + .zip(pts.iter().cycle().skip(2)) + .map(|((&a, &b), &c)| { + let (u, v) = (b - a, c - b); + u.cross(v).atan2(u.dot(v)).abs() + }) + .sum(); + turned < 4.0 * std::f64::consts::PI * (1.0 - 1e-9) +} + +/// Most corners of a convex hull [`hull_width`] measures; a larger hull measures as unbounded. +const MAX_HULL: usize = 512; + +/// The least distance between two parallel lines that hold every point and handle of `bp` (the +/// width of their convex hull, which holds the curves too). +fn hull_width(bp: &BezPath) -> f64 { + let mut pts = control_points(bp); + pts.sort_by(|a, b| a.x.total_cmp(&b.x).then(a.y.total_cmp(&b.y))); + pts.dedup(); + if pts.len() < 3 { + return 0.0; + } + // Andrew's monotone chain: the lower hull, then the upper. + let turn = |o: Point, a: Point, b: Point| (a - o).cross(b - o); + let mut hull: Vec = Vec::with_capacity(pts.len() + 1); + for pass in [false, true] { + let floor = hull.len(); + let ordered: Box> = if pass { Box::new(pts.iter().rev()) } else { Box::new(pts.iter()) }; + for &p in ordered { + while hull.len() >= floor + 2 && hull.get(hull.len() - 2).zip(hull.last()).is_some_and(|(&o, &a)| turn(o, a, p) <= 0.0) { + hull.pop(); + } + hull.push(p); + } + hull.pop(); + } + if hull.len() < 3 { + return 0.0; + } + if hull.len() > MAX_HULL { + return f64::INFINITY; + } + // For each side, the farthest corner from its line; the least of those is the width. + let mut least = f64::INFINITY; + for (&a, &b) in hull.iter().zip(hull.iter().cycle().skip(1)) { + let side = b - a; + let len = side.hypot(); + if len > 0.0 { + let far = hull.iter().map(|&p| side.cross(p - a).abs() / len).fold(0.0, f64::max); + least = least.min(far); + } + } + least +} + +/// Add `bp`'s outline to `edges` as line pieces within `tolerance` of it: false when that takes +/// more than [`MAX_THICKNESS_PIECES`], or when a curve is too long for [`vectorcraft_geom::flatten`] +/// to keep within `tolerance`. +fn flatten_into(bp: &BezPath, tolerance: f64, edges: &mut Vec<(Point, Point)>) -> bool { + let push = |from: Point, to: Point, edges: &mut Vec<(Point, Point)>| { + if from != to { + edges.push((from, to)); + } + }; + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + let most = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE; + for el in bp.iter() { + if edges.len() > MAX_THICKNESS_PIECES { + return false; + } + match el { + // An outline that doesn't end where it starts is closed with a line, as a fill paints it. + PathEl::MoveTo(p) => { + push(last, start, edges); + (start, last) = (p, p); + } + PathEl::ClosePath => { + push(last, start, edges); + last = start; + } + PathEl::LineTo(p) => { + push(last, p, edges); + last = p; + } + PathEl::QuadTo(a, p) | PathEl::CurveTo(a, _, p) => { + let length = match el { + PathEl::CurveTo(_, b, _) => last.distance(a) + a.distance(b) + b.distance(p), + _ => last.distance(a) + a.distance(p), + }; + if length / most > tolerance { + return false; + } + let mut from = last; + vectorcraft_geom::flatten([PathEl::MoveTo(last), el], tolerance, |piece| { + if let PathEl::LineTo(to) = piece { + push(from, to, edges); + from = to; + } + }); + last = p; + } + } + } + push(last, start, edges); + edges.len() <= MAX_THICKNESS_PIECES +} + +/// The distance from `p` to the nearest of `edges`, negative outside the region they bound under +/// `rule`. +fn signed_distance(edges: &[(Point, Point)], rule: FillRule, p: Point) -> f64 { + let mut winding = 0i32; + let mut nearest = f64::INFINITY; + for &(a, b) in edges { + if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) { + winding += if b.y > a.y { 1 } else { -1 }; + } + let ab = b - a; + let len2 = ab.hypot2(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + nearest = nearest.min((p - (a + ab * t)).hypot2()); + } + let inside = match rule { + FillRule::NonZero => winding != 0, + FillRule::EvenOdd => winding % 2 != 0, + }; + let d = nearest.sqrt(); + if inside { d } else { -d } +} + +/// A square cell of the search: its center, half its side, the signed distance from its center to +/// the outline, and the most that distance can be anywhere in it. +struct Cell { + c: Point, + h: f64, + d: f64, + most: f64, +} + +impl PartialEq for Cell { + fn eq(&self, other: &Self) -> bool { + self.most.total_cmp(&other.most) == Ordering::Equal + } +} + +impl Eq for Cell {} + +impl PartialOrd for Cell { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Cell { + fn cmp(&self, other: &Self) -> Ordering { + self.most.total_cmp(&other.most) + } +} + +/// What [`search`] found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Search { + /// A point at least the distance asked for from the outline. + Found, + /// No such point. + Absent, + /// None found, but cells smaller than the finest size could still hold one. + Unsure, + /// The search needed more cells or distances than it may take. + TooLong, +} + +/// Look for a point inside the region `edges` bound under `rule` (within `bounds`) at least `goal` +/// from its outline. The bounds are cut into square cells, and the cell that could hold the farthest +/// point is split first, until a cell's center is `goal` away or no cell could be. The distance +/// changes no faster than the point moves, so a cell holds no point farther than its center's +/// distance plus half its diagonal. Cells smaller than `finest` are not split further. The +/// distances it measures, no more than [`MAX_WORK`], are taken from `budget`. +fn search(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, goal: f64, finest: f64, budget: &mut ThicknessBudget) -> Search { + let mut work = 0usize; + let found = search_up_to(edges, bounds, rule, (goal, finest), budget.0.min(MAX_WORK), &mut work); + budget.0 = budget.0.saturating_sub(work); + found +} + +/// [`search`], measuring no more than `limit` distances and counting them in `work`. +fn search_up_to(edges: &[(Point, Point)], bounds: Rect, rule: FillRule, (goal, finest): (f64, f64), limit: usize, work: &mut usize) -> Search { + let side = bounds.width().min(bounds.height()); + if side.is_nan() || side <= 0.0 { + return Search::Absent; + } + let (cols, rows) = ((bounds.width() / side).ceil(), (bounds.height() / side).ceil()); + if cols * rows > MAX_CELLS as f64 || cols * rows * edges.len() as f64 > limit as f64 { + return Search::TooLong; + } + let cell = |c: Point, h: f64, work: &mut usize| { + *work += edges.len(); + let d = signed_distance(edges, rule, c); + Cell { c, h, d, most: d + h * std::f64::consts::SQRT_2 } + }; + let mut heap = BinaryHeap::new(); + let h = side / 2.0; + for i in 0..cols as usize { + for j in 0..rows as usize { + heap.push(cell(Point::new(bounds.x0 + (i as f64 + 0.5) * side, bounds.y0 + (j as f64 + 0.5) * side), h, work)); + } + } + let (mut made, mut unsure) = (heap.len(), false); + while let Some(next) = heap.pop() { + if next.d >= goal { + return Search::Found; + } + if next.most < goal { + break; + } + if next.h < finest / 2.0 { + unsure = true; + continue; + } + if made + 4 > MAX_CELLS || work.saturating_add(4 * edges.len()) > limit { + return Search::TooLong; + } + let h = next.h / 2.0; + for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] { + let part = cell(Point::new(next.c.x + dx, next.c.y + dy), h, work); + // A cell that can't hold a point `goal` away is left out. + if part.most >= goal { + heap.push(part); + } + } + made += 4; + } + if unsure { Search::Unsure } else { Search::Absent } +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::{Anchor, SubPath}; + + use super::*; + + fn polygon(points: &[(f64, f64)]) -> SubPath { + SubPath::new(points.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true) + } + + fn one(points: &[(f64, f64)]) -> PathData { + PathData::single(polygon(points)) + } + + fn thin(p: &PathData, rule: FillRule, width: f64) -> bool { + thinner_than(p, rule, width) == Some(true) + } + + fn thick(p: &PathData, rule: FillRule, width: f64) -> bool { + thinner_than(p, rule, width) == Some(false) + } + + #[test] + fn a_triangle_whose_third_anchor_almost_meets_its_first_is_thinner_than_a_hairline() { + let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); + assert!(thin(&sliver, FillRule::NonZero, 0.085)); + // Long and on a slant at the narrowest width, and far from the origin. + assert!(thin(&one(&[(0.0, 0.0), (600.0, 600.0), (0.0, 0.0001)]), FillRule::NonZero, 0.001)); + let (x, y) = (1_000_000.0, 1_000_000.0); + assert!(thin(&one(&[(x, y), (x + 0.01, y + 0.0075), (x + 0.0001, y + 0.0002)]), FillRule::NonZero, 0.001)); + } + + #[test] + fn a_bent_sliver_is_found_by_measuring_inside_it() { + // Out along two sides of a triangle and back 0.002 pt inside them: its hull and bounds are + // wide, and only the measure inside finds it thin. + let v = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]); + assert!(thin(&v, FillRule::NonZero, 0.085)); + } + + #[test] + fn a_narrow_strip_wider_than_the_width_is_kept_and_one_narrower_is_not() { + // A diagonal strip 100 pt long. + let strip = |w: f64| { + let (dx, dy) = (0.6 * w, -0.8 * w); + one(&[(0.0, 0.0), (80.0, 60.0), (80.0 + dx, 60.0 + dy), (dx, dy)]) + }; + assert!(thick(&strip(0.2), FillRule::NonZero, 0.085)); + assert!(thick(&strip(0.2), FillRule::NonZero, 0.18)); + assert!(thin(&strip(0.05), FillRule::NonZero, 0.085)); + assert!(thin(&strip(0.2), FillRule::NonZero, 0.24)); + } + + #[test] + fn a_triangle_holding_the_circle_off_every_cell_center_is_kept() { + // Its inscribed circle is 2 across, centered at (1, 1). + let t = one(&[(0.0, 0.0), (4.0, 0.0), (0.0, 3.0)]); + assert!(thick(&t, FillRule::NonZero, 1.95)); + assert!(thin(&t, FillRule::NonZero, 2.3)); + } + + #[test] + fn a_tiny_round_dot_is_kept() { + let dot = vectorcraft_geom::shapes::ellipse(kurbo::Rect::new(10.0, 10.0, 10.3, 10.3)); + assert!(thick(&dot, FillRule::NonZero, 0.085)); + assert!(thick(&dot, FillRule::NonZero, 0.29)); + assert!(thin(&dot, FillRule::NonZero, 0.4)); + } + + #[test] + fn a_thin_ring_is_thin_whichever_way_its_subpaths_run() { + let square = |x0: f64, x1: f64| polygon(&[(x0, x0), (x1, x0), (x1, x1), (x0, x1)]); + let mut hole = square(1.01, 98.99); + hole.reverse(); + assert!(thin(&PathData::new(vec![square(1.0, 99.0), hole]), FillRule::NonZero, 0.085)); + // Even-odd: an inner square running the same way still cuts a hole. + assert!(thin(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::EvenOdd, 0.085)); + // Nonzero: it doesn't, and the edges inside the fill are no outline of it. + assert!(thick(&PathData::new(vec![square(1.0, 99.0), square(1.01, 98.99)]), FillRule::NonZero, 0.085)); + } + + #[test] + fn overlapping_strips_are_measured_by_their_union() { + // Two strips 0.2 pt tall overlapping by half: their fill is 0.3 pt tall, while the edges of + // each that run inside the other are no more than 0.1 pt apart. + let strip = |y: f64| polygon(&[(0.0, y), (100.0, y), (100.0, y + 0.2), (0.0, y + 0.2)]); + let strips = PathData::new(vec![strip(0.0), strip(0.1)]); + assert!(thick(&strips, FillRule::NonZero, 0.15)); + assert!(thin(&strips, FillRule::NonZero, 0.35)); + } + + #[test] + fn an_outline_out_and_back_along_itself_has_no_fill_and_is_thin() { + assert!(thin(&one(&[(0.0, 0.0), (30.0, 40.0), (0.0, 0.0), (30.0, 40.0)]), FillRule::NonZero, 0.085)); + assert!(thin(&PathData::default(), FillRule::NonZero, 0.085)); + } + + /// Shapes thicker than the width by their area, and slivers lying flat along an axis, are settled + /// without resolving their outlines, so a document of thousands of them is measured quickly. + #[test] + fn plain_shapes_and_flat_slivers_are_settled_without_resolving_their_outlines() { + let before = crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()); + for k in 0..2000 { + let x = f64::from(k) * 12.0; + assert!(thick(&one(&[(x, 0.0), (x + 10.0, 0.0), (x + 10.0, 10.0), (x, 10.0)]), FillRule::NonZero, 0.085)); + assert!(thin(&one(&[(x, 20.0), (x + 10.0, 20.0), (x + 10.0, 20.01), (x, 20.01)]), FillRule::NonZero, 0.085)); + // Long slivers on a slant are settled by the width of their hull. + assert!(thin(&one(&[(x, 40.0), (x + 9.0, 52.0), (x + 0.001, 40.0015)]), FillRule::NonZero, 0.085)); + } + assert_eq!(crate::boolean::NORMALIZE_SWEEPS.with(|n| n.get()), before); + } + + /// The area measure is used only for an outline that runs around once: one that runs around + /// twice counts its area twice. + #[test] + fn an_outline_that_runs_around_twice_is_not_measured_by_its_area() { + let square = |n: usize| { + let mut bp = BezPath::new(); + bp.move_to((0.0, 0.0)); + for _ in 0..n { + for p in [(10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0)] { + bp.line_to(p); + } + } + bp.close_path(); + bp + }; + assert!(winds_at_most_once(&square(1))); + assert!(!winds_at_most_once(&square(2))); + // Measured inside instead, a square run around twice is still as thick as one. + let twice = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0), (0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + assert!(thick(&twice, FillRule::NonZero, 0.085)); + } + + /// Shapes that need the search share one budget: once it is spent they can't be measured, and + /// the quick checks still settle the rest. + #[test] + fn a_spent_budget_leaves_the_shapes_that_need_a_search_unmeasured() { + let bent = one(&[(0.0, 0.0), (40.0, 30.0), (80.0, 0.0), (79.997, 0.0), (40.0, 29.998), (0.003, 0.0)]); + let square = one(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let mut budget = ThicknessBudget::document(); + assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut budget), Some(true)); + assert!(budget.left() < MAX_DOCUMENT_THICKNESS_WORK); + let mut spent = ThicknessBudget::new(0); + assert_eq!(thinner_than_within(&bent, FillRule::NonZero, 0.085, &mut spent), None); + assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false)); + } + + #[test] + fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() { + let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); + for w in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert_eq!(thinner_than(&sliver, FillRule::NonZero, w), None, "{w}"); + } + let flat = one(&[(0.0, 0.0), (f64::NAN, 0.0), (40.0, 0.0)]); + assert_eq!(thinner_than(&flat, FillRule::NonZero, 0.085), None); + } +} diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 6fd3009921..e568c0f7c8 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -21,7 +21,16 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let linked = d.fields.get("__rowGutterLinked").is_some() && d.fields.get("__rowGutterLinked") == d.fields.get("rowGutter"); let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk); let choices = |k: &str| rasterize_color_models(&command, k, cmyk).or_else(|| choices(&command, k)); - form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, app.session.general_unit()); + // Hairline Slivers' widths show in the stroke unit (Preferences › Units › Stroke), or in + // points when that unit's field rounds the narrowest width to 0. + let unit = match command.as_str() { + "object.path.cleanUp" | "select.object.hairlineSlivers" => { + let stroke = app.session.stroke_unit(); + if stroke.number(*vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE.start()) == "0" { vectorcraft_doc::Unit::Points } else { stroke } + } + _ => app.session.general_unit(), + }; + form::param_fields(ui, d, &|k| lengths.contains(&k), &choices, &rank, unit); if command == crate::addons::packaging::SET_ROLE_SWATCH { crate::addons::packaging::follow_role(app, d); } @@ -154,6 +163,8 @@ fn lengths(command: &str) -> &'static [&'static str] { crate::addons::cutting::BRIDGES => &["width"], "object.textWrap.options" => &["offset"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset"], + "object.path.cleanUp" => &["sliverWidth"], + "select.object.hairlineSlivers" => &["width"], _ => &[], } } @@ -168,6 +179,7 @@ pub(super) fn length_range(command: &str, key: &str) -> Option { Some(0.0..=vectorcraft_engine::MAX_COORD) } + ("object.path.cleanUp", "sliverWidth") | ("select.object.hairlineSlivers", "width") => Some(vectorcraft_engine::HAIRLINE_SLIVER_WIDTH_RANGE), _ => None, } } @@ -192,6 +204,7 @@ fn order(command: &str) -> &'static [&'static str] { crate::addons::packaging::SET_ROLE_SWATCH => &["role", "swatch"], crate::addons::pathtools::COMMON_TANGENTS => &["tangents", "centerline"], crate::addons::pathtools::BOUNDING_RECTANGLE | crate::addons::pathtools::BOUNDING_CIRCLE => &["offset", "each"], + "object.path.cleanUp" => &["strayPoints", "unpaintedObjects", "emptyTextPaths", "hairlineSlivers", "sliverWidth"], _ => &[], } } diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3e68b98c92..474fea5063 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -260,7 +260,17 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Divide Objects Below", "object.path.divideObjectsBelow"), c("Split Into Grid…", "object.path.splitIntoGrid"), Sep, - cp("Clean Up…", "object.path.cleanUp", json!({"strayPoints": true, "unpaintedObjects": true, "emptyTextPaths": true})), + cp( + "Clean Up…", + "object.path.cleanUp", + json!({ + "strayPoints": true, + "unpaintedObjects": true, + "emptyTextPaths": true, + "hairlineSlivers": false, + "sliverWidth": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH + }), + ), ], ), sub("Shape", vec![c("Convert to Shape", "object.shape.convertToShape"), c("Expand Shape", "object.expandShape")]), @@ -538,6 +548,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Clipping Masks", "select.object.clippingMasks"), c("Slices", "select.object.slices"), c("Stray Points", "select.object.strayPoints"), + cp("Hairline Slivers…", "select.object.hairlineSlivers", json!({"width": vectorcraft_engine::HAIRLINE_SLIVER_WIDTH})), c("Open Paths", "select.object.openPaths"), c("Not Aligned to Pixel Grid", "select.object.notAlignedToPixelGrid"), Sep, diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..b9dc1a4087 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7204,6 +7204,24 @@ the dialog on those settings next time. `"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit (`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default. +`object.path.cleanUp` with `hairlineSlivers: true` also removes hairline slivers: closed paths and compound paths with +a visible fill, no visible stroke and no effect, so thin that no circle `sliverWidth` across fits inside their fill +(Unpainted Objects covers shapes with no paint). A compound path is measured as one fill, so a compound path with one +sliver member and one real shape stays. `sliverWidth` is a distance from 0.001 to 3 pt; it defaults to 0.03 mm, +VectorCraft's own value, and `hairlineSlivers` is off by default. In the desktop app the Clean Up dialog has a Hairline +Slivers checkbox and a Sliver Width field, shown in the stroke unit, or in points when that unit's field would round +0.001 pt to 0. `select.object.hairlineSlivers {width?}` (Select › Object › Hairline Slivers…) selects the objects Clean +Up would remove, only inside the isolated group while one is isolated, and replies `{count, warning?}`. Neither command +takes hidden or locked objects, objects in template layers, art on locked artboards, guides, the clipping paths of +groups and layers, shapes with an effect, or the members of Live Paint groups and other live or generated art. A shape +that holds a circle 15/16 of the width across is kept too. A shape too complex to measure is kept as well, and so is +every shape still unmeasured when one run reaches its limit of work; the reply's `warning` says how many there were: + +```json +{"name":"run_command","arguments":{"command":"object.path.cleanUp","params":{"strayPoints":false,"unpaintedObjects":false,"emptyTextPaths":false,"hairlineSlivers":true,"sliverWidth":"0.03 mm"}}} +{"name":"run_command","arguments":{"command":"select.object.hairlineSlivers","params":{"width":0.1}}} +``` + ## Smooth `object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..8df165d8d2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1675,6 +1675,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Geometry and effects:** - **Open-path anchor Delete:** Delete/Backspace removes selected anchors and their adjoining segments, leaving drawable runs as separate open subpaths of the original object. Surviving curves and appearance stay intact; one Undo restores the document and selection, and a second Delete removes the selected remainder. Explicit Remove Anchor Points still reconnects/refits. Four core regressions, one full-frame Delete/Backspace regression and three existing removal/segment controls pass, covering these distinctions, multiple deletions, transformed geometry and mixed whole-object selection. Behaviour references: the legacy public [Illustrator reference guide, Add or delete an anchor point](https://helpx.adobe.com/content/dam/help/en/pdf/illustrator_reference.pdf) distinguishes keyboard deletion from dedicated removal; the current [Add or remove anchor points](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/add-or-remove-anchor-points.html) describes the dedicated tools. Other G11 gaps and scores/hours remain unchanged. - Pathfinder (10 exact curve booleans; single-result shape operations retain source names and SVG IDs, #1293), Offset, Outline Stroke, Simplify, Clean Up, Split Into Grid, Divide Objects Below. With one group selected alone, the Pathfinder panel's buttons work on its members (among other selected objects a group still acts as one shape), and a greyed-out button says what it needs (#1450; behaviour reference: [combine objects using Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html); one plain path selected alone stays disabled, which the documentation doesn't settle). Split Into Grid takes the number, height or width, gutter and total of the rows and of the columns, Add Guides and Preview, and several selected paths become one grid painted as the topmost one (#1462, `object.path.splitIntoGrid`; behaviour reference: [divide or split objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/divide-or-split-objects.html); a typed height or width keeps the gutter and changes the total, our choice). Object › Path › Remove Anchor Points (`path.removeAnchors`) removes the direct-selected anchors without opening their paths (the Delete key still deletes them with their segments): the neighbours keep their handle directions and their facing handles are refitted so one cubic follows the two old segments, and straight sides stay straight. The Delete Anchor Point tool uses the same refit. The Control bar, the contextual task bar, the Properties quick actions and the canvas context menu offer it when anchors are selected. With anchors selected, the Control bar and the Properties panel also convert them to corner or smooth (`path.convertAnchors`), connect end points (Join) and cut the path at them (`path.cutAtAnchors`, also on the task bar and the context menu): a closed path opens there and an open one becomes one path per piece, each cut leaving one of its two coincident anchors selected so a drag pulls the path apart. In the Pathfinder panel a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled (#1642, #1635). + Clean Up has a Hairline Slivers option, VectorCraft's own and off by default: it removes closed paths and compound paths with a visible fill, no visible stroke and no effect when no circle as wide as its Sliver Width (0.03 mm by default) fits inside their fill, and Select › Object › Hairline Slivers… selects them (`crates/engine/src/tests/pathops.rs`, `crates/pathops/src/thickness.rs` tests). Outline Stroke, Expand's Stroke option and Flatten Transparency's Convert All Strokes to Outlines apply the object's visible geometry effects (Offset Path, Zig Zag and the others) to the path, and then apply each stroke's own geometry effects before outlining that stroke, as the canvas draws it. The filled outline of a stroke without a brush keeps the stroke's other effects, such as a drop shadow. Outline Stroke and Unite remove the overlaps of a long, low path with the sweep turned along it: when the estimated number of segments the sweep holds at once is under two thirds as large for the path turned a quarter turn (paths of 2,048 segments or more), the overlaps are removed on the turned path and the result is turned back, which moves no point by rounding. The lookups of the input curve that a piece of the result lies on, and of the input anchors that are kept, can search along y instead of x: once lookups with more than 64 candidates along x have counted 16 for each input curve or anchor, a lookup searches along y when it finds fewer candidates there (under a quarter as many for curves), and where that has rarely happened it measures along y in only one lookup of 32. On one open path of 200,000 anchors in rows of 1,000, Outline Stroke takes 17.3 s of processor time instead of 31.3 s and Unite 2.9 s instead of 6.5 s in a release build. A turned result has as many subpaths as the result without the turn, and the area where the two differ is no larger than the refit precision times the outline's length (`crates/pathops/src/sweep_axis.rs` tests). Offset Path turns the sweep the same way: when the estimate for its fill, the ring stroked around the fill and the outline of its open subpaths is under two thirds as large turned a quarter turn, the faces are found on the turned parts, the faces that lie within the offset distance of the path are dropped by testing their points turned back, and the result is turned back. On an open path of 10,000 anchors in rows of 1,000, offsetting by 2 pt takes 1.0 s of processor time instead of 1.8 s in a release build. The offset of a long, low path has as many subpaths as the offset of the same path stood on end, and the area where the two differ is no larger than the refit precision times the outline's length (`offset_path_sweeps_a_long_low_path_turned_with_the_result_of_the_path_on_end`). From 3237057ec8e6072df37847d74391345c6bd207e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:04:29 -0800 Subject: [PATCH 033/153] Plug-ins: names and labels show in the UI language from the manifest's translations A plug-in manifest may give `translations`, keyed by language code, with the plug-in's name, its commands' labels, its parameters' labels, help and choice labels, and its group headings. Menus, plug-in dialogs, the Appearance panel, Keyboard Shortcuts, the command palette and Last Effect show the text for the UI language, then for the language without its region (pt-br, then pt), then the manifest's own text. Command ids, parameter names, choice values, plugin.list and errors keep the manifest's own text. The install approval asks with the name in the UI language and shows the manifest's own name under the ID when they differ. Installing refuses malformed or repeated language codes, more than 16 languages, empty or over-long text, control, direction and line-separator characters, keys the manifest does not declare, and two choices with the same label after fallback, with an error that names the key. The 64 KiB manifest limit covers the translations. Filter and importer menu items, plug-in dialog text and the heavy-filter refusal now escape bidirectional characters, and Keyboard Shortcuts and the palette no longer put a plug-in's own name or command label through the app's catalogs. --- crates/engine/src/cmd/plugin.rs | 10 +- crates/engine/src/tests/plugins.rs | 13 + crates/plugins/src/lib.rs | 4 +- crates/plugins/src/manifest.rs | 14 +- crates/plugins/src/permissions.rs | 2 +- crates/plugins/src/translations.rs | 539 ++++++++++++++++++++++++ crates/ui-egui/src/dialogs/effect.rs | 12 +- crates/ui-egui/src/dialogs/form.rs | 78 +++- crates/ui-egui/src/dialogs/plugin.rs | 106 +++-- crates/ui-egui/src/dialogs/tests.rs | 70 +++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + crates/ui-egui/src/io/open.rs | 27 +- crates/ui-egui/src/menus/labels.rs | 13 +- crates/ui-egui/src/palette.rs | 69 ++- crates/ui-egui/src/panels/appearance.rs | 20 +- crates/ui-egui/src/shortcut_editor.rs | 49 ++- crates/ui-egui/src/tests/plugins.rs | 167 ++++++++ docs/mcp.md | 3 + docs/plugins.md | 48 +++ docs/target-app-parity.md | 1 + 47 files changed, 1301 insertions(+), 97 deletions(-) create mode 100644 crates/plugins/src/translations.rs diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 2a1b8c8b40..6ff023d4de 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -808,11 +808,11 @@ fn install(s: &mut Session, p: &Value) -> Result { // A heavy plug-in is installed once a person agrees. if plugin.manifest().budget == Budget::Heavy && !allow_heavy { let (minutes, times) = vectorcraft_plugins::heavy_terms(); + let name = permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME); return Err(bad( C, format!( - "“{}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants", - plugin.manifest().name + "“{name}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants" ), )); } @@ -955,6 +955,10 @@ fn inspect(s: &mut Session, p: &Value) -> Result { if !refused.is_empty() { v["refusedCommands"] = json!(refused); } + let translations = &plugin.manifest().translations; + if !translations.is_empty() { + v["translations"] = serde_json::to_value(translations).unwrap_or(Value::Null); + } v }) } @@ -1306,7 +1310,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", + "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has), refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module) and translations?: {language: {name?, params?, groups?, commands?}} (the manifest's translations as declared, when it gives any)", always, inspect ), diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 947a3ec42d..32d96f5df9 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -2017,6 +2017,19 @@ fn a_heavy_filter_installs_once_the_user_agrees() { assert!(install(&mut s, DESATURATE).get("budget").is_none()); } +/// The refusal of a heavy filter names it as prompts show text: a right-to-left override in its +/// name is escaped, so it can't reorder the message around it. +#[test] +fn a_heavy_filter_refusal_escapes_its_name() { + let mut s = session(); + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + let manifest = format!(r#"{{"id":"test.engine.heavy.name","name":"Route{rlo}txt.exe","version":"1","kind":"filter","budget":"heavy"}}"#); + let module = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let e = s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap_err().to_string(); + assert!(e.contains("“Route\\u{202E}txt.exe” asks for a heavy budget"), "{e}"); +} + #[test] fn invalid_install_flags_are_refused() { let mut s = session(); diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index 019dd0d858..1e053354c6 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -31,7 +31,8 @@ //! them well: labels, units, groups, help and conditions ([`dialog`]). What a plug-in may do is //! the set of [`permissions`] its manifest lists, which the user approves when it is installed. A //! filter or a live effect may also add menu commands of its own ([`Command`]), which the host -//! runs through `vc_run` with the command's id in `_context`. +//! runs through `vc_run` with the command's id in `_context`. Its name, command labels and +//! parameter text may come in other languages too ([`translations`]). #![forbid(unsafe_code)] pub mod deferred; @@ -48,6 +49,7 @@ pub mod registry; mod runtime; pub mod safe_mode; pub mod storage; +pub mod translations; pub mod wat; pub use dialog::ParamUi; diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index b6e17e3ad0..4efef7cd9e 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -6,6 +6,7 @@ use serde_json::{Map, Value, json}; use crate::dialog::ParamUi; use crate::permissions::{self, API_LEVEL, INPUTS_API, PROGRESS_API, Permission}; +use crate::translations::Translations; use crate::{Error, Result}; /// Longest manifest the host reads. @@ -348,6 +349,10 @@ pub struct Manifest { /// lists any ([`Manifest::validate`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub command_allowlist: Vec, + /// Its name, command labels and parameter text in other languages, shown in place of the + /// manifest's own when the UI is in one of them ([`crate::translations`]). + #[serde(default, skip_serializing_if = "Translations::is_empty")] + pub translations: Translations, } impl Manifest { @@ -383,13 +388,15 @@ impl Manifest { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + translations: Translations::default(), } } /// The manifest command `c` runs with: this one with `c`'s label as its name and `c`'s - /// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them. + /// parameters as its own, so dialogs show them and [`Manifest::resolve_params`] checks them, + /// and with `c`'s text in each language as its translations. pub fn for_command(&self, c: &Command) -> Manifest { - Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), ..self.clone() } + Manifest { name: c.label.clone(), params: c.params.clone(), commands: Vec::new(), translations: self.command_translations(c), ..self.clone() } } /// The command with id `id`. @@ -440,7 +447,8 @@ impl Manifest { } self.validate_params()?; self.validate_commands()?; - self.validate_allowlist() + self.validate_allowlist()?; + self.validate_translations() } /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index b8c8672693..88641f03bf 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -211,7 +211,7 @@ pub fn names(permissions: &[Permission]) -> Vec<&'static str> { /// Is `c` a character that changes the direction text is laid out in, or a line or paragraph /// separator, which a prompt must not let a manifest string use to disguise itself? -fn is_bidi_or_separator(c: char) -> bool { +pub(crate) fn is_bidi_or_separator(c: char) -> bool { matches!(c, '\u{061C}' | '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{2028}' | '\u{2029}') } diff --git a/crates/plugins/src/translations.rs b/crates/plugins/src/translations.rs new file mode 100644 index 0000000000..f940a635cd --- /dev/null +++ b/crates/plugins/src/translations.rs @@ -0,0 +1,539 @@ +//! Text a plug-in gives in other languages: its manifest's `translations` (docs/plugins.md › +//! Translations). +//! +//! `translations` maps language codes (`de`, `pt-br`, `zh-hant`, compared without regard to case) +//! to the text shown in that language: the plug-in's `name`, its commands' labels, its parameters' +//! labels, help and choice labels, and its group headings. Every entry is optional; text a language +//! leaves out comes from the language without its last part (`pt-br`, then `pt`) and then from the +//! manifest's own text. The text is shown only: command ids, parameter names, the values a choice +//! passes, `plugin.list` and the install approval keep the manifest's own text. + +use std::collections::HashSet; + +use serde::{Deserialize, Serialize}; + +use crate::dialog::{MAX_HELP, MAX_LABEL}; +use crate::manifest::{Command, Manifest, ParamSpec}; +use crate::permissions::{self, MAX_SHOWN_FIELD, MAX_SHOWN_NAME}; +use crate::{Error, Result}; + +/// Most languages a manifest's `translations` gives text in. +pub const MAX_LANGUAGES: usize = 16; +/// Longest language code, in bytes. +pub const MAX_LANGUAGE_CODE: usize = 35; +/// Longest translated plug-in name, command label or choice label, in characters. +pub const MAX_NAME: usize = 64; + +/// Named entries in the order the manifest gives them; each name at most once. +#[derive(Clone, Debug, PartialEq)] +pub struct Entries(pub Vec<(String, T)>); + +impl Default for Entries { + fn default() -> Self { + Entries(Vec::new()) + } +} + +impl Entries { + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// The entry named `name`. + pub fn get(&self, name: &str) -> Option<&T> { + self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v) + } +} + +impl Serialize for Entries { + fn serialize(&self, s: S) -> std::result::Result { + use serde::ser::SerializeMap; + let mut m = s.serialize_map(Some(self.0.len()))?; + for (k, v) in &self.0 { + m.serialize_entry(k, v)?; + } + m.end() + } +} + +impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries { + fn deserialize>(d: D) -> std::result::Result { + struct V(std::marker::PhantomData); + impl<'de, T: Deserialize<'de>> serde::de::Visitor<'de> for V { + type Value = Entries; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("an object") + } + fn visit_unit(self) -> std::result::Result { + Ok(Entries::default()) + } + fn visit_map>(self, mut map: A) -> std::result::Result { + let mut seen = HashSet::new(); + let mut out = Vec::new(); + while let Some(k) = map.next_key::()? { + if !seen.insert(k.clone()) { + let shown = permissions::display_text(&k, MAX_SHOWN_FIELD); + return Err(serde::de::Error::custom(format!("`{shown}` is given twice"))); + } + out.push((k, map.next_value()?)); + } + Ok(Entries(out)) + } + } + d.deserialize_any(V(std::marker::PhantomData)) + } +} + +/// A parameter's text in one language. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ParamText { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub help: Option, + /// A choice's labels, by the value each option passes. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub options: Entries, +} + +/// A command's text in one language. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CommandText { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub params: Entries, +} + +/// A plug-in's text in one language. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Catalog { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// By parameter name. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub params: Entries, + /// Group headings, by the `group` the parameters give. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub groups: Entries, + /// By command id. + #[serde(default, skip_serializing_if = "Entries::is_empty")] + pub commands: Entries, +} + +/// A manifest's `translations`, by language code. +pub type Translations = Entries; + +/// Is `tag` a language code: a language of 2 or 3 letters, then parts of 2 to 8 letters and +/// digits, each after a `-`, at most [`MAX_LANGUAGE_CODE`] bytes in all (`de`, `pt-BR`, +/// `zh-Hant-TW`)? +pub fn valid_language_code(tag: &str) -> bool { + let mut parts = tag.split('-'); + tag.len() <= MAX_LANGUAGE_CODE + && parts.next().is_some_and(|l| (2..=3).contains(&l.len()) && l.bytes().all(|b| b.is_ascii_alphabetic())) + && parts.all(|p| (2..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric())) +} + +/// The codes text for language `lang` is looked up under, most specific first: `lang`, then +/// `lang` without its last part, down to the language alone (`zh-hant-tw`, `zh-hant`, `zh`). +fn lookup_codes(lang: &str) -> impl Iterator { + std::iter::successors(Some(lang), |l| l.rfind('-').map(|i| &l[..i])) +} + +impl Translations { + /// The first text `f` finds for language `lang` ([`lookup_codes`]). + fn find<'a, T>(&'a self, lang: &str, f: impl Fn(&'a Catalog) -> Option) -> Option { + lookup_codes(lang).find_map(|code| self.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case(code)).find_map(|(_, c)| f(c))) + } + + /// The plug-in's name these translations give for language `lang` (`None`: they give none). + pub fn name_in(&self, lang: &str) -> Option<&str> { + self.find(lang, |c| c.name.as_deref()) + } +} + +/// Is `s` text a translation may give: 1 to `max` characters, not all spaces, without control +/// characters (`\n` too, unless `lines`) or characters that change the direction text is laid out +/// in or separate lines? +fn fits(s: &str, max: usize, lines: bool) -> bool { + !s.trim().is_empty() + && s.chars().count() <= max + && s.chars().all(|c| (!c.is_control() || (lines && c == '\n')) && !permissions::is_bidi_or_separator(c)) +} + +/// `translations.` as an error names it, each part escaped as prompts show text. +fn key(path: &[&str]) -> String { + let parts: Vec = path.iter().map(|p| permissions::display_text(p, MAX_SHOWN_FIELD)).collect(); + format!("`translations.{}`", parts.join(".")) +} + +/// Checks text `s` at `path` against `max` characters (`lines`: `\n` allowed). +fn check_text(s: &str, max: usize, lines: bool, path: &[&str]) -> Result<()> { + if fits(s, max, lines) { + return Ok(()); + } + let at = key(path); + Err(Error::Manifest(format!("{at} must be 1-{max} printable characters, without direction or line-separator characters"))) +} + +/// The error for the key at `path`, which names a parameter, choice value, group or command the +/// manifest doesn't declare, or translates a field the manifest doesn't give (`options` of a +/// parameter that isn't a choice, `help` of a parameter without one). +fn undeclared(path: &[&str]) -> Error { + let at = key(path); + Error::Manifest(format!("{at} names or translates something the manifest doesn't declare")) +} + +/// Checks the text of parameters `texts` against the parameters `params` they name, at `path`. +fn check_params(texts: &Entries, params: &[(String, crate::Param)], path: &[&str]) -> Result<()> { + for (k, t) in &texts.0 { + let here = [path, &[k.as_str()]].concat(); + let Some((_, p)) = params.iter().find(|(name, _)| name == k) else { + return Err(undeclared(&here)); + }; + if let Some(label) = &t.label { + check_text(label, MAX_LABEL, false, &[here.as_slice(), &["label"]].concat())?; + } + if let Some(help) = &t.help { + let at = [here.as_slice(), &["help"]].concat(); + if p.ui.help.is_none() { + return Err(undeclared(&at)); + } + check_text(help, MAX_HELP, true, &at)?; + } + if t.options.is_empty() { + continue; + } + let ParamSpec::Choice { options, .. } = &p.spec else { + return Err(undeclared(&[here.as_slice(), &["options"]].concat())); + }; + for (value, label) in &t.options.0 { + let at = [here.as_slice(), &["options", value.as_str()]].concat(); + if !options.contains(value) { + return Err(undeclared(&at)); + } + check_text(label, MAX_NAME, false, &at)?; + } + } + Ok(()) +} + +impl Manifest { + /// `translations` gives at most [`MAX_LANGUAGES`] languages, each by a distinct language code + /// ([`valid_language_code`]; case doesn't tell codes apart), and names only what the manifest + /// declares: its parameters, their choices' values, its groups and its commands. Each text + /// follows the rules of the text it translates, without direction or line-separator + /// characters, and `help` translates a `help` the parameter gives. The error names the key. + pub(crate) fn validate_translations(&self) -> Result<()> { + let langs = &self.translations.0; + if langs.len() > MAX_LANGUAGES { + return Err(Error::Manifest(format!("`translations` gives at most {MAX_LANGUAGES} languages"))); + } + let groups: HashSet<&str> = + self.params.iter().chain(self.commands.iter().flat_map(|c| c.params.iter())).filter_map(|(_, p)| p.ui.group.as_deref()).collect(); + for (i, (lang, c)) in langs.iter().enumerate() { + let lang = lang.as_str(); + if !valid_language_code(lang) || langs.get(..i).is_some_and(|before| before.iter().any(|(b, _)| b.eq_ignore_ascii_case(lang))) { + let at = key(&[lang]); + return Err(Error::Manifest(format!("{at} is not a language code such as `de` or `pt-BR`, or repeats one given before it"))); + } + if let Some(name) = &c.name { + check_text(name, MAX_NAME, false, &[lang, "name"])?; + } + check_params(&c.params, &self.params, &[lang, "params"])?; + for (g, heading) in &c.groups.0 { + let g = g.as_str(); + if !groups.contains(g) { + return Err(undeclared(&[lang, "groups", g])); + } + check_text(heading, MAX_LABEL, false, &[lang, "groups", g])?; + } + for (id, t) in &c.commands.0 { + let id = id.as_str(); + let Some(command) = self.command(id) else { + return Err(undeclared(&[lang, "commands", id])); + }; + if let Some(label) = &t.label { + check_text(label, MAX_NAME, false, &[lang, "commands", id, "label"])?; + } + check_params(&t.params, &command.params, &[lang, "commands", id, "params"])?; + } + } + // A dropdown tells its options apart by their labels: in each language, with the labels a + // language leaves out taken from the language without its region, no two may be the same. + for (lang, _) in langs { + self.check_option_labels(lang, &[lang, "params"])?; + } + for c in self.commands.iter().filter(|c| c.params.iter().any(|(_, p)| matches!(p.spec, ParamSpec::Choice { .. }))) { + let own = self.for_command(c); + for (lang, _) in langs { + own.check_option_labels(lang, &[lang, "commands", c.id.as_str(), "params"])?; + } + } + Ok(()) + } + + /// Checks that no two options of a choice show the same label in language `lang`, naming the + /// choice's `options` under `path`. + fn check_option_labels(&self, lang: &str, path: &[&str]) -> Result<()> { + for (k, p) in &self.params { + let ParamSpec::Choice { options, .. } = &p.spec else { continue }; + let shown: Vec<&str> = options.iter().map(|o| self.option_label_in(k, o, lang)).collect(); + if shown.iter().enumerate().any(|(i, s)| shown.get(..i).is_some_and(|before| before.contains(s))) { + let at = key(&[path, &[k.as_str(), "options"]].concat()); + return Err(Error::Manifest(format!("{at} gives two options the same label"))); + } + } + Ok(()) + } + + /// The translations command `c`'s manifest ([`Manifest::for_command`]) shows: in each language, + /// `c`'s label as its name, `c`'s parameters' text and the group headings. + pub(crate) fn command_translations(&self, c: &Command) -> Translations { + let langs = self.translations.0.iter().map(|(lang, cat)| { + let own = cat.commands.get(&c.id); + let catalog = Catalog { + name: own.and_then(|t| t.label.clone()), + params: own.map(|t| t.params.clone()).unwrap_or_default(), + groups: cat.groups.clone(), + commands: Entries::default(), + }; + (lang.clone(), catalog) + }); + Entries(langs.collect()) + } + + /// The plug-in's name in language `lang` (an app language code such as `de` or `pt-br`): its + /// translation, else the manifest's `name`. + pub fn name_in(&self, lang: &str) -> &str { + self.translations.name_in(lang).unwrap_or(&self.name) + } + + /// [`Manifest::name_in`] as menus show it: trimmed, control and bidirectional characters + /// escaped, at most [`MAX_SHOWN_NAME`] characters. + pub fn shown_name(&self, lang: &str) -> String { + permissions::display_text(self.name_in(lang).trim(), MAX_SHOWN_NAME) + } + + /// Command `c`'s label in language `lang`, as menus show it ([`Command::shown_label`]). + pub fn shown_command_label(&self, c: &Command, lang: &str) -> String { + let label = self.translations.find(lang, |t| t.commands.get(&c.id).and_then(|t| t.label.as_deref())).unwrap_or(&c.label); + permissions::display_text(label.trim(), MAX_SHOWN_NAME) + } + + /// Parameter `k`'s label in language `lang`: its translation, else its `label` (`None`: it + /// has neither). + pub fn param_label_in(&self, k: &str, lang: &str) -> Option<&str> { + let own = self.param(k).and_then(|p| p.ui.label.as_deref()); + self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.label.as_deref())).or(own) + } + + /// Parameter `k`'s help in language `lang`: its translation, else its `help`. + pub fn param_help_in(&self, k: &str, lang: &str) -> Option<&str> { + let own = self.param(k).and_then(|p| p.ui.help.as_deref()); + self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.help.as_deref())).or(own) + } + + /// The label of value `option` of choice `k` in language `lang`: its translation, else the + /// value itself. + pub fn option_label_in<'a>(&'a self, k: &str, option: &'a str, lang: &str) -> &'a str { + self.translations.find(lang, |c| c.params.get(k).and_then(|t| t.options.get(option)).map(String::as_str)).unwrap_or(option) + } + + /// The heading of group `group` in language `lang`: its translation, else `group`. + pub fn group_in<'a>(&'a self, group: &'a str, lang: &str) -> &'a str { + self.translations.find(lang, |c| c.groups.get(group).map(String::as_str)).unwrap_or(group) + } +} + +#[cfg(test)] +mod tests { + use serde_json::{Value, json}; + + use super::*; + + const TRANSLATED: &str = r#"{"id":"org.example.tidy","name":"Tidy","kind":"filter", + "params":{"mode":{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."}, + "steps":{"type":"int","min":1,"max":9,"group":"Shape"}}, + "commands":[{"id":"grow","label":"Grow","params":{"by":{"type":"number","min":0,"max":10,"default":2,"label":"By","group":"Shape"}}}, + {"id":"shrink","label":"Shrink"}], + "translations":{ + "de":{"name":"Aufräumen","params":{"mode":{"label":"Modus","help":"Wie stark.","options":{"soft":"Weich"}},"steps":{"label":"Schritte"}}, + "groups":{"Shape":"Form"}, + "commands":{"grow":{"label":"Wachsen","params":{"by":{"label":"Um"}}}}}, + "pt":{"name":"Arrumar","commands":{"shrink":{"label":"Encolher"}}}, + "pt-BR":{"name":"Organizar"}}}"#; + + fn translated() -> Manifest { + Manifest::parse(TRANSLATED.as_bytes()).unwrap() + } + + /// A German UI shows the German text; any language without a catalog shows the manifest's own. + #[test] + fn a_language_shows_its_text_and_others_the_manifests_own() { + let m = translated(); + assert_eq!(m.name_in("de"), "Aufräumen"); + assert_eq!(m.shown_name("de"), "Aufräumen"); + assert_eq!(m.name_in("de-at"), "Aufräumen", "a region falls back to its language"); + for other in ["en", "fr", "ja", "zh-hant"] { + assert_eq!(m.name_in(other), "Tidy", "{other}"); + assert_eq!(m.param_label_in("mode", other), Some("Mode"), "{other}"); + assert_eq!(m.param_label_in("steps", other), None, "{other}"); + assert_eq!(m.option_label_in("mode", "soft", other), "soft", "{other}"); + assert_eq!(m.group_in("Shape", other), "Shape", "{other}"); + } + assert_eq!(m.param_label_in("mode", "de"), Some("Modus")); + assert_eq!(m.param_label_in("steps", "de"), Some("Schritte"), "a label for a parameter that gives none"); + assert_eq!(m.param_help_in("mode", "de"), Some("Wie stark.")); + assert_eq!((m.option_label_in("mode", "soft", "de"), m.option_label_in("mode", "hard", "de")), ("Weich", "hard")); + assert_eq!(m.group_in("Shape", "de"), "Form"); + let grow = m.command("grow").unwrap(); + assert_eq!((m.shown_command_label(grow, "de"), m.shown_command_label(grow, "en")), ("Wachsen".into(), "Grow".into())); + // A command's dialog shows its own text in that language. + let run = m.for_command(grow); + assert_eq!((run.name_in("de"), run.param_label_in("by", "de"), run.group_in("Shape", "de")), ("Wachsen", Some("Um"), "Form")); + assert_eq!((run.name_in("en"), run.param_label_in("by", "en")), ("Grow", Some("By"))); + // The text is shown only: what runs and what plugin.list reads keep the manifest's own. + assert_eq!((m.name.as_str(), grow.label.as_str(), grow.id.as_str()), ("Tidy", "Grow", "grow")); + assert_eq!(Value::Object(m.resolve_params(&json!({"mode": "soft"})).unwrap())["mode"], json!("soft")); + } + + /// `pt-br` text comes from `pt-br`, then `pt`, then the manifest, each piece on its own. + #[test] + fn a_region_falls_back_to_its_language_and_then_the_manifest() { + let m = translated(); + assert_eq!(m.name_in("pt-br"), "Organizar", "codes match without regard to case"); + assert_eq!(m.name_in("pt"), "Arrumar"); + assert_eq!(m.name_in("pt-pt"), "Arrumar"); + let shrink = m.command("shrink").unwrap(); + assert_eq!(m.shown_command_label(shrink, "pt-br"), "Encolher", "from pt"); + let grow = m.command("grow").unwrap(); + assert_eq!(m.shown_command_label(grow, "pt-br"), "Grow", "from the manifest"); + } + + #[test] + fn translations_round_trip_and_are_left_out_when_absent() { + let m = translated(); + let written = serde_json::to_value(&m).unwrap(); + assert_eq!(written["translations"]["pt-BR"], json!({"name": "Organizar"})); + assert_eq!(Manifest::parse(&serde_json::to_vec(&m).unwrap()).unwrap(), m); + let plain = Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap(); + assert!(serde_json::to_value(&plain).unwrap().get("translations").is_none()); + assert_eq!(plain.name_in("de"), "x"); + } + + /// A bad code, text a source field couldn't hold, text that changes direction, and a key the + /// manifest doesn't declare are refused with an error naming the key. + #[test] + fn bad_translations_are_refused_naming_the_key() { + let with = |translations: &str| { + format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["a","b"],"group":"G"}}, + "n":{{"type":"number","min":0,"max":1,"default":0}}}},"commands":[{{"id":"c","label":"C"}}],"translations":{translations}}}"# + ) + }; + let long = "x".repeat(MAX_NAME + 1); + let long_label = format!(r#"{{"de":{{"params":{{"n":{{"label":"{}"}}}}}}}}"#, "x".repeat(MAX_LABEL + 1)); + let long_name = format!(r#"{{"de":{{"name":"{long}"}}}}"#); + for (translations, says) in [ + (r#"{"german":{"name":"X"}}"#, "`translations.german` is not a language code"), + (r#"{"d":{"name":"X"}}"#, "`translations.d` is not a language code"), + (r#"{"de-":{"name":"X"}}"#, "`translations.de-` is not a language code"), + (r#"{"de_DE":{"name":"X"}}"#, "`translations.de_DE` is not a language code"), + (r#"{"x-klingon":{"name":"X"}}"#, "`translations.x-klingon` is not a language code"), + (r#"{"":{"name":"X"}}"#, "`translations.` is not a language code"), + (r#"{"de":{"name":"X"},"DE":{"name":"Y"}}"#, "`translations.DE` is not a language code such as `de` or `pt-BR`, or repeats one"), + (r#"{"de":{"name":""}}"#, "`translations.de.name` must be 1-64"), + (r#"{"de":{"name":" "}}"#, "`translations.de.name` must be 1-64"), + (long_name.as_str(), "`translations.de.name` must be 1-64"), + (r#"{"de":{"name":"a\u0007b"}}"#, "`translations.de.name`"), + (r#"{"de":{"commands":{"c":{"label":"a\nb"}}}}"#, "`translations.de.commands.c.label` must be"), + ( + r#"{"de":{"commands":{"nope":{"label":"N"}}}}"#, + "`translations.de.commands.nope` names or translates something the manifest doesn't declare", + ), + (r#"{"de":{"params":{"nope":{"label":"N"}}}}"#, "`translations.de.params.nope` names or translates"), + (long_label.as_str(), "`translations.de.params.n.label` must be 1-64"), + (r#"{"de":{"params":{"n":{"help":"H"}}}}"#, "`translations.de.params.n.help` names or translates"), + (r#"{"de":{"params":{"n":{"options":{"a":"A"}}}}}"#, "`translations.de.params.n.options` names or translates"), + (r#"{"de":{"params":{"mode":{"options":{"c":"C"}}}}}"#, "`translations.de.params.mode.options.c` names or translates"), + (r#"{"de":{"params":{"mode":{"options":{"a":""}}}}}"#, "`translations.de.params.mode.options.a` must be"), + (r#"{"de":{"params":{"mode":{"options":{"a":"b"}}}}}"#, "`translations.de.params.mode.options` gives two options the same label"), + (r#"{"de":{"params":{"mode":{"options":{"a":"X","b":"X"}}}}}"#, "gives two options the same label"), + ( + r#"{"pt":{"params":{"mode":{"options":{"a":"Leve"}}}},"pt-BR":{"params":{"mode":{"options":{"b":"Leve"}}}}}"#, + "`translations.pt-BR.params.mode.options` gives two options the same label", + ), + (r#"{"de":{"groups":{"H":"Ha"}}}"#, "`translations.de.groups.H` names or translates"), + ] { + let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{translations}: {e}"); + } + // Characters that change the direction of the text or separate lines, written as JSON + // escapes: right-to-left and left-to-right overrides, isolates, and a line separator. + let esc = |c: u32| format!("\\u{c:04X}"); + for (translations, says) in [ + (format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x202E)), "`translations.de.name` must be"), + (format!(r#"{{"de":{{"name":"Flip{}txt"}}}}"#, esc(0x2067)), "`translations.de.name` must be"), + (format!(r#"{{"de":{{"name":"a{}b"}}}}"#, esc(0x2028)), "`translations.de.name` must be"), + (format!(r#"{{"de":{{"commands":{{"c":{{"label":"{}C"}}}}}}}}"#, esc(0x202E)), "`translations.de.commands.c.label` must be"), + (format!(r#"{{"de":{{"params":{{"n":{{"label":"{}N"}}}}}}}}"#, esc(0x202D)), "`translations.de.params.n.label` must be"), + (format!(r#"{{"de":{{"params":{{"mode":{{"options":{{"a":"{}A"}}}}}}}}}}"#, esc(0x202B)), "`translations.de.params.mode.options.a`"), + (format!(r#"{{"de":{{"groups":{{"G":"{}Ge"}}}}}}"#, esc(0x2066)), "`translations.de.groups.G` must be"), + (format!(r#"{{"de{}":{{"name":"X"}}}}"#, esc(0x202E)), "`translations.de\\u{202E}` is not a language code"), + ] { + let e = Manifest::parse(with(&translations).as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{translations}: {e}"); + } + // Keys and types serde reads: an unknown key, a repeated one, and a value of the wrong type. + for (translations, says) in [ + (r#"{"de":{"title":"X"}}"#, "unknown field `title`"), + (r#"{"de":{"params":{"n":{"unit":"mm"}}}}"#, "unknown field `unit`"), + (r#"{"de":{"name":"X","name":"Y"}}"#, "duplicate field `name`"), + (r#"{"de":{"params":{"n":{"label":"A"},"n":{"label":"B"}}}}"#, "`n` is given twice"), + (r#"{"de":{"name":"X"},"de":{"name":"Y"}}"#, "`de` is given twice"), + (r#"{"de":{"name":7}}"#, "manifest"), + (r#"["de"]"#, "manifest"), + (r#""de""#, "manifest"), + ] { + let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{translations}: {e}"); + } + // Right-to-left text without direction characters is text like any other. + let arabic = Manifest::parse(with(r#"{"ar":{"name":"ترتيب","commands":{"c":{"label":"تكبير"}}}}"#).as_bytes()).unwrap(); + assert_eq!(arabic.name_in("ar"), "ترتيب"); + } + + /// At most 16 languages, and the whole manifest, translations included, stays within the + /// manifest's byte limit. + #[test] + fn languages_and_manifest_size_are_capped() { + const CODES: [&str; 17] = ["de", "fr", "es", "it", "pt", "nl", "sv", "da", "fi", "pl", "cs", "hu", "ro", "tr", "ru", "uk", "ja"]; + let manifest = |n: usize| { + let langs: Vec = CODES.iter().take(n).map(|c| format!(r#""{c}":{{"name":"X"}}"#)).collect(); + format!(r#"{{"id":"a","name":"x","kind":"filter","translations":{{{}}}}}"#, langs.join(",")) + }; + assert_eq!(Manifest::parse(manifest(MAX_LANGUAGES).as_bytes()).unwrap().translations.0.len(), MAX_LANGUAGES); + let e = Manifest::parse(manifest(MAX_LANGUAGES + 1).as_bytes()).unwrap_err().to_string(); + assert!(e.contains("`translations` gives at most 16 languages"), "{e}"); + let help = "h".repeat(crate::manifest::MAX_MANIFEST_BYTES); + let big = format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"n":{{"type":"bool","help":"H"}}}},"translations":{{"de":{{"params":{{"n":{{"help":"{help}"}}}}}}}}}}"# + ); + assert!(Manifest::parse(big.as_bytes()).unwrap_err().to_string().contains("limit"), "the manifest's byte limit applies"); + } + + #[test] + fn language_codes() { + for good in ["de", "DE", "pt-br", "pt-BR", "zh-Hant", "zh-Hant-TW", "es-419", "fil", "sr-Latn-RS"] { + assert!(valid_language_code(good), "{good}"); + } + let long = format!("de-{}", ["abcdefgh"; 4].join("-")); + for bad in ["", "d", "deutsch", "de-", "-de", "de--at", "de_AT", "de-a", "x-test", "i-klingon", "de-abcdefghi", "1d", long.as_str()] { + assert!(!valid_language_code(bad), "{bad}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index df5789e649..143759d0b6 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -68,11 +68,12 @@ fn three_d_refusal(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, } /// The effect's name (`__label`, English) in the UI language: the catalog may carry it with or -/// without its trailing ellipsis. A plug-in effect's name is shown as it is. +/// without its trailing ellipsis. A plug-in effect's name is the plug-in's in the UI language +/// ([`super::plugin::effect_name`]). fn heading_label(d: &Dialog) -> String { let label = d.str("__label"); if vectorcraft_plugins::effect::plugin_id(&d.str("__effect")).is_some() { - return label; + return super::plugin::effect_name(&d.str("__effect")).unwrap_or(label); } let dotted = format!("{label}…"); let shown = tl!(&dotted); @@ -648,8 +649,11 @@ pub(super) fn own_choices(effect: &str, key: &str, cmyk: bool) -> Option, cmyk: bool) -> Option> { if let Some(plugin) = vectorcraft_plugins::effect::installed(effect) { - return plugin.manifest().param(key).and_then(|p| match &p.spec { - vectorcraft_plugins::ParamSpec::Choice { options, .. } => Some(options.iter().map(|o| (o.clone(), o.clone())).collect()), + let m = plugin.manifest(); + return m.param(key).and_then(|p| match &p.spec { + vectorcraft_plugins::ParamSpec::Choice { options, .. } => { + Some(options.iter().map(|o| (form::plugin_option_label(m, key, o), o.clone())).collect()) + } _ => None, }); } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index f19cd18cda..2e596173f8 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -615,7 +615,8 @@ fn typed_number(x: f64) -> Value { /// page. Parameters outside any group come first, then each group as a section that folds /// ([`Manifest::sections`]); a parameter whose `visibleWhen` the values don't meet is left out /// ([`Manifest::visible`]). Returns true when a value changed. Labels, choices, groups and help are -/// the plug-in's text, shown as they are. A plug-in may declare more parameters +/// the plug-in's text in the UI language ([`vectorcraft_plugins::translations`]), with control and +/// bidirectional characters escaped ([`plugin_text`]). A plug-in may declare more parameters /// ([`MAX_PARAMS`](vectorcraft_plugins::manifest::MAX_PARAMS)) than the window has room for, and /// the rows then scroll ([`super::modal::scrolled_rows`]). pub(super) fn schema_fields(app: &mut crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> bool { @@ -640,7 +641,7 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b // down the dialog; the rows outside groups make up for the indent of a group's rows. let font = egui::TextStyle::Body.resolve(ui.style()); let label_width = (m.params.iter().filter(|(k, _)| visible.contains(k.as_str()))) - .map(|(k, p)| ui.painter().layout_no_wrap(param_label(k, p), font.clone(), egui::Color32::WHITE).size().x) + .map(|(k, _)| ui.painter().layout_no_wrap(param_label(m, k), font.clone(), egui::Color32::WHITE).size().x) .fold(0.0, f32::max); let indent = if sections.iter().any(|(group, _)| group.is_some()) { ui.spacing().indent } else { 0.0 }; super::modal::scrolled_rows(ui, "plugin-fields", |ui| { @@ -653,7 +654,7 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b let grid = egui::Grid::new(("plugin-grid", section)).num_columns(2).spacing([12.0, 8.0]).min_col_width(label_width); grid.show(ui, |ui| { for (k, p) in shown { - let (row_changed, opened) = param_row(ui, d, k, p); + let (row_changed, opened) = param_row(ui, d, m, k, p); changed |= row_changed; help = help.take().or(opened); ui.end_row(); @@ -663,7 +664,9 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b match group { None => rows(ui, label_width + indent), Some(g) => { - egui::CollapsingHeader::new(g).id_salt(("plugin-group", g)).default_open(true).show(ui, |ui| rows(ui, label_width)); + // The section is kept by the manifest's group, whatever language heads it. + let heading = plugin_text(m.group_in(g, plugin_lang())); + egui::CollapsingHeader::new(heading).id_salt(("plugin-group", g)).default_open(true).show(ui, |ui| rows(ui, label_width)); } } } @@ -671,18 +674,56 @@ pub(super) fn schema_rows(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest) -> (b (changed, help) } -/// The label of parameter `k`'s row: its manifest `label`, else its name spaced out. -fn param_label(k: &str, p: &Param) -> String { - p.ui.label.as_ref().map_or_else(|| humanize(k), |l| format!("{l}:")) +/// The UI language's code, which a plug-in's translations are looked up under. +fn plugin_lang() -> &'static str { + crate::i18n::current().code() +} + +/// Plug-in text `s` as a dialog shows it: each line with its control and bidirectional characters +/// escaped ([`vectorcraft_plugins::permissions::display_text`]), so a label or help can't reorder +/// the text around it. +fn plugin_text(s: &str) -> String { + let lines: Vec = + s.split('\n').map(|l| vectorcraft_plugins::permissions::display_text(l, vectorcraft_plugins::dialog::MAX_HELP)).collect(); + lines.join("\n") +} + +/// Parameter `k`'s `label` in manifest `m`, in the UI language as dialogs show it ([`plugin_text`]); +/// `None` when it gives none. +pub(crate) fn plugin_param_label(m: &Manifest, k: &str) -> Option { + m.param_label_in(k, plugin_lang()).map(plugin_text) +} + +/// Parameter `k`'s `help` in manifest `m`, in the UI language as dialogs show it. +pub(crate) fn plugin_param_help(m: &Manifest, k: &str) -> Option { + m.param_help_in(k, plugin_lang()).map(plugin_text) +} + +/// The label of value `option` of choice `k` in manifest `m`, in the UI language as dialogs show it. +pub(crate) fn plugin_option_label(m: &Manifest, k: &str, option: &str) -> String { + plugin_text(m.option_label_in(k, option, plugin_lang())) +} + +/// The label of parameter `k`'s row in manifest `m`: its `label` in the UI language, else its name +/// spaced out. +fn param_label(m: &Manifest, k: &str) -> String { + plugin_param_label(m, k).map_or_else(|| humanize(k), |l| format!("{l}:")) } /// One row of [`schema_fields`]: parameter `k`'s label and value field → whether the value changed, /// and the help page asked for. -fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Option) { +fn param_row(ui: &mut egui::Ui, d: &mut Dialog, m: &Manifest, k: &str, p: &Param) -> (bool, Option) { let t = Tokens::get(ui.ctx()); - let label = param_label(k, p); + let label = param_label(m, k); let shown_label = ui.label(egui::RichText::new(&label).color(t.text)); - let shown_label = if let Some(help) = &p.ui.help { shown_label.on_hover_text(help) } else { shown_label }; + let shown_label = match plugin_param_help(m, k) { + Some(help) => shown_label.on_hover_text(help), + None => shown_label, + }; + let choices: Vec = match &p.spec { + ParamSpec::Choice { options, .. } => options.iter().map(|o| plugin_option_label(m, k, o)).collect(), + _ => Vec::new(), + }; let cur = d.fields.get(k).cloned().unwrap_or_else(|| p.spec.default_value()); let unit = p.ui.unit.as_deref().unwrap_or_default(); let suffix = unit_suffix(unit); @@ -691,7 +732,7 @@ fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Op .horizontal(|ui| { // The row's painted label names every input in its value column (egui 0.37's strict // accessibility gate), not only the first one. - let (new, in_field) = ui.label_inputs_by(shown_label.id, |ui| value_field(ui, k, &label, &p.spec, &cur, &suffix)); + let (new, in_field) = ui.label_inputs_by(shown_label.id, |ui| value_field(ui, k, &label, &p.spec, &choices, &cur, &suffix)); if !in_field && !unit.is_empty() { ui.label(egui::RichText::new(unit).color(t.text_dim)); } @@ -707,10 +748,10 @@ fn param_row(ui: &mut egui::Ui, d: &mut Dialog, k: &str, p: &Param) -> (bool, Op (changed, opened) } -/// The field of parameter `k`'s value `cur` (a checkbox is called by the row's `label`) → the new -/// value when it changed, and whether the field shows `suffix` (numbers do; the other fields leave -/// the unit to a label after them). -fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: &Value, suffix: &str) -> (Option, bool) { +/// The field of parameter `k`'s value `cur` (a checkbox is called by the row's `label`; a choice +/// shows `choices`, the label of each option in order) → the new value when it changed, and whether +/// the field shows `suffix` (numbers do; the other fields leave the unit to a label after them). +fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, choices: &[String], cur: &Value, suffix: &str) -> (Option, bool) { match spec { ParamSpec::Number { min, max, .. } => { let x = cur.as_f64().unwrap_or(*min); @@ -737,9 +778,10 @@ fn value_field(ui: &mut egui::Ui, k: &str, label: &str, spec: &ParamSpec, cur: & (crate::widgets::check_box(ui, label, b, true).then(|| json!(!b)), false) } ParamSpec::Choice { options, .. } => { - let labels: Vec<&str> = options.iter().map(String::as_str).collect(); - let chosen = - crate::widgets::dropdown_names_named(ui, ("plugin-choice", k), Some(label), cur.as_str().unwrap_or_default(), &labels, 140.0); + let labels: Vec<&str> = choices.iter().map(String::as_str).collect(); + // The option chosen now, by its label in `choices`. + let shown = options.iter().position(|o| Some(o.as_str()) == cur.as_str()).and_then(|i| labels.get(i).copied()).unwrap_or_default(); + let chosen = crate::widgets::dropdown_names_named(ui, ("plugin-choice", k), Some(label), shown, &labels, 140.0); (chosen.and_then(|i| options.get(i)).map(|o| json!(o)), false) } ParamSpec::Text { max_length, .. } => { diff --git a/crates/ui-egui/src/dialogs/plugin.rs b/crates/ui-egui/src/dialogs/plugin.rs index 706188f6da..c4dfe69d86 100644 --- a/crates/ui-egui/src/dialogs/plugin.rs +++ b/crates/ui-egui/src/dialogs/plugin.rs @@ -43,9 +43,57 @@ const CMD: &str = "plugin.run"; /// Object › Plug-ins' header while no filter plug-in is installed. pub const NO_FILTERS: &str = "No filter plug-ins installed"; -/// Headed by the plug-in's name, as it is (plug-in text is never translated). -pub(super) const SPEC: DialogSpec = - DialogSpec { heading: |d| d.str("__label"), body, confirm, preview: true, max_width: Some(420.0), ..DialogSpec::FORM }; +/// Headed by the plug-in's name, or the command's label, in the UI language ([`heading`]). +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, preview: true, max_width: Some(420.0), ..DialogSpec::FORM }; + +/// The UI language's code, which a plug-in's translations are looked up under +/// ([`vectorcraft_plugins::translations`]): plug-in text comes from the plug-in, never from the +/// app's catalogs. +fn lang() -> &'static str { + crate::i18n::current().code() +} + +/// Menu path `path` (English, `›`-separated) with each segment put through `tr`, except the +/// segments after Object › Plug-ins or Effect › Plug-ins: those are a plug-in's name and its items, +/// already in the UI language from the plug-in's translations. +pub(crate) fn translate_path<'a>(path: &'a str, tr: impl Fn(&'a str) -> &'a str) -> String { + let parts: Vec<&str> = path.split(" › ").collect(); + let plugin = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", _, ..]); + parts.iter().enumerate().map(|(i, s)| if plugin && i >= 2 { s } else { tr(s) }).collect::>().join(" › ") +} + +/// The heading of plug-in dialog `d`: its command's label (`__command`), else its plug-in's name, +/// in the UI language as menus show it, read each time it is drawn so a change of language shows +/// at once; `__label` once the plug-in is gone. +fn heading(d: &Dialog) -> String { + let command = d.str("__command"); + let shown = match command.is_empty() { + true => shown_name(&d.str("__plugin")), + false => vectorcraft_engine::cmd::plugin::command_of(&command).map(|(plugin, c)| plugin.manifest().shown_command_label(&c, lang())), + }; + shown.unwrap_or_else(|| d.str("__label")) +} + +/// Plug-in `id`'s name in the UI language as menus show it, without a trailing ellipsis (`None` +/// while no such plug-in is installed). +pub(crate) fn shown_name(id: &str) -> Option { + registry::get(id).map(|p| p.manifest().shown_name(lang()).trim_end_matches('…').to_string()) +} + +/// The name of live effect `effect` (an effect id) in the UI language when a plug-in gives it +/// ([`shown_name`]); `None` for a built-in effect. +pub(crate) fn effect_name(effect: &str) -> Option { + vectorcraft_plugins::effect::plugin_id(effect).and_then(shown_name) +} + +/// Effect › Plug-ins' label for live effect `e`: its plug-in's name in the UI language, with an +/// ellipsis when it opens a dialog ([`label`]); the catalog's label once the plug-in is gone. +pub(crate) fn effect_item_label(e: &vectorcraft_effects::EffectInfo) -> &'static str { + match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) { + Some(p) => label(&p.manifest().shown_name(lang()), !p.manifest().params.is_empty()), + None => e.label, + } +} /// A menu label for plug-in `name`: with an ellipsis when it opens a dialog. fn label(name: &str, has_params: bool) -> &'static str { @@ -56,7 +104,7 @@ fn label(name: &str, has_params: bool) -> &'static str { /// A filter or live effect `plugin`'s item `own`, as the menu lists it: alone, or for a plug-in /// with commands of its own, a submenu named after it holding `own` and then its commands. Each /// command runs its command id (`plugin..`), with an ellipsis when it has parameters, -/// whose dialog [`open_command`] opens. +/// whose dialog [`open_command`] opens. Names and labels are in the UI language. fn with_commands(plugin: &Plugin, own: Item) -> Item { let m = plugin.manifest(); if m.commands.is_empty() { @@ -65,18 +113,21 @@ fn with_commands(plugin: &Plugin, own: Item) -> Item { let mut items = vec![own, Item::Sep]; items.extend(m.commands.iter().map(|c| { let id = registry::intern(&vectorcraft_engine::cmd::plugin::command_id(&m.id, &c.id)); - Item::Cmd(label(&c.shown_label(), !c.params.is_empty()), id, Value::Null) + Item::Cmd(label(&m.shown_command_label(c, lang()), !c.params.is_empty()), id, Value::Null) })); - Item::Sub(registry::intern(&permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)), items) + Item::Sub(registry::intern(&m.shown_name(lang())), items) } -/// Object › Plug-ins: the installed object filters (each with its commands, if it has any), then -/// Install Plug-in… and Reload Plug-ins. +/// Object › Plug-ins: the installed object filters by their names in the UI language (each with +/// its commands, if it has any), then Install Plug-in… and Reload Plug-ins. pub fn object_menu() -> Vec { let mut items: Vec = registry::list() .iter() .filter(|p| p.manifest().kind == Kind::Filter) - .map(|p| with_commands(p, Item::Cmd(label(&p.manifest().name, !p.manifest().params.is_empty()), "plugin.dialog", json!({ "id": p.id() })))) + .map(|p| { + let m = p.manifest(); + with_commands(p, Item::Cmd(label(&m.shown_name(lang()), !m.params.is_empty()), "plugin.dialog", json!({ "id": p.id() }))) + }) .collect(); if items.is_empty() { items.push(Item::Header(NO_FILTERS)); @@ -92,11 +143,15 @@ pub fn object_menu() -> Vec { /// File › Open With's header while no importer plug-in is installed. pub const NO_IMPORTERS: &str = "No importer plug-ins installed"; -/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name. +/// File › Open With: the installed importers (`file.openWith {importer}`), each by its name in the +/// UI language. pub fn open_with_menu() -> Vec { let items: Vec = vectorcraft_plugins::import::installed() .iter() - .map(|p| Item::Cmd(label(&p.manifest().name, true), "file.openWith", json!({ "importer": vectorcraft_plugins::export::format_id(p.id()) }))) + .map(|p| { + let importer = vectorcraft_plugins::export::format_id(p.id()); + Item::Cmd(label(&p.manifest().shown_name(lang()), true), "file.openWith", json!({ "importer": importer })) + }) .collect(); if items.is_empty() { vec![Item::Header(NO_IMPORTERS)] } else { items } } @@ -107,9 +162,10 @@ pub fn effect_menu() -> Option { let items: Vec = vectorcraft_effects::plugin_effects() .into_iter() .map(|e| { + let label = effect_item_label(&e); let own = match e.defaults.as_object().is_some_and(|o| o.is_empty()) { - true => Item::Cmd(e.label, "effect.apply", json!({ "effect": e.id })), - false => Item::Cmd(e.label, "effect.dialog", json!({ "effect": e.id })), + true => Item::Cmd(label, "effect.apply", json!({ "effect": e.id })), + false => Item::Cmd(label, "effect.dialog", json!({ "effect": e.id })), }; match vectorcraft_plugins::effect::plugin_id(e.id).and_then(registry::get) { Some(plugin) => with_commands(&plugin, own), @@ -273,15 +329,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// The dialog kind of an exporter's parameters, after Export As picked the file. pub const EXPORT_KIND: &str = "pluginExport"; -/// Headed by the plug-in's name, as it is; Export writes the file. -pub(super) const EXPORT_SPEC: DialogSpec = DialogSpec { - heading: |d| d.str("__label"), - body: export_body, - confirm: export_confirm, - ok: Some("Export"), - max_width: Some(420.0), - ..DialogSpec::FORM -}; +/// Headed by the plug-in's name in the UI language ([`heading`]); Export writes the file. +pub(super) const EXPORT_SPEC: DialogSpec = + DialogSpec { heading, body: export_body, confirm: export_confirm, ok: Some("Export"), max_width: Some(420.0), ..DialogSpec::FORM }; /// Export As with exporter `plugin`, which has parameters: its fields at their defaults, and /// `export`, the export's own parameters (`format`, `path`, …), kept for Export. @@ -310,15 +360,9 @@ fn export_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result /// The dialog kind of an importer's parameters, after Open With picked the file. pub const IMPORT_KIND: &str = "pluginImport"; -/// Headed by the plug-in's name, as it is; Open opens the file. -pub(super) const IMPORT_SPEC: DialogSpec = DialogSpec { - heading: |d| d.str("__label"), - body: export_body, - confirm: import_confirm, - ok: Some("Open"), - max_width: Some(420.0), - ..DialogSpec::FORM -}; +/// Headed by the plug-in's name in the UI language ([`heading`]); Open opens the file. +pub(super) const IMPORT_SPEC: DialogSpec = + DialogSpec { heading, body: export_body, confirm: import_confirm, ok: Some("Open"), max_width: Some(420.0), ..DialogSpec::FORM }; /// Open With with importer `plugin`, which has parameters: its fields at their defaults, and /// `open`, Open With's own parameters (`path`, `importer`, and `picked` for a file from the diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 4561f3dc73..16356868d7 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -720,6 +720,7 @@ impl PluginIntField { paint_output: false, commands: Vec::new(), command_allowlist: Vec::new(), + translations: Default::default(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { @@ -819,6 +820,75 @@ fn plugin_color_parameter_shows_a_color_button() { } } +/// Every text `shape` draws. +fn drawn_texts(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| drawn_texts(s, out)), + _ => {} + } +} + +/// A plug-in's dialog shows the text its manifest's `translations` give in the UI language (the +/// heading, a label, a group heading and a choice's label) and its own text in any other language; +/// the choice still passes its value. Plug-in text with a right-to-left override is drawn escaped. +#[test] +fn plugin_dialogs_show_the_plugins_text_in_the_ui_language() { + let id = "test.dialogs.translated"; + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + let manifest = format!( + r#"{{"id":"{id}","name":"Tidy","kind":"filter","params":{{ + "mode":{{"type":"choice","options":["soft","hard"],"label":"Mode","group":"Shape","help":"How hard."}}, + "flip":{{"type":"bool","label":"Flip{rlo}txt"}}}}, + "commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"number","min":0,"max":10,"default":2,"label":"By"}}}}}}], + "translations":{{"de":{{"name":"Aufräumen","params":{{"mode":{{"label":"Modus","options":{{"soft":"Weich"}}}}}}, + "groups":{{"Shape":"Form"}},"commands":{{"grow":{{"label":"Wachsen","params":{{"by":{{"label":"Um"}}}}}}}}}}}}}}"# + ); + let module = wat::parse_str(vectorcraft_plugins::wat::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let installed = vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let drawn = |lang: &str, m: &vectorcraft_plugins::Manifest, fields: serde_json::Value| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered")); + let mut d = Dialog::new(plugin::KIND, fields); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + form::schema_rows(ui, &mut d, m); + }); + out.textures_delta.clear(); + let mut texts = Vec::new(); + out.shapes.iter().for_each(|s| drawn_texts(&s.shape, &mut texts)); + crate::i18n::set_current(crate::i18n::Lang::EN); + texts + }; + let m = installed.manifest(); + let de = drawn("de", m, json!({"mode": "soft"})); + for text in ["Modus:", "Weich", "Form", "Flip\\u{202E}txt:"] { + assert!(de.iter().any(|t| t == text), "{text} in German: {de:?}"); + } + assert!(!de.iter().any(|t| t == "Mode:" || t == "soft" || t == "Shape"), "{de:?}"); + let en = drawn("en", m, json!({"mode": "soft"})); + for text in ["Mode:", "soft", "Shape"] { + assert!(en.iter().any(|t| t == text), "{text} in English: {en:?}"); + } + assert!(!en.iter().chain(&de).any(|t| t.contains('\u{202E}')), "the override is never drawn as one"); + // The heading follows the language it is drawn in, for the filter and for its command. + let own = Dialog::new(plugin::KIND, json!({"__plugin": id, "__label": "Tidy"})); + let command = Dialog::new(plugin::KIND, json!({"__plugin": id, "__label": "Grow", "__command": format!("plugin.{id}.grow")})); + let heading = |lang: &str, d: &Dialog| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let shown = (plugin::SPEC.heading)(d); + crate::i18n::set_current(crate::i18n::Lang::EN); + shown + }; + assert_eq!((heading("de", &own), heading("en", &own)), ("Aufräumen".to_string(), "Tidy".to_string())); + assert_eq!((heading("de", &command), heading("fr", &command)), ("Wachsen".to_string(), "Grow".to_string())); + let grow = m.for_command(m.command("grow").unwrap()); + assert!(drawn("de", &grow, json!({})).iter().any(|t| t == "Um:")); + vectorcraft_plugins::registry::remove(id); +} + #[test] fn a_dialog_opens_with_its_first_field_focused_so_typing_and_enter_apply() { let mut app = app(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 167737554d..436e92c147 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -6677,6 +6677,7 @@ axis Y Axis Y ос # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Да се инсталира ли „{name}“, който иска тези права? ID: {id} ID: {id} + Manifest name: {name} Име в манифеста: {name} Version: {version} Версия: {version} Install “{name}” in place of the plug-in with the same ID? Да се инсталира ли „{name}“ на мястото на приставката със същия ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Този файл не е приставката, инсталирана преди с този ID. Той получава настройките и кеша, пазени за този ID. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d6e35ed8..e55b59f674 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -6703,6 +6703,7 @@ axis Y Axis Y osa # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instalirati „{name}”, koji traži ove dozvole? ID: {id} ID: {id} + Manifest name: {name} Naziv u manifestu: {name} Version: {version} Verzija: {version} Install “{name}” in place of the plug-in with the same ID? Instalirati „{name}” umjesto dodatka s istim ID-om? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ova datoteka nije dodatak ranije instaliran s ovim ID-om. Dobija postavke i predmemoriju sačuvane za taj ID. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..a50e9c56ed 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7827,6 +7827,7 @@ variable-list-end {0}, {1} {0} i {1} # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instal·la «{name}», que demana aquests permisos? ID: {id} ID: {id} + Manifest name: {name} Nom al manifest: {name} Version: {version} Versió: {version} Install “{name}” in place of the plug-in with the same ID? Instal·la «{name}» en lloc del complement amb el mateix ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Aquest fitxer no és el complement instal·lat abans amb aquest ID. Rep la configuració i la memòria cau desades per a aquest ID. @@ -7890,6 +7891,11 @@ variable-list-end {0}, {1} {0} i {1} @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a «{name}» no se li ha concedit `{p}`, que la seva sortida necessita: no s’ha canviat res @msg a heavy filter runs in the background, so it can't declare `commands` un filtre pesat s’executa en segon pla, de manera que no pot declarar `commands` @msg at most {MAX_COMMANDS} `commands` com a màxim {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dona com a màxim {MAX_LANGUAGES} idiomes +@msg {at} gives two options the same label {at} dona la mateixa etiqueta a dues opcions +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no és un codi d’idioma com `de` o `pt-BR`, o en repeteix un de donat abans +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} ha de tenir 1-{max} caràcters imprimibles, sense caràcters de direcció ni separadors de línia +@msg {at} names or translates something the manifest doesn't declare {at} anomena o tradueix alguna cosa que el manifest no declara @msg command {name} is declared twice l’ordre {name} està declarada dues vegades @msg command {name}: `label` must be 1-64 printable characters ordre {name}: `label` ha de tenir 1-64 caràcters imprimibles @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ordre {name}: fes servir un id d’1-{MAX_COMMAND_ID} caràcters d’a-z 0-9 _ que comenci per una lletra diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..9331658a1d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -7437,6 +7437,7 @@ axis Y Axis osa Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Nainstalovat „{name}“, který žádá o tato oprávnění? ID: {id} ID: {id} + Manifest name: {name} Název v manifestu: {name} Version: {version} Verze: {version} Install “{name}” in place of the plug-in with the same ID? Nainstalovat „{name}“ místo zásuvného modulu se stejným ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tento soubor není zásuvný modul dříve nainstalovaný s tímto ID. Získá nastavení a mezipaměť uchovávané pro toto ID. @@ -7500,6 +7501,11 @@ axis Y Axis osa Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ nedostal `{p}`, které jeho výstup potřebuje: nic se nezměnilo @msg a heavy filter runs in the background, so it can't declare `commands` těžký filtr běží na pozadí, takže nemůže deklarovat `commands` @msg at most {MAX_COMMANDS} `commands` nejvýše {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` uvádí nejvýše {MAX_LANGUAGES} jazyků +@msg {at} gives two options the same label {at} dává dvěma možnostem stejný popisek +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} není kód jazyka jako `de` nebo `pt-BR`, nebo opakuje kód uvedený dříve +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musí mít 1-{max} tisknutelných znaků, bez znaků směru textu a oddělovačů řádků +@msg {at} names or translates something the manifest doesn't declare {at} pojmenovává nebo překládá něco, co manifest nedeklaruje @msg command {name} is declared twice příkaz {name} je deklarován dvakrát @msg command {name}: `label` must be 1-64 printable characters příkaz {name}: `label` musí mít 1-64 tisknutelných znaků @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter příkaz {name}: použijte id o 1-{MAX_COMMAND_ID} znacích z a-z 0-9 _, které začíná písmenem diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..9e950f43af 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -712,6 +712,11 @@ liquify-list-end {0}, {1} {0} og {1} @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed »{name}« fik ikke tildelt `{p}`, som dets output kræver: intet blev ændret @msg a heavy filter runs in the background, so it can't declare `commands` et tungt filter kører i baggrunden, så det kan ikke angive `commands` @msg at most {MAX_COMMANDS} `commands` højst {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` angiver højst {MAX_LANGUAGES} sprog +@msg {at} gives two options the same label {at} giver to valgmuligheder samme etiket +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} er ikke en sprogkode som `de` eller `pt-BR`, eller gentager en, der er angivet før +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} skal være 1-{max} tegn, der kan udskrives, uden retnings- eller linjeskilletegn +@msg {at} names or translates something the manifest doesn't declare {at} navngiver eller oversætter noget, som manifestet ikke erklærer @msg command {name} is declared twice kommandoen {name} er erklæret to gange @msg command {name}: `label` must be 1-64 printable characters kommandoen {name}: `label` skal være 1-64 tegn, der kan udskrives @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommandoen {name}: brug et id på 1-{MAX_COMMAND_ID} tegn fra a-z 0-9 _, der starter med et bogstav @@ -9596,6 +9601,7 @@ axis Y Axis Y-akse # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installér »{name}«, som beder om disse rettigheder? ID: {id} ID: {id} + Manifest name: {name} Navn i manifestet: {name} Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? Installér »{name}« i stedet for det plug-in, der har samme id? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Denne fil er ikke det plug-in, der før var installeret med dette id. Den får de indstillinger og den cache, der er gemt for dette id. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..1be15dae35 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -7020,6 +7020,7 @@ axis Y Axis Y-Achse # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? „{name}“ installieren, das diese Berechtigungen verlangt? ID: {id} ID: {id} + Manifest name: {name} Name im Manifest: {name} Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? „{name}“ anstelle des Plug-ins mit derselben ID installieren? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Diese Datei ist nicht das Plug-in, das vorher mit dieser ID installiert war. Sie erhält die Einstellungen und den Cache, die für diese ID gespeichert sind. @@ -7083,6 +7084,11 @@ axis Y Axis Y-Achse @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“ wurde `{p}` nicht gewährt, das seine Ausgabe braucht: Es wurde nichts geändert @msg a heavy filter runs in the background, so it can't declare `commands` ein schwerer Filter läuft im Hintergrund und kann daher keine `commands` deklarieren @msg at most {MAX_COMMANDS} `commands` höchstens {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` gibt höchstens {MAX_LANGUAGES} Sprachen an +@msg {at} gives two options the same label {at} gibt zwei Optionen dieselbe Beschriftung +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ist kein Sprachcode wie `de` oder `pt-BR` oder wiederholt einen zuvor angegebenen +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} muss 1-{max} druckbare Zeichen lang sein, ohne Schreibrichtungs- oder Zeilentrennzeichen +@msg {at} names or translates something the manifest doesn't declare {at} benennt oder übersetzt etwas, das das Manifest nicht deklariert @msg command {name} is declared twice der Befehl {name} ist doppelt deklariert @msg command {name}: `label` must be 1-64 printable characters Befehl {name}: `label` muss 1-64 druckbare Zeichen haben @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter Befehl {name}: Verwenden Sie eine ID aus 1-{MAX_COMMAND_ID} Zeichen aus a-z 0-9 _, die mit einem Buchstaben beginnt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..03fa786075 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7427,6 +7427,7 @@ axis Y Axis Άξονας Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Να εγκατασταθεί το «{name}», που ζητά αυτά τα δικαιώματα; ID: {id} Αναγνωριστικό: {id} + Manifest name: {name} Όνομα στο manifest: {name} Version: {version} Έκδοση: {version} Install “{name}” in place of the plug-in with the same ID? Να εγκατασταθεί το «{name}» στη θέση του πρόσθετου με το ίδιο αναγνωριστικό; This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Αυτό το αρχείο δεν είναι το πρόσθετο που ήταν εγκατεστημένο πριν με αυτό το αναγνωριστικό. Παίρνει τις ρυθμίσεις και την κρυφή μνήμη που διατηρούνται για αυτό το αναγνωριστικό. @@ -7490,6 +7491,11 @@ axis Y Axis Άξονας Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed στο «{name}» δεν παραχωρήθηκε το `{p}`, που χρειάζεται η έξοδός του: δεν άλλαξε τίποτα @msg a heavy filter runs in the background, so it can't declare `commands` ένα βαρύ φίλτρο εκτελείται στο παρασκήνιο, οπότε δεν μπορεί να δηλώνει `commands` @msg at most {MAX_COMMANDS} `commands` το πολύ {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages το `translations` δίνει το πολύ {MAX_LANGUAGES} γλώσσες +@msg {at} gives two options the same label το {at} δίνει την ίδια ετικέτα σε δύο επιλογές +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it το {at} δεν είναι κωδικός γλώσσας όπως `de` ή `pt-BR`, ή επαναλαμβάνει έναν που δόθηκε πριν +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters το {at} πρέπει να έχει 1-{max} εκτυπώσιμους χαρακτήρες, χωρίς χαρακτήρες κατεύθυνσης ή διαχωρισμού γραμμών +@msg {at} names or translates something the manifest doesn't declare το {at} ονομάζει ή μεταφράζει κάτι που το manifest δεν δηλώνει @msg command {name} is declared twice η εντολή {name} δηλώνεται δύο φορές @msg command {name}: `label` must be 1-64 printable characters εντολή {name}: το `label` πρέπει να έχει 1-64 εκτυπώσιμους χαρακτήρες @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter εντολή {name}: χρησιμοποιήστε αναγνωριστικό 1-{MAX_COMMAND_ID} χαρακτήρων από a-z 0-9 _ που αρχίζει με γράμμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..413e456910 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7413,6 +7413,7 @@ axis Y Axis Eje Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? ¿Instalar “{name}”, que pide estos permisos? ID: {id} ID: {id} + Manifest name: {name} Nombre en el manifiesto: {name} Version: {version} Versión: {version} Install “{name}” in place of the plug-in with the same ID? ¿Instalar “{name}” en lugar del plugin con el mismo ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este archivo no es el plugin instalado antes con este ID. Recibe la configuración y la caché guardadas para ese ID. @@ -7476,6 +7477,11 @@ axis Y Axis Eje Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” no se le concedió `{p}`, que su resultado necesita: no se cambió nada @msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesado se ejecuta en segundo plano, así que no puede declarar `commands` @msg at most {MAX_COMMANDS} `commands` como máximo {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` da como máximo {MAX_LANGUAGES} idiomas +@msg {at} gives two options the same label {at} da la misma etiqueta a dos opciones +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} no es un código de idioma como `de` o `pt-BR`, o repite uno dado antes +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} debe tener 1-{max} caracteres imprimibles, sin caracteres de dirección ni separadores de línea +@msg {at} names or translates something the manifest doesn't declare {at} nombra o traduce algo que el manifiesto no declara @msg command {name} is declared twice el comando {name} está declarado dos veces @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` debe tener 1-64 caracteres imprimibles @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que empiece por una letra diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..4e424a2741 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -7504,6 +7504,7 @@ axis Y Axis Y-akseli # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Asennetaanko ”{name}”, joka pyytää näitä käyttöoikeuksia? ID: {id} Tunnus: {id} + Manifest name: {name} Nimi manifestissa: {name} Version: {version} Versio: {version} Install “{name}” in place of the plug-in with the same ID? Asennetaanko ”{name}” samaa tunnusta käyttävän laajennuksen tilalle? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tämä tiedosto ei ole laajennus, joka oli aiemmin asennettu tällä tunnuksella. Se saa tälle tunnukselle säilytetyt asetukset ja välimuistin. @@ -7567,6 +7568,11 @@ axis Y Axis Y-akseli @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” ei saanut käyttöoikeutta `{p}`, jota sen tulos tarvitsee: mitään ei muutettu @msg a heavy filter runs in the background, so it can't declare `commands` raskas suodin suoritetaan taustalla, joten se ei voi määritellä `commands`-kohtaa @msg at most {MAX_COMMANDS} `commands` enintään {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` antaa enintään {MAX_LANGUAGES} kieltä +@msg {at} gives two options the same label {at} antaa kahdelle vaihtoehdolle saman nimen +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} ei ole kielikoodi kuten `de` tai `pt-BR`, tai toistaa aiemmin annetun koodin +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} saa olla 1-{max} tulostettavaa merkkiä ilman suunta- tai rivinerotinmerkkejä +@msg {at} names or translates something the manifest doesn't declare {at} nimeää tai kääntää jotain, mitä manifesti ei määrittele @msg command {name} is declared twice komento {name} on määritelty kahdesti @msg command {name}: `label` must be 1-64 printable characters komento {name}: `label`-kentässä on oltava 1-64 tulostettavaa merkkiä @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter komento {name}: käytä 1-{MAX_COMMAND_ID} merkin tunnusta merkeistä a-z 0-9 _, joka alkaa kirjaimella diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..4fc64305db 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7433,6 +7433,7 @@ axis Y Axis Axe Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installer « {name} », qui demande ces autorisations ? ID: {id} ID : {id} + Manifest name: {name} Le manifeste le nomme {name} Version: {version} Version : {version} Install “{name}” in place of the plug-in with the same ID? Installer « {name} » à la place du module externe qui a le même ID ? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ce fichier n’est pas le module externe installé auparavant avec cet ID. Il reçoit les réglages et le cache conservés pour cet ID. @@ -7496,6 +7497,11 @@ axis Y Axis Axe Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed « {name} » n’a pas reçu `{p}`, dont sa sortie a besoin : rien n’a été modifié @msg a heavy filter runs in the background, so it can't declare `commands` un filtre lourd s’exécute en arrière-plan, il ne peut donc pas déclarer `commands` @msg at most {MAX_COMMANDS} `commands` au plus {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` donne au plus {MAX_LANGUAGES} langues +@msg {at} gives two options the same label {at} donne le même libellé à deux options +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} n’est pas un code de langue comme `de` ou `pt-BR`, ou répète un code donné avant +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} doit compter 1-{max} caractères imprimables, sans caractères de direction ni séparateurs de ligne +@msg {at} names or translates something the manifest doesn't declare {at} nomme ou traduit quelque chose que le manifeste ne déclare pas @msg command {name} is declared twice la commande {name} est déclarée deux fois @msg command {name}: `label` must be 1-64 printable characters commande {name} : `label` doit compter 1-64 caractères imprimables @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter commande {name} : utilisez un id de 1-{MAX_COMMAND_ID} caractères parmi a-z 0-9 _ commençant par une lettre diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 0bb7c9b71f..5eadc075d0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1876,6 +1876,7 @@ Max Ascender મહત્તમ એસેન્ડર ICF Top/Right ICF ઉપર/જમણે ID: {id} ID: {id} + Manifest name: {name} મેનિફેસ્ટમાં નામ: {name} Identify Objects By ઑબ્જેક્ટ્સ આ રીતે ઓળખો If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. જો ડ્રોઇંગ ટેબ્લેટની પેન દોરતી ન હોય, તો X11 (XWayland) વિકલ્પ પસંદ કરો. Ignore અવગણો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..45d53ee202 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6621,6 +6621,7 @@ arrowhead Feather पंख # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? "{name}" स्थापित करें, जो ये अनुमतियां मांगता है? ID: {id} ID: {id} + Manifest name: {name} मैनिफ़ेस्ट में नाम: {name} Version: {version} संस्करण: {version} Install “{name}” in place of the plug-in with the same ID? समान ID वाले प्लग-इन की जगह “{name}” इंस्टॉल करें? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. यह फ़ाइल इस ID के साथ पहले इंस्टॉल किया गया प्लग-इन नहीं है। इसे उस ID के लिए रखी गई सेटिंग्स और कैश मिलते हैं। @@ -6680,6 +6681,11 @@ arrowhead Feather पंख @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” को `{p}` नहीं दी गई, जो उसके आउटपुट को चाहिए: कुछ नहीं बदला @msg a heavy filter runs in the background, so it can't declare `commands` भारी फ़िल्टर पृष्ठभूमि में चलता है, इसलिए वह `commands` घोषित नहीं कर सकता @msg at most {MAX_COMMANDS} `commands` अधिकतम {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` अधिकतम {MAX_LANGUAGES} भाषाएँ देता है +@msg {at} gives two options the same label {at} दो विकल्पों को एक ही लेबल देता है +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} `de` या `pt-BR` जैसा भाषा कोड नहीं है, या पहले दिए गए कोड को दोहराता है +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} में 1-{max} मुद्रण योग्य वर्ण होने चाहिए, दिशा या पंक्ति-विभाजक वर्णों के बिना +@msg {at} names or translates something the manifest doesn't declare {at} ऐसी चीज़ का नाम लेता है या अनुवाद करता है जिसे मैनिफ़ेस्ट घोषित नहीं करता @msg command {name} is declared twice कमांड {name} दो बार घोषित है @msg command {name}: `label` must be 1-64 printable characters कमांड {name}: `label` में 1-64 प्रिंट करने योग्य वर्ण होने चाहिए @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter कमांड {name}: a-z 0-9 _ के 1-{MAX_COMMAND_ID} वर्णों वाली ऐसी id इस्तेमाल करें जो अक्षर से शुरू हो diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..8059e3c8f7 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -7422,6 +7422,7 @@ axis Y Axis Y tengely # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Telepíted a(z) „{name}” bővítményt, amely ezeket az engedélyeket kéri? ID: {id} Azonosító: {id} + Manifest name: {name} Név a manifestben: {name} Version: {version} Verzió: {version} Install “{name}” in place of the plug-in with the same ID? Telepíted a(z) „{name}” bővítményt az azonos azonosítójú bővítmény helyére? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ez a fájl nem az a bővítmény, amely korábban ezzel az azonosítóval volt telepítve. Megkapja az ehhez az azonosítóhoz tárolt beállításokat és gyorsítótárat. @@ -7485,6 +7486,11 @@ axis Y Axis Y tengely @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a(z) „{name}” nem kapta meg a(z) `{p}` engedélyt, amelyre a kimenetének szüksége van: semmi sem változott @msg a heavy filter runs in the background, so it can't declare `commands` a nehéz szűrő a háttérben fut, ezért nem deklarálhat `commands` értéket @msg at most {MAX_COMMANDS} `commands` legfeljebb {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages a `translations` legfeljebb {MAX_LANGUAGES} nyelvet adhat meg +@msg {at} gives two options the same label {at} két lehetőségnek ugyanazt a címkét adja +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nem olyan nyelvkód, mint a `de` vagy a `pt-BR`, vagy egy korábban megadottat ismétel +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 1-{max} nyomtatható karakter lehet, irány- és sorelválasztó karakterek nélkül +@msg {at} names or translates something the manifest doesn't declare {at} olyasmit nevez meg vagy fordít, amit a manifest nem deklarál @msg command {name} is declared twice a(z) {name} parancs kétszer van deklarálva @msg command {name}: `label` must be 1-64 printable characters {name} parancs: a `label` 1-64 nyomtatható karakter legyen @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} parancs: használj 1-{MAX_COMMAND_ID} karakteres, a-z 0-9 _ karakterekből álló, betűvel kezdődő azonosítót diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..b7227a3c2a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -594,6 +594,11 @@ @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” tidak diberi `{p}`, yang diperlukan keluarannya: tidak ada yang diubah @msg a heavy filter runs in the background, so it can't declare `commands` filter berat berjalan di latar belakang, sehingga tidak dapat mendeklarasikan `commands` @msg at most {MAX_COMMANDS} `commands` paling banyak {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` memberikan paling banyak {MAX_LANGUAGES} bahasa +@msg {at} gives two options the same label {at} memberikan label yang sama untuk dua opsi +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} bukan kode bahasa seperti `de` atau `pt-BR`, atau mengulang kode yang diberikan sebelumnya +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} harus berisi 1-{max} karakter yang dapat dicetak, tanpa karakter arah atau pemisah baris +@msg {at} names or translates something the manifest doesn't declare {at} menamai atau menerjemahkan sesuatu yang tidak dideklarasikan manifes @msg command {name} is declared twice perintah {name} dideklarasikan dua kali @msg command {name}: `label` must be 1-64 printable characters perintah {name}: `label` harus berupa 1-64 karakter yang dapat dicetak @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter perintah {name}: gunakan id sepanjang 1-{MAX_COMMAND_ID} karakter dari a-z 0-9 _ yang diawali huruf @@ -7381,6 +7386,7 @@ axis Y Axis Sumbu Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instal “{name}”, yang meminta izin berikut? ID: {id} ID: {id} + Manifest name: {name} Nama di manifes: {name} Version: {version} Versi: {version} Install “{name}” in place of the plug-in with the same ID? Instal “{name}” sebagai pengganti plug-in dengan ID yang sama? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. File ini bukan plug-in yang sebelumnya diinstal dengan ID ini. File ini mendapatkan pengaturan dan cache yang disimpan untuk ID tersebut. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..e3748e5199 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -7059,6 +7059,7 @@ axis Y Axis Asse Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installare “{name}”, che chiede queste autorizzazioni? ID: {id} ID: {id} + Manifest name: {name} Nome nel manifest: {name} Version: {version} Versione: {version} Install “{name}” in place of the plug-in with the same ID? Installare “{name}” al posto del plug-in con lo stesso ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Questo file non è il plug-in installato prima con questo ID. Riceve le impostazioni e la cache conservate per quell’ID. @@ -7122,6 +7123,11 @@ axis Y Axis Asse Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed a “{name}” non è stata concessa `{p}`, che serve al suo risultato: non è stato modificato nulla @msg a heavy filter runs in the background, so it can't declare `commands` un filtro pesante viene eseguito in background, quindi non può dichiarare `commands` @msg at most {MAX_COMMANDS} `commands` al massimo {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` indica al massimo {MAX_LANGUAGES} lingue +@msg {at} gives two options the same label {at} dà la stessa etichetta a due opzioni +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} non è un codice di lingua come `de` o `pt-BR`, o ripete uno indicato prima +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve avere 1-{max} caratteri stampabili, senza caratteri di direzione o separatori di riga +@msg {at} names or translates something the manifest doesn't declare {at} nomina o traduce qualcosa che il manifest non dichiara @msg command {name} is declared twice il comando {name} è dichiarato due volte @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve avere 1-64 caratteri stampabili @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: usa un id di 1-{MAX_COMMAND_ID} caratteri tra a-z 0-9 _ che inizi con una lettera diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..35d55b2518 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7134,6 +7134,7 @@ axis Y Axis Y 軸 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? これらの権限を求める「{name}」をインストールしますか? ID: {id} ID: {id} + Manifest name: {name} マニフェストの名前: {name} Version: {version} バージョン: {version} Install “{name}” in place of the plug-in with the same ID? 同じ ID のプラグインの代わりに「{name}」をインストールしますか? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. このファイルは、以前にこの ID でインストールされていたプラグインではありません。この ID 用に保持されている設定とキャッシュを引き継ぎます。 @@ -7197,6 +7198,11 @@ axis Y Axis Y 軸 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」には出力に必要な `{p}` が付与されていません。何も変更されませんでした @msg a heavy filter runs in the background, so it can't declare `commands` 重いフィルターはバックグラウンドで実行されるため、`commands` を宣言できません @msg at most {MAX_COMMANDS} `commands` `commands` は最大 {MAX_COMMANDS} 個です +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` に指定できる言語は最大 {MAX_LANGUAGES} 個です +@msg {at} gives two options the same label {at} で 2 つの選択肢に同じラベルが付いています +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} は `de` や `pt-BR` のような言語コードではないか、前に指定したコードの繰り返しです +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} は方向制御文字や行区切り文字を含まない 1-{max} 文字の印字可能な文字にしてください +@msg {at} names or translates something the manifest doesn't declare {at} はマニフェストで宣言されていないものを指定または翻訳しています @msg command {name} is declared twice コマンド {name} が 2 回宣言されています @msg command {name}: `label` must be 1-64 printable characters コマンド {name}: `label` は印刷可能な 1-64 文字にしてください @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter コマンド {name}: a-z 0-9 _ からなり英字で始まる 1-{MAX_COMMAND_ID} 文字の ID を使用してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..3e78f5a722 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -9540,6 +9540,7 @@ axis Y Axis Y ღერძი # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? დავაყენოთ „{name}“, რომელიც ამ ნებართვებს ითხოვს? ID: {id} ID: {id} + Manifest name: {name} სახელი მანიფესტში: {name} Version: {version} ვერსია: {version} Install “{name}” in place of the plug-in with the same ID? დავაყენოთ „{name}“ იმავე ID-ის მქონე პლაგინის ნაცვლად? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. ეს ფაილი არ არის ამ ID-ით ადრე დაყენებული პლაგინი. ის მიიღებს ამ ID-სთვის შენახულ პარამეტრებს და ქეშს. @@ -9603,6 +9604,11 @@ axis Y Axis Y ღერძი @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}“-ს არ მიეცა `{p}`, რომელიც მის შედეგს სჭირდება: არაფერი შეცვლილა @msg a heavy filter runs in the background, so it can't declare `commands` მძიმე ფილტრი ფონურ რეჟიმში მუშაობს, ამიტომ მას არ შეუძლია `commands`-ის გამოცხადება @msg at most {MAX_COMMANDS} `commands` მაქსიმუმ {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` იძლევა მაქსიმუმ {MAX_LANGUAGES} ენას +@msg {at} gives two options the same label {at} ორ ვარიანტს ერთსა და იმავე წარწერას აძლევს +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} არ არის ენის კოდი, როგორიცაა `de` ან `pt-BR`, ან იმეორებს ადრე მოცემულ კოდს +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} უნდა იყოს 1-{max} დასაბეჭდი სიმბოლო, მიმართულების და ხაზის გამყოფი სიმბოლოების გარეშე +@msg {at} names or translates something the manifest doesn't declare {at} ასახელებს ან თარგმნის რაღაცას, რასაც მანიფესტი არ აცხადებს @msg command {name} is declared twice ბრძანება {name} ორჯერაა გამოცხადებული @msg command {name}: `label` must be 1-64 printable characters ბრძანება {name}: `label` უნდა შედგებოდეს 1-64 დასაბეჭდი სიმბოლოსგან @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter ბრძანება {name}: გამოიყენეთ 1-{MAX_COMMAND_ID} სიმბოლოიანი id a-z 0-9 _ სიმბოლოებიდან, რომელიც ასოთი იწყება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..ff523d1e27 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -7031,6 +7031,7 @@ axis Y Axis Y축 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 이 권한을 요청하는 “{name}”을(를) 설치하시겠습니까? ID: {id} ID: {id} + Manifest name: {name} 매니페스트의 이름: {name} Version: {version} 버전: {version} Install “{name}” in place of the plug-in with the same ID? 같은 ID의 플러그인 대신 “{name}”을(를) 설치하시겠습니까? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 이 파일은 이전에 이 ID로 설치된 플러그인이 아닙니다. 이 ID에 보관된 설정과 캐시를 받습니다. @@ -7094,6 +7095,11 @@ axis Y Axis Y축 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”에 출력에 필요한 `{p}` 권한이 부여되지 않았습니다. 아무것도 변경되지 않았습니다 @msg a heavy filter runs in the background, so it can't declare `commands` 무거운 필터는 백그라운드에서 실행되므로 `commands`를 선언할 수 없습니다 @msg at most {MAX_COMMANDS} `commands` `commands`는 최대 {MAX_COMMANDS}개입니다 +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations`에는 언어를 최대 {MAX_LANGUAGES}개까지 지정할 수 있습니다 +@msg {at} gives two options the same label {at}에서 두 옵션에 같은 레이블을 지정했습니다 +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}은(는) `de`나 `pt-BR` 같은 언어 코드가 아니거나 앞에서 지정한 코드를 반복합니다 +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}은(는) 방향 문자나 줄 구분 문자 없이 인쇄 가능한 문자 1-{max}자여야 합니다 +@msg {at} names or translates something the manifest doesn't declare {at}은(는) 매니페스트가 선언하지 않은 항목을 지정하거나 번역합니다 @msg command {name} is declared twice 명령 {name}이(가) 두 번 선언되었습니다 @msg command {name}: `label` must be 1-64 printable characters 명령 {name}: `label`은 인쇄 가능한 문자 1-64자여야 합니다 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 명령 {name}: a-z 0-9 _로 이루어지고 문자로 시작하는 1-{MAX_COMMAND_ID}자 ID를 사용하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..647178e610 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -558,6 +558,11 @@ liquify-list-end {0}, {1} {0} en {1} @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” heeft `{p}` niet gekregen, wat de uitvoer ervan nodig heeft: er is niets gewijzigd @msg a heavy filter runs in the background, so it can't declare `commands` een zwaar filter wordt op de achtergrond uitgevoerd, dus kan het geen `commands` declareren @msg at most {MAX_COMMANDS} `commands` maximaal {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` geeft maximaal {MAX_LANGUAGES} talen +@msg {at} gives two options the same label {at} geeft twee opties hetzelfde label +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} is geen taalcode zoals `de` of `pt-BR`, of herhaalt een eerder gegeven code +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} moet 1-{max} afdrukbare tekens zijn, zonder richtings- of regelscheidingstekens +@msg {at} names or translates something the manifest doesn't declare {at} noemt of vertaalt iets wat het manifest niet declareert @msg command {name} is declared twice opdracht {name} is twee keer gedeclareerd @msg command {name}: `label` must be 1-64 printable characters opdracht {name}: `label` moet uit 1-64 afdrukbare tekens bestaan @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter opdracht {name}: gebruik een id van 1-{MAX_COMMAND_ID} tekens uit a-z 0-9 _ die met een letter begint @@ -9434,6 +9439,7 @@ axis Y Axis Y-as # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? „{name}” installeren, dat om deze machtigingen vraagt? ID: {id} ID: {id} + Manifest name: {name} Naam in het manifest: {name} Version: {version} Versie: {version} Install “{name}” in place of the plug-in with the same ID? „{name}” installeren in plaats van de plug-in met dezelfde ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Dit bestand is niet de plug-in die eerder met deze ID was geïnstalleerd. Het krijgt de instellingen en cache die voor die ID bewaard zijn. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..0c6e487cfa 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -7292,6 +7292,7 @@ axis Y Axis Oś Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Zainstalować „{name}”, wtyczkę, która prosi o te uprawnienia? ID: {id} ID: {id} + Manifest name: {name} Nazwa w manifeście: {name} Version: {version} Wersja: {version} Install “{name}” in place of the plug-in with the same ID? Zainstalować „{name}” zamiast wtyczki o tym samym ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Ten plik nie jest wtyczką zainstalowaną wcześniej z tym ID. Otrzyma ustawienia i pamięć podręczną przechowywane dla tego ID. @@ -7355,6 +7356,11 @@ axis Y Axis Oś Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed „{name}” nie otrzymała `{p}`, którego potrzebuje jej wynik: nic nie zmieniono @msg a heavy filter runs in the background, so it can't declare `commands` ciężki filtr działa w tle, więc nie może deklarować `commands` @msg at most {MAX_COMMANDS} `commands` najwyżej {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` podaje najwyżej {MAX_LANGUAGES} języków +@msg {at} gives two options the same label {at} nadaje dwóm opcjom tę samą etykietę +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} nie jest kodem języka takim jak `de` czy `pt-BR` albo powtarza kod podany wcześniej +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} musi mieć 1-{max} drukowalnych znaków, bez znaków kierunku tekstu i separatorów wierszy +@msg {at} names or translates something the manifest doesn't declare {at} nazywa lub tłumaczy coś, czego manifest nie deklaruje @msg command {name} is declared twice polecenie {name} jest zadeklarowane dwa razy @msg command {name}: `label` must be 1-64 printable characters polecenie {name}: `label` musi mieć 1-64 drukowalnych znaków @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter polecenie {name}: użyj id z 1-{MAX_COMMAND_ID} znaków spośród a-z 0-9 _, zaczynającego się od litery diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..59a2544240 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -7336,6 +7336,7 @@ axis Y Axis Eixo Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Instalar “{name}”, que pede estas permissões? ID: {id} ID: {id} + Manifest name: {name} Nome no manifesto: {name} Version: {version} Versão: {version} Install “{name}” in place of the plug-in with the same ID? Instalar “{name}” no lugar do plug-in com o mesmo ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Este arquivo não é o plug-in instalado antes com este ID. Ele recebe as configurações e o cache guardados para esse ID. @@ -7399,6 +7400,11 @@ axis Y Axis Eixo Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” não recebeu `{p}`, de que sua saída precisa: nada foi alterado @msg a heavy filter runs in the background, so it can't declare `commands` um filtro pesado é executado em segundo plano, então não pode declarar `commands` @msg at most {MAX_COMMANDS} `commands` no máximo {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` dá no máximo {MAX_LANGUAGES} idiomas +@msg {at} gives two options the same label {at} dá o mesmo rótulo a duas opções +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} não é um código de idioma como `de` ou `pt-BR`, ou repete um dado antes +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} deve ter 1-{max} caracteres imprimíveis, sem caracteres de direção ou separadores de linha +@msg {at} names or translates something the manifest doesn't declare {at} nomeia ou traduz algo que o manifesto não declara @msg command {name} is declared twice o comando {name} está declarado duas vezes @msg command {name}: `label` must be 1-64 printable characters comando {name}: `label` deve ter 1-64 caracteres imprimíveis @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter comando {name}: use um id de 1-{MAX_COMMAND_ID} caracteres de a-z 0-9 _ que comece com uma letra diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..bd75d9b29d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -7059,6 +7059,7 @@ axis Y Axis Ось Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Установить «{name}», которому нужны эти разрешения? ID: {id} ID: {id} + Manifest name: {name} Имя в манифесте: {name} Version: {version} Версия: {version} Install “{name}” in place of the plug-in with the same ID? Установить «{name}» вместо модуля с тем же ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Этот файл не является модулем, установленным ранее с этим ID. Он получит настройки и кэш, сохранённые для этого ID. @@ -7122,6 +7123,11 @@ axis Y Axis Ось Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не получил разрешение `{p}`, нужное для его результата: ничего не изменено @msg a heavy filter runs in the background, so it can't declare `commands` тяжёлый фильтр выполняется в фоне, поэтому не может объявлять `commands` @msg at most {MAX_COMMANDS} `commands` не более {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задаёт не более {MAX_LANGUAGES} языков +@msg {at} gives two options the same label {at} даёт двум вариантам одинаковую подпись +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не является кодом языка вроде `de` или `pt-BR` или повторяет код, заданный ранее +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} должен содержать 1-{max} печатных символов без символов направления текста и разделителей строк +@msg {at} names or translates something the manifest doesn't declare {at} называет или переводит то, что манифест не объявляет @msg command {name} is declared twice команда {name} объявлена дважды @msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` должен содержать 1-64 печатаемых символа @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: используйте id из 1-{MAX_COMMAND_ID} символов a-z 0-9 _, начинающийся с буквы diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..7a6a004d29 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7449,6 +7449,7 @@ axis Y Axis Y-axel # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Installera ”{name}”, som begär dessa behörigheter? ID: {id} ID: {id} + Manifest name: {name} Namn i manifestet: {name} Version: {version} Version: {version} Install “{name}” in place of the plug-in with the same ID? Installera ”{name}” i stället för det plugin som har samma id? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Den här filen är inte det plugin som tidigare installerades med detta id. Den får de inställningar och den cache som sparats för detta id. @@ -7508,6 +7509,11 @@ axis Y Axis Y-axel @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed ”{name}” beviljades inte `{p}`, som dess utdata behöver: ingenting ändrades @msg a heavy filter runs in the background, so it can't declare `commands` ett tungt filter körs i bakgrunden, så det kan inte deklarera `commands` @msg at most {MAX_COMMANDS} `commands` högst {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` anger högst {MAX_LANGUAGES} språk +@msg {at} gives two options the same label {at} ger två alternativ samma etikett +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} är inte en språkkod som `de` eller `pt-BR`, eller upprepar en som angetts tidigare +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} måste vara 1-{max} utskrivbara tecken, utan riktnings- eller radavgränsartecken +@msg {at} names or translates something the manifest doesn't declare {at} namnger eller översätter något som manifestet inte deklarerar @msg command {name} is declared twice kommandot {name} deklareras två gånger @msg command {name}: `label` must be 1-64 printable characters kommando {name}: `label` måste ha 1-64 utskrivbara tecken @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter kommando {name}: använd ett id med 1-{MAX_COMMAND_ID} tecken av a-z 0-9 _ som börjar med en bokstav diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..e256c8ee68 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7509,6 +7509,7 @@ axis Y Axis Y ekseni # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Bu izinleri isteyen “{name}” yüklensin mi? ID: {id} Kimlik: {id} + Manifest name: {name} Manifestteki ad: {name} Version: {version} Sürüm: {version} Install “{name}” in place of the plug-in with the same ID? Aynı kimliğe sahip eklentinin yerine “{name}” yüklensin mi? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Bu dosya, daha önce bu kimlikle yüklenen eklenti değil. O kimlik için saklanan ayarları ve önbelleği alır. @@ -7572,6 +7573,11 @@ axis Y Axis Y ekseni @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” öğesine çıktısının ihtiyaç duyduğu `{p}` izni verilmedi: hiçbir şey değiştirilmedi @msg a heavy filter runs in the background, so it can't declare `commands` ağır bir filtre arka planda çalışır, bu yüzden `commands` bildiremez @msg at most {MAX_COMMANDS} `commands` en fazla {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` en fazla {MAX_LANGUAGES} dil verir +@msg {at} gives two options the same label {at} iki seçeneğe aynı etiketi veriyor +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at}, `de` veya `pt-BR` gibi bir dil kodu değil ya da daha önce verilmiş bir kodu yineliyor +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at}, yön veya satır ayırıcı karakterleri olmadan 1-{max} yazdırılabilir karakter olmalıdır +@msg {at} names or translates something the manifest doesn't declare {at}, manifestin bildirmediği bir şeyi adlandırıyor veya çeviriyor @msg command {name} is declared twice {name} komutu iki kez bildirilmiş @msg command {name}: `label` must be 1-64 printable characters {name} komutu: `label` 1-64 yazdırılabilir karakter olmalıdır @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter {name} komutu: a-z 0-9 _ karakterlerinden oluşan ve harfle başlayan 1-{MAX_COMMAND_ID} karakterlik bir kimlik kullanın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..fdcf7c5894 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -7041,6 +7041,7 @@ axis Y Axis Вісь Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Встановити «{name}», якому потрібні ці дозволи? ID: {id} ID: {id} + Manifest name: {name} Назва в маніфесті: {name} Version: {version} Версія: {version} Install “{name}” in place of the plug-in with the same ID? Встановити «{name}» замість модуля з тим самим ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Цей файл не є модулем, установленим раніше з цим ID. Він отримає налаштування й кеш, збережені для цього ID. @@ -7104,6 +7105,11 @@ axis Y Axis Вісь Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed «{name}» не отримав дозволу `{p}`, потрібного для його результату: нічого не змінено @msg a heavy filter runs in the background, so it can't declare `commands` важкий фільтр виконується у фоні, тому не може оголошувати `commands` @msg at most {MAX_COMMANDS} `commands` щонайбільше {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` задає щонайбільше {MAX_LANGUAGES} мов +@msg {at} gives two options the same label {at} дає двом варіантам однаковий підпис +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} не є кодом мови на кшталт `de` чи `pt-BR` або повторює код, заданий раніше +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} має містити 1-{max} друкованих символів без символів напрямку тексту й розділювачів рядків +@msg {at} names or translates something the manifest doesn't declare {at} називає або перекладає те, чого маніфест не оголошує @msg command {name} is declared twice команду {name} оголошено двічі @msg command {name}: `label` must be 1-64 printable characters команда {name}: `label` має містити 1-64 друковані символи @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter команда {name}: використайте id з 1-{MAX_COMMAND_ID} символів a-z 0-9 _, що починається з літери diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..72dd7e49a2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7088,6 +7088,7 @@ axis Y Axis Trục Y # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? Cài đặt “{name}”, plug-in yêu cầu các quyền này? ID: {id} ID: {id} + Manifest name: {name} Tên trong manifest: {name} Version: {version} Phiên bản: {version} Install “{name}” in place of the plug-in with the same ID? Cài đặt “{name}” thay cho plug-in có cùng ID? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. Tệp này không phải là plug-in đã cài đặt trước đây với ID này. Tệp sẽ nhận cài đặt và bộ nhớ đệm được lưu cho ID đó. @@ -7151,6 +7152,11 @@ axis Y Axis Trục Y @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}” chưa được cấp `{p}`, quyền mà đầu ra của nó cần: không có gì thay đổi @msg a heavy filter runs in the background, so it can't declare `commands` bộ lọc nặng chạy ở chế độ nền nên không thể khai báo `commands` @msg at most {MAX_COMMANDS} `commands` tối đa {MAX_COMMANDS} `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` chỉ định tối đa {MAX_LANGUAGES} ngôn ngữ +@msg {at} gives two options the same label {at} đặt cùng một nhãn cho hai tùy chọn +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} không phải mã ngôn ngữ như `de` hoặc `pt-BR`, hoặc lặp lại mã đã cho trước đó +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} phải có 1-{max} ký tự in được, không có ký tự định hướng hoặc ký tự phân cách dòng +@msg {at} names or translates something the manifest doesn't declare {at} đặt tên hoặc dịch một thứ mà manifest không khai báo @msg command {name} is declared twice lệnh {name} được khai báo hai lần @msg command {name}: `label` must be 1-64 printable characters lệnh {name}: `label` phải có 1-64 ký tự in được @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter lệnh {name}: hãy dùng id gồm 1-{MAX_COMMAND_ID} ký tự từ a-z 0-9 _ và bắt đầu bằng một chữ cái diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..c563337d66 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -7269,6 +7269,7 @@ axis Y Axis Y 轴 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 要安装需要这些权限的“{name}”吗? ID: {id} ID:{id} + Manifest name: {name} 清单中的名称:{name} Version: {version} 版本:{version} Install “{name}” in place of the plug-in with the same ID? 要安装“{name}”来替换具有相同 ID 的插件吗? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此文件不是之前以此 ID 安装的插件。它将获得为该 ID 保存的设置和缓存。 @@ -7332,6 +7333,11 @@ axis Y Axis Y 轴 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed “{name}”未获授予其输出所需的 `{p}`:未作任何更改 @msg a heavy filter runs in the background, so it can't declare `commands` 重型滤镜在后台运行,因此不能声明 `commands` @msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 个 `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多给出 {MAX_LANGUAGES} 种语言 +@msg {at} gives two options the same label {at} 为两个选项给出了相同的标签 +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 这样的语言代码,或重复了前面给出的代码 +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必须为 1-{max} 个可打印字符,且不含方向字符或行分隔符 +@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻译了清单未声明的内容 @msg command {name} is declared twice 命令 {name} 声明了两次 @msg command {name}: `label` must be 1-64 printable characters 命令 {name}:`label` 必须是 1-64 个可打印字符 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 命令 {name}:请使用由 a-z 0-9 _ 组成、以字母开头的 1-{MAX_COMMAND_ID} 个字符的 ID diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..5b9ce67800 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -7090,6 +7090,7 @@ axis Y Axis Y 軸 # Plug-in permissions (Install Plug-in…, plugin.install grant) Install “{name}”, which asks for these permissions? 要安裝需要這些權限的「{name}」嗎? ID: {id} ID:{id} + Manifest name: {name} 資訊清單中的名稱:{name} Version: {version} 版本:{version} Install “{name}” in place of the plug-in with the same ID? 要安裝「{name}」來取代具有相同 ID 的增效模組嗎? This file is not the plug-in installed before with this ID. It gets the settings and cache kept for that ID. 此檔案不是先前以此 ID 安裝的增效模組。它會取得為該 ID 保存的設定和快取。 @@ -7153,6 +7154,11 @@ axis Y Axis Y 軸 @msg “{name}” wasn't granted `{p}`, which its output needs: nothing was changed 「{name}」未獲授予其輸出所需的 `{p}`:未做任何變更 @msg a heavy filter runs in the background, so it can't declare `commands` 重型濾鏡在背景執行,因此不能宣告 `commands` @msg at most {MAX_COMMANDS} `commands` 最多 {MAX_COMMANDS} 個 `commands` +@msg `translations` gives at most {MAX_LANGUAGES} languages `translations` 最多提供 {MAX_LANGUAGES} 種語言 +@msg {at} gives two options the same label {at} 為兩個選項提供了相同的標籤 +@msg {at} is not a language code such as `de` or `pt-BR`, or repeats one given before it {at} 不是 `de` 或 `pt-BR` 這類語言代碼,或重複了前面提供的代碼 +@msg {at} must be 1-{max} printable characters, without direction or line-separator characters {at} 必須為 1-{max} 個可列印字元,且不含方向字元或行分隔字元 +@msg {at} names or translates something the manifest doesn't declare {at} 指定或翻譯了資訊清單未宣告的內容 @msg command {name} is declared twice 指令 {name} 宣告了兩次 @msg command {name}: `label` must be 1-64 printable characters 指令 {name}:`label` 必須是 1-64 個可列印字元 @msg command {name}: use an id of 1-{MAX_COMMAND_ID} characters from a-z 0-9 _ that starts with a letter 指令 {name}:請使用由 a-z 0-9 _ 組成、以字母開頭的 1-{MAX_COMMAND_ID} 個字元的 ID diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 180c459453..63c2e82b15 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -279,12 +279,25 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result Result Option { Some(text) } +/// The name Last Effect gives effect `e`: its Effect menu label, a plug-in's name in the UI language +/// as Effect › Plug-ins shows it ([`crate::dialogs::plugin::effect_item_label`]). +fn last_effect_name(e: &str) -> &str { + vectorcraft_effects::effect_info(e).map(|i| crate::dialogs::plugin::effect_item_label(&i)).unwrap_or(e) +} + /// The labels that follow the last effect, the envelope being edited, the history and the perspective grid. fn command_label(app: &VectorcraftApp, id: &str, label: &str) -> Option { let text: String = match id { "effect.last" => match &app.last_effect { - Some((e, _)) => format!("Last Effect: {}", vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str())), + Some((e, _)) => format!("Last Effect: {}", last_effect_name(e)), None => label.into(), }, // Edit Contents reads Edit Envelope while an envelope's contents are being edited. @@ -151,7 +157,8 @@ pub(crate) fn shows_a_name(id: &str, label: &str) -> bool { ) || vectorcraft_engine::cmd::plugin::is_command_id(id) || (id == "window.workspace" && !crate::workspaces::is_builtin(label)) - || (matches!(id, "effect.apply" | "effect.dialog") && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label)) + || (matches!(id, "effect.apply" | "effect.dialog") + && vectorcraft_effects::plugin_effects().iter().any(|e| e.label == label || crate::dialogs::plugin::effect_item_label(e) == label)) } /// Does the menu item `id` with `params` list an installed plug-in (an Object › Plug-ins filter, an @@ -187,7 +194,7 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } "effect.last" => match &app.last_effect { Some((e, _)) => { - let name = vectorcraft_effects::effect_info(e).map(|i| i.label).unwrap_or(e.as_str()); + let name = last_effect_name(e); fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) } None => crate::i18n::tr_id(lang, id, label).to_string(), diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index a3c5fed207..eabb023ad4 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -106,6 +106,9 @@ struct Draft { label: String, /// Does the label translate? An installed filter plug-in's name does not. translates: bool, + /// Is this a plug-in command, whose label and plug-in name come from the plug-in's own + /// translations? + plugin_command: bool, id: String, shortcut: String, /// Has [`distinct_names`] given the result its [`context`]? @@ -120,6 +123,7 @@ impl Draft { path: path.to_string(), label: label.to_string(), translates: true, + plugin_command: false, id, shortcut: shortcut.to_string(), in_context: false, @@ -130,6 +134,20 @@ impl Draft { /// The name in `lang`: the path's segments and the label translate on their own, and the id /// follows in parentheses when the result shows it. fn name(&self, lang: crate::i18n::Lang) -> String { + // A plug-in command shows its label and its plug-in's name as its menu item does. + if self.plugin_command + && let Some((plugin, command)) = vectorcraft_engine::cmd::plugin::command_of(&self.id) + { + let m = plugin.manifest(); + let path = if self.in_context { + shown_label(lang, &self.path) + } else { + let top = self.path.rsplit_once(" › ").map_or("", |(top, _)| top); + format!("{} › {}", shown_label(lang, top), m.shown_name(lang.code())) + }; + let name = format!("{path} › {}", m.shown_command_label(&command, lang.code())); + return if self.keyed { format!("{name} ({})", self.id) } else { name }; + } // A built-in effect's label translates by its effect id first, as the Effect menu's does. let label = match self.id.strip_prefix("effect:") { _ if !self.translates => self.label.as_str(), @@ -158,9 +176,13 @@ fn drafts() -> Vec { && !ui_ids.contains(c.id) && (!crate::shortcut_editor::needs_a_value(c.id) || PICK_RUNS.contains(&c.id)) }; - for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c)).chain(plugin_commands) { + for c in vectorcraft_engine::command_specs().iter().filter(|c| listed(c)) { out.push(Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or(""))); } + for c in plugin_commands { + let draft = Draft::new(&c.menu.join(" › "), c.label, c.id.to_string(), menus::shortcut_of(c.id).unwrap_or("")); + out.push(Draft { plugin_command: true, ..draft }); + } // `plugin.dialog` runs nothing without an id: [`build`] lists each filter instead. A script of // the Scripts folder runs from File › Scripts, by its path. A UI command that wraps an engine // command, or has an engine command's id, takes that command's menu path, so a search for the @@ -266,9 +288,10 @@ fn distinct_names(drafts: &mut [Draft], langs: &[crate::i18n::Lang]) { } /// A palette label in `lang`: each `›`-separated menu segment and the command label translate on -/// their own. +/// their own, except a plug-in's name and items after Object › Plug-ins or Effect › Plug-ins +/// ([`crate::dialogs::plugin::translate_path`]). fn shown_label(lang: crate::i18n::Lang, label: &str) -> String { - label.split(" › ").map(|s| crate::i18n::tr(lang, s)).collect::>().join(" › ") + crate::dialogs::plugin::translate_path(label, |s| crate::i18n::tr(lang, s)) } /// The label of the item of the menu bar that runs `e`, in `lang`, as the menu bar draws it @@ -3259,6 +3282,46 @@ mod tests { vectorcraft_plugins::registry::remove(two); } + /// A plug-in command's result shows its label and its plug-in's name in the language the + /// plug-in translates them into, and the manifest's own text in a language it doesn't. + #[test] + fn a_plugin_command_result_shows_the_plugins_translation() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_translated"; + let manifest = format!( + r#"{{"id":"{id}","name":"Tidy","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Grow"}}], + "translations":{{"de":{{"name":"Aufräumen","commands":{{"grow":{{"label":"Wachsen"}}}}}}}}}}"# + ); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let key = format!("plugin.{id}.grow"); + let shown = |code: &str| { + let lang = Lang::from_code(code).unwrap(); + build(lang).into_iter().find(|e| e.id == key).map(|e| (e.shown, crate::i18n::tr(lang, "Object"), crate::i18n::tr(lang, "Plug-ins"))) + }; + let (de, fr) = (shown("de"), shown("fr")); + vectorcraft_plugins::registry::remove(id); + let (de, object, plugins) = de.expect("the command is a result"); + assert_eq!(de, format!("{object} › {plugins} › Aufräumen › Wachsen")); + let (fr, object, plugins) = fr.expect("the command is a result"); + assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); + } + + /// A plug-in's name in the path of its own item, in the submenu a plug-in with commands gets, + /// stays as the plug-in gives it where it matches text the app translates ("Open" in German). + #[test] + fn a_plugin_submenu_name_is_not_translated_by_the_app() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_submenu_name"; + let manifest = format!(r#"{{"id":"{id}","name":"Open","version":"1","kind":"filter","commands":[{{"id":"go","label":"Go"}}]}}"#); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let de = Lang::from_code("de").unwrap(); + let shown = build(de).into_iter().find(|e| e.id == format!("plugin:{id}")).map(|e| e.shown); + vectorcraft_plugins::registry::remove(id); + assert_ne!(crate::i18n::tr(de, "Open"), "Open", "German translates the app's Open"); + let path = format!("{} › {}", crate::i18n::tr(de, "Object"), crate::i18n::tr(de, "Plug-ins")); + assert_eq!(shown, Some(format!("{path} › Open › Open"))); + } + /// Of the engine commands the palette listed before, it leaves out only the ones /// [`crate::shortcut_editor::needs_a_value`] marks: queries with no default key and no item of /// the menu bar, and commands that need a value no menu item gives. A pick of each one it leaves diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 52b36b4535..4c7b0a345a 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -243,11 +243,12 @@ fn built_in_effect(id: &str) -> bool { } /// [`effect_label`] as shown: a built-in effect's in the UI language (an `@id` row for the -/// effect's id wins over the plain row of its English label), a plug-in's as it is. +/// effect's id wins over the plain row of its English label), a plug-in's by the name the plug-in +/// gives in the UI language ([`crate::dialogs::plugin::effect_name`]). pub(crate) fn shown_effect_label(id: &str) -> String { match catalog().iter().find(|c| c.0 == id) { Some(c) => crate::i18n::t_id(id, &c.1).to_string(), - None => effect_label(id), + None => crate::dialogs::plugin::effect_name(id).unwrap_or_else(|| effect_label(id)), } } @@ -1396,10 +1397,14 @@ fn effect_editor(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: } let ui_keys = manifest.and_then(|m| m.param(key)).map(|p| &p.ui); ui.horizontal(|ui| { - let label = ui_keys.and_then(|u| u.label.clone()).unwrap_or_else(|| param_label(key, built_in)); + // A plug-in's label and help in the UI language, escaped as its dialog shows them. + let label = manifest.and_then(|m| crate::dialogs::form::plugin_param_label(m, key)).unwrap_or_else(|| param_label(key, built_in)); let label_node = ui.add_sized(vec2(84.0, 22.0), egui::Label::new(egui::RichText::new(label.as_str()).size(11.5).color(t.text)).truncate()); - let label_node = if let Some(help) = ui_keys.and_then(|u| u.help.as_deref()) { label_node.on_hover_text(help) } else { label_node }; + let label_node = match manifest.and_then(|m| crate::dialogs::form::plugin_param_help(m, key)) { + Some(help) => label_node.on_hover_text(help), + None => label_node, + }; // The row's actual label node names its fields, including a plug-in's plain text // and number fields (egui 0.37's strict a11y gate). ui.label_inputs_by(label_node.id, |ui| { @@ -1815,8 +1820,11 @@ fn delete_selected(app: &mut VectorcraftApp, ui: &Ui, node: Option<&Node>, sel: /// opens the effect dialog. pub(crate) fn fx_menu(app: &mut VectorcraftApp, ui: &mut Ui) { let mut groups: Vec<(String, Vec<(String, String)>)> = vec![]; - let plugins: Vec<_> = vectorcraft_effects::plugin_effects().into_iter().map(catalog_entry).collect(); - // Built-in effects in the UI language; a plug-in's by the name it gives. + let plugins: Vec<_> = vectorcraft_effects::plugin_effects() + .into_iter() + .map(|e| (e.id.to_string(), crate::dialogs::plugin::effect_item_label(&e).trim_end_matches('…').to_string(), catalog_entry(e).2)) + .collect(); + // Built-in effects in the UI language; a plug-in's by the name it gives in it. let built_in = catalog().iter().map(|(id, label, menu)| (id, tl!(label), menu)); for (id, label, menu) in built_in.chain(plugins.iter().map(|(id, label, menu)| (id, label.as_str(), menu))) { let g = menu.get(1).cloned().unwrap_or_else(|| "Other".into()); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index a9d7b022a7..bf1471df25 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -385,15 +385,20 @@ pub struct Entry { pub(crate) struct Snapshot { /// The plug-in revision read before the menus were walked. pub revision: u64, + /// The UI language the menus were walked in, which names plug-in items in a plug-in's own + /// translations. + pub lang: &'static str, pub effects: Arc<[EffectItem]>, pub filters: Arc<[FilterItem]>, pub entries: Arc<[Entry]>, } /// The entries for the plug-ins installed now: rebuilt when a plug-in is installed or removed, so -/// a live-effect or filter plug-in installed later has its row, and one removed has none. +/// a live-effect or filter plug-in installed later has its row, and one removed has none, and when +/// the UI language changes, so plug-in items show the plug-in's text in it. pub(crate) fn snapshot() -> Arc { static LAST: Mutex>> = Mutex::new(None); + let lang = crate::i18n::current().code(); let mut revision = menus::plugin_revision(); let last = LAST.lock().unwrap_or_else(|e| e.into_inner()).clone(); // A test's walk hook runs even when a snapshot of this revision is already stored. @@ -406,13 +411,13 @@ pub(crate) fn snapshot() -> Arc { }; #[cfg(not(test))] let hooked = false; - if let Some(s) = last.filter(|s| s.revision == revision && !hooked) { + if let Some(s) = last.filter(|s| s.revision == revision && s.lang == lang && !hooked) { return s; } // When a plug-in is installed or removed during the walk, the entries may not match // `revision`, and the keymap cached for it would lack rows or hold extra ones. The menus are // walked again at the new revision, and a snapshot that still doesn't match is not cached. - let mut s = build_snapshot(revision); + let mut s = build_snapshot(revision, lang); for _ in 0..8 { let now = menus::plugin_revision(); if now == revision { @@ -424,13 +429,14 @@ pub(crate) fn snapshot() -> Arc { return s; } revision = now; - s = build_snapshot(revision); + s = build_snapshot(revision, lang); } s } -/// The snapshot of the menus as they are now, under plug-in revision `revision`. -fn build_snapshot(revision: u64) -> Arc { +/// The snapshot of the menus as they are now, under plug-in revision `revision`, walked in UI +/// language `lang`. +fn build_snapshot(revision: u64, lang: &'static str) -> Arc { // Built without the lock held: the Effect menu is walked anew. #[cfg(test)] if let Some(f) = tests::WHILE_WALKING.take() { @@ -456,17 +462,22 @@ fn build_snapshot(revision: u64) -> Arc { is_tool: false, shows_key: false, })) - .chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| Entry { - key: c.id.into(), - label: c.label.into(), - group: c.menu.join(" › "), - is_tool: false, - shows_key: false, + .chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| { + // A plug-in command's label and its plug-in's name in `lang`, as its menu shows them. + let (label, group) = match vectorcraft_engine::cmd::plugin::command_of(c.id) { + Some((plugin, command)) => { + let m = plugin.manifest(); + let path: Vec = c.menu.iter().take(2).map(|s| s.to_string()).chain([m.shown_name(lang)]).collect(); + (m.shown_command_label(&command, lang), path.join(" › ")) + } + None => (c.label.to_string(), c.menu.join(" › ")), + }; + Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false } })) .chain(tail.iter().cloned()) .collect(); distinct_names(&mut entries); - Arc::new(Snapshot { revision, effects, filters, entries: entries.into() }) + Arc::new(Snapshot { revision, lang, effects, filters, entries: entries.into() }) } /// Every tool, command and panel the editor can give a shortcut; [`listed`] says which it lists. @@ -647,15 +658,19 @@ pub fn filter_shortcut(id: &str) -> Option<&'static str> { effective(&format!("plugin:{id}")) } -/// Entry `e`'s label in the UI language. A plug-in's own name is not translated. +/// Entry `e`'s label in the UI language. A plug-in's own name and its commands' labels, already in +/// the UI language from the plug-in's translations, are not translated again. pub(crate) fn shown_label(e: &Entry) -> &str { - let plugin = e.key.starts_with("plugin:") || e.key.strip_prefix("effect:").and_then(vectorcraft_plugins::effect::plugin_id).is_some(); + let plugin = e.key.starts_with("plugin:") + || vectorcraft_engine::cmd::plugin::is_command_id(&e.key) + || e.key.strip_prefix("effect:").and_then(vectorcraft_plugins::effect::plugin_id).is_some(); if plugin { &e.label } else { tl!(&e.label) } } -/// A menu path in the UI language, one segment at a time. +/// A menu path in the UI language, one segment at a time; a plug-in's name after Object › Plug-ins +/// or Effect › Plug-ins stays as the plug-in gives it ([`crate::dialogs::plugin::translate_path`]). pub(crate) fn shown_group(group: &str) -> String { - group.split(" › ").map(|s| tl!(s)).collect::>().join(" › ") + crate::dialogs::plugin::translate_path(group, |s| tl!(s)) } /// How Keyboard Shortcuts names entry `e`: a tool by its label, the others after their menu, and diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 0a80254db0..81046387f3 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -279,6 +279,41 @@ fn installing_a_plugin_that_lists_permissions_asks_first() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// The approval names a plug-in whose manifest translates its name in the UI language and also +/// gives the manifest's own name, both escaped; a language without a translation shows the +/// manifest's name alone. What OK installs stays bound to the id and hash shown. +#[test] +fn the_install_approval_shows_the_translated_and_the_manifests_own_name() { + let mut app = app(); + let id = "test.ui.translated_approval"; + let manifest = json!({"id": id, "name": "Tidy", "version": "1", "kind": "filter", "permissions": ["doc.read"], + "translations": {"de": {"name": "Aufräumen"}}}) + .to_string(); + let bytes = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes); + let data = vectorcraft_format::base64_encode(&bytes); + let ask = |app: &mut VectorcraftApp, lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let r = app.run("ui.installPlugin", json!({ "dataBase64": data })); + let pending = app.pending_plugin_install.as_ref().map(|p| (p.message.clone(), p.detail.clone(), p.params["hash"].clone())); + crate::i18n::set_current(crate::i18n::Lang::EN); + dialogs::cancel(app); + assert_eq!(r.unwrap()["pending"], dialogs::plugin::INSTALL_KIND); + pending.unwrap() + }; + let (message, detail, shown_hash) = ask(&mut app, "de"); + assert!(message.contains("Aufräumen") && !message.contains("Tidy"), "{message}"); + assert!(detail.contains("ID: test.ui.translated_approval"), "{detail}"); + assert!(detail.contains("Tidy"), "the manifest's own name: {detail}"); + assert!(!detail.contains("Aufräumen"), "{detail}"); + assert_eq!(shown_hash, json!(hash)); + let (message, detail, _) = ask(&mut app, "en"); + assert_eq!(message, "Install “Tidy”, which asks for these permissions?"); + assert_eq!(detail.lines().next(), Some("ID: test.ui.translated_approval")); + assert_eq!(detail.lines().nth(1), Some("Version: 1"), "no second name line: {detail}"); + assert!(vectorcraft_plugins::registry::get(id).is_none()); +} + /// The approval's OK takes no click, Enter or Space, and a confirm installs nothing, until its /// question has been on screen for [`dialogs::plugin::APPROVAL_DELAY`]; then a click installs it. /// Cancel works on the first frame. @@ -720,3 +755,135 @@ fn installing_a_plugin_that_reports_progress_says_so() { assert_eq!(vectorcraft_plugins::registry::granted(id).map(|g| g.permissions.len()), Some(2)); app.run("plugin.remove", json!({"id": id})).unwrap(); } + +/// The label of each item of `items`, a submenu's as `name ›` followed by its items'. +fn menu_labels(items: &[menus::Item]) -> Vec { + items + .iter() + .flat_map(|it| match it { + menus::Item::Cmd(label, ..) | menus::Item::Header(label) => vec![label.to_string()], + menus::Item::Sub(name, children) => std::iter::once(format!("{name} ›")).chain(menu_labels(children)).collect(), + _ => Vec::new(), + }) + .collect() +} + +/// Object › Plug-ins, Effect › Plug-ins and File › Open With name a plug-in and its commands in the +/// UI language when its manifest's `translations` give them: German text in German, `pt` text for +/// Brazilian Portuguese without its own, and the manifest's own text in any other language. +#[test] +fn plugin_menus_show_the_plugins_names_in_the_ui_language() { + let mut app = app(); + let (filter, effect, importer) = ("test.ui.translated.filter", "test.ui.translated.effect", "test.ui.translated.importer"); + let translations = r#""translations":{"de":{"name":"Aufräumen","commands":{"grow":{"label":"Wachsen"}}},"pt":{"name":"Arrumar"}}"#; + let filter_manifest = format!( + r#"{{"id":"{filter}","name":"Tidy","kind":"filter","commands":[{{"id":"grow","label":"Grow","params":{{"by":{{"type":"bool"}}}}}}],{translations}}}"# + ); + let effect_manifest = format!( + r#"{{"id":"{effect}","name":"Wobble","kind":"effect","params":{{"on":{{"type":"bool"}}}},"translations":{{"de":{{"name":"Wackeln"}}}}}}"# + ); + let importer_manifest = + format!(r#"{{"id":"{importer}","name":"Plotter","kind":"importer","extensions":["tpx"],"translations":{{"de":{{"name":"Zeichner"}}}}}}"#); + for manifest in [filter_manifest, effect_manifest, importer_manifest] { + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + } + let shown = |lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("language registered")); + let effects = dialogs::plugin::effect_menu().map(|m| menu_labels(&[m])).unwrap_or_default(); + let all = [menu_labels(&dialogs::plugin::object_menu()), effects, menu_labels(&dialogs::plugin::open_with_menu())].concat(); + crate::i18n::set_current(crate::i18n::Lang::EN); + all + }; + let de = shown("de"); + for label in ["Aufräumen ›", "Aufräumen", "Wachsen…", "Wackeln…", "Zeichner…"] { + assert!(de.contains(&label.to_string()), "{label} in German: {de:?}"); + } + // Other tests' plug-ins may be installed meanwhile: only this test's names are checked. + for label in ["Tidy ›", "Tidy", "Grow…", "Wobble…", "Plotter…"] { + assert!(!de.contains(&label.to_string()), "{label} in German: {de:?}"); + } + let pt_br = shown("pt-br"); + assert!(pt_br.contains(&"Arrumar ›".to_string()) && pt_br.contains(&"Grow…".to_string()), "pt, then the manifest: {pt_br:?}"); + for lang in ["en", "fr"] { + let other = shown(lang); + for label in ["Tidy ›", "Grow…", "Wobble…", "Plotter…"] { + assert!(other.contains(&label.to_string()), "{label} in {lang}: {other:?}"); + } + } + // A German item is still the plug-in's own name, not text a catalog translates, and Keyboard + // Shortcuts lists the filter and its command as the menu does, in the language it is shown in. + let grow = format!("plugin.{filter}.grow"); + let rows = |lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let names = menus::shows_a_name("effect.dialog", "Wackeln…"); + let row = |key: &str| crate::shortcut_editor::entry(key).map(|e| (e.label.clone(), e.group.clone())); + let rows = (names, row(&grow), row(&format!("plugin:{filter}"))); + crate::i18n::set_current(crate::i18n::Lang::EN); + rows + }; + let (names, command, own) = rows("de"); + assert!(names); + assert_eq!(command, Some(("Wachsen".to_string(), "Object › Plug-ins › Aufräumen".to_string()))); + assert_eq!(own.map(|r| r.0), Some("Aufräumen".to_string())); + let (_, command, _) = rows("en"); + assert_eq!(command, Some(("Grow".to_string(), "Object › Plug-ins › Tidy".to_string()))); + // Last Effect names the effect as Effect › Plug-ins does. + app.last_effect = Some((vectorcraft_plugins::effect::effect_id(effect), json!({}))); + let last = |lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let shown = (menus::display_label(&app, "effect.last", "Last Effect…"), menus::dynamic_label(&app, "effect.last", "Last Effect…")); + crate::i18n::set_current(crate::i18n::Lang::EN); + shown + }; + let (de, de_dynamic) = last("de"); + assert!(de.contains("Wackeln…") && de_dynamic == "Last Effect: Wackeln…", "{de} / {de_dynamic}"); + assert_eq!(last("en"), ("Last Effect: Wobble…".to_string(), "Last Effect: Wobble…".to_string())); + app.last_effect = None; + for id in [filter, effect, importer] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} + +/// Keyboard Shortcuts shows a plug-in command's label and its plug-in's name as the plug-in gives +/// them, even where they match text the app translates: in German, a command labeled "Open" of a +/// plug-in named "Close" keeps both, as in its menu. +#[test] +fn keyboard_shortcuts_leave_a_plugin_commands_text_as_the_plugin_gives_it() { + let mut app = app(); + let id = "test.ui.untranslated.command"; + let manifest = format!(r#"{{"id":"{id}","name":"Close","kind":"filter","commands":[{{"id":"go","label":"Open"}}]}}"#); + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let shown = crate::shortcut_editor::entry(&format!("plugin.{id}.go")).map(|e| crate::shortcut_editor::shown_name(&e)); + let expected = format!("{} › {} › Close › Open", crate::i18n::t("Object"), crate::i18n::t("Plug-ins")); + assert_ne!((crate::i18n::t("Open"), crate::i18n::t("Close")), ("Open", "Close"), "German translates both as app text"); + crate::i18n::set_current(crate::i18n::Lang::EN); + app.run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(shown, Some(expected)); +} + +/// A filter's and an importer's menu item show their names as prompts do, a right-to-left override +/// escaped, as a filter with commands already showed its submenu. +#[test] +fn plugin_menu_items_escape_bidirectional_characters() { + let mut app = app(); + let (filter, importer) = ("test.ui.bidi.filter", "test.ui.bidi.importer"); + // The override as a JSON escape in the manifest. + let rlo = format!("\\u{:04X}", 0x202E); + for manifest in [ + format!(r#"{{"id":"{filter}","name":"Flip{rlo}txt.exe","kind":"filter"}}"#), + format!(r#"{{"id":"{importer}","name":"Read{rlo}fdp.exe","kind":"importer","extensions":["rdx"]}}"#), + ] { + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + } + let labels = [menu_labels(&dialogs::plugin::object_menu()), menu_labels(&dialogs::plugin::open_with_menu())].concat(); + assert!(labels.contains(&"Flip\\u{202E}txt.exe".to_string()), "{labels:?}"); + assert!(labels.contains(&"Read\\u{202E}fdp.exe…".to_string()), "{labels:?}"); + assert!(!labels.iter().any(|l| l.contains('\u{202E}')), "{labels:?}"); + for id in [filter, importer] { + app.run("plugin.remove", json!({"id": id})).unwrap(); + } +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..fccfc2d5d2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13312,6 +13312,9 @@ The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `pr sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M, plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)). +A manifest's `translations` ([plug-ins](plugins.md#translations)) change only the text the app shows: `plugin.list`, +`plugin.info` and plug-in command entries keep the manifest's own names and labels, and `plugin.inspect` and +`plugin.info`'s `manifest` give `translations` as declared. A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, diff --git a/docs/plugins.md b/docs/plugins.md index ab294db1ff..42a20023c5 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -574,6 +574,7 @@ the module's start function, in a run that isn't a filter's run on a document, o it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. +- `translations`: the plug-in's text in other languages ([Translations](#translations)). - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults are also clamped @@ -604,6 +605,53 @@ declares them still installs there: A hidden parameter still goes to the plug-in with its value: what the dialog showed never changes a run. The filter, live-effect and exporter dialogs use all of these keys. The Appearance panel's editor of a plug-in effect's parameters uses `label`, `unit`, `help` and `visibleWhen`, and lists the parameters without sections or help buttons. +Dialogs and menus show plug-in text with control and bidirectional characters escaped (`\u{202E}`). + +#### Translations + +`translations` gives the plug-in's text in other languages, keyed by language code. The app shows the text for its +interface language (Preferences › User Interface). Text a language leaves out comes from the same code without its +last part (`pt-BR`, then `pt`; `zh-Hant-TW`, then `zh-Hant`, then `zh`) and then from the manifest's own text. Codes +match without regard to case. + +```json +"translations": { + "de": { + "name": "Pfade aufräumen", + "params": {"mode": {"label": "Modus", "help": "Weich rundet die Ecken.", "options": {"soft": "Weich", "hard": "Hart"}}}, + "groups": {"Shape": "Form"}, + "commands": {"grow": {"label": "Vergrößern", "params": {"by": {"label": "Um"}}}} + }, + "pt": {"name": "Arrumar caminhos"}, + "pt-BR": {"name": "Organizar caminhos"} +} +``` + +| Key | What it translates | +|---|---| +| `name` | The plug-in's name in Object › Plug-ins, Effect › Plug-ins, File › Open With, Edit › Keyboard Shortcuts, the command palette, the Appearance panel and dialog headings (1–64 characters). | +| `params` | By parameter name: its `label` (also for a parameter that gives none), `help` (only where the parameter gives one; line breaks allowed) and `options`, the label of each choice by the value it passes (1–64 characters each). | +| `groups` | By the `group` the parameters give: the section's heading. The section stays the same section in every language. | +| `commands` | By command id: its `label` and its parameters' text, as `params` gives it. | + +The text is only shown. Command ids, parameter names and choice values are the same in every language, the plug-in +is given the values it declared, and `plugin.list`, `plugin.info` and errors use the manifest's own `name` and labels; +`plugin.inspect` and `plugin.info` give `translations` as declared. The install approval names the plug-in in the UI +language and, when that name is a translation, also shows the manifest's own name under its ID; what the approval +grants is still bound to the ID and file hash it shows. + +A manifest gives at most 16 languages, inside its 64 KiB limit. Installing refuses the following, with an error that +names the key (such as `translations.de.params.mode.label`): + +- a code that is not a language of 2 or 3 letters followed by parts of 2–8 letters and digits after a `-` (at most 35 + characters), or a language given twice; +- text longer than the field it translates allows, empty text, or text with a control character (a line break + outside `help`), a character that changes the direction text runs in (`U+202A`–`U+202E`, `U+2066`–`U+2069`, + `U+200E`, `U+200F`, `U+061C`) or a line or paragraph separator; +- a parameter, choice value, group or command the manifest doesn't declare, `options` on a parameter that isn't a + choice, two options of a choice with the same label, or a key not listed above. + +Hosts from before `translations` ignore it and show the manifest's own text. ### Input diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..b56fc9013c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2647,6 +2647,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Importer plug-ins (G17):** a WebAssembly plug-in of kind `importer` adds a read-only file format, as [the help page](https://ai-sdk-2020.84.nz/html/struct_a_i_file_format_suite) describes for file format plug-ins that read: File › Open lists its files under "All readable files" and its own filter, and File › Open With lists each importer by name. `document.open` uses it for a file whose extension no built-in format reads, by content or extension (the importer whose id sorts first, when several list the extension), or the one `importer` names, also for an extension a built-in format reads; a damaged file of a built-in format reports that format's error. The plug-in is given at most 128 MiB of the file and `_context` (`mode: "import"`, `extension`, `name`), and returns paths and compound paths in the filters' object JSON, checked as a filter's output is; they become a new document whose artboard is their bounds, which Save asks a name for. A decline, invalid output, a trap or Cancel opens nothing. The routing rule, the limit and Open With are VectorCraft's own. Regressions: `crates/engine/tests/plugin_import.rs`, `crates/plugins/src/import.rs`, `crates/ui-egui/src/dialogs/tests_plugin_import.rs`. Scores and hours unchanged. - **Plug-in parameters as their manifest presents them (G17):** each parameter may have a `label`, a `unit` shown after its value, `help` on its label and a `helpUrl` page opened from a button, a `group` (sections that fold, after the parameters outside any group) and a `visibleWhen` that shows it only while the checkboxes and choices it names have one of the listed values (a hidden parameter still goes to the plug-in). `string` and `numberList` parameters join number, int, bool and choice, and a plug-in declares up to 256 parameters, at most 64 outside groups. The filter, live-effect and exporter dialogs use these keys, and the Appearance panel's effect editor the labels, units, help and conditions; hosts from before them ignore them. Regressions: `crates/plugins/src/dialog.rs`, `crates/plugins/src/manifest.rs`, `crates/ui-egui/src/dialogs/tests_plugin_fields.rs`, `crates/ui-egui/src/panels/appearance.rs`. Scores and hours unchanged. +- **Plug-in text in the UI language:** a manifest's `translations` give the plug-in's name, its commands' labels, its parameters' labels, help and choice labels, and its group headings in up to 16 languages, by language code (`de`, `pt-BR`). Object › Plug-ins, Effect › Plug-ins, File › Open With, Edit › Keyboard Shortcuts, the command palette, the plug-in dialogs and the Appearance panel show the text for the UI language, then for the language without its region (`pt-br`, then `pt`), then the manifest's own; command ids, parameter names, choice values and `plugin.list` keep the manifest's own text, and the install approval shows the manifest's own name under the ID when the name it asks with is a translation. An unknown code, a repeated language, text a source field couldn't hold, a control, direction or line-separator character, or a key the manifest doesn't declare is refused at install with an error naming the key, inside the 64 KiB manifest limit. Filter and importer menu items and plug-in dialog labels, help, groups and choices now escape bidirectional characters as command labels already did, and so does the refusal of a heavy filter. Regressions: `crates/plugins/src/translations.rs`, `crates/ui-egui/src/tests/plugins.rs`, `crates/ui-egui/src/dialogs/tests.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Live-effect plug-ins read their object's paints (G17):** a live effect is given the object's `fills` and `strokes` as a filter gets them, read only, and `_context.item` (`"object"`, or the fill or stroke whose own effects hold it); the result is cached by paint too, so a change of paint runs it again. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/effect.rs`. Scores and hours unchanged. - **Live-effect plug-ins before a fill's or stroke's own 3D effect:** a live effect listed before a fill's or stroke's own Extrude & Bevel, Inflate or Rotate effect is given `_context.item` for that fill or stroke (`{"fill": i}` or `{"stroke": i}`), not `"object"`, in the drawn art, in the 3D meshes and in Expand as Wireframes; a deferred stage there is listed at that fill's or stroke's place. Regressions: `crates/effects/src/tests/solidcontext.rs`. Scores and hours unchanged. - **Filter plug-ins set effects and stroke styles (G17):** a filter is given each object's effect records and its strokes' `join`, `cap` and `miterLimit`, and may return them; the records are admitted as `effect.apply` admits them (a known effect or installed live-effect plug-in, parameters it takes, one 3D effect that fits, no texture read from a file), and one refused refuses the output. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. From 3c3f2e82b7c84341f3a71efeeb7cb882f6b0959e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:48:14 -0800 Subject: [PATCH 034/153] Clean Up: leave a shape unmeasured when resolving it would merge edges Resolving a fill's outlines snaps points within the sweep tolerance together, and that tolerance grows with the shape's size. For a shape large enough that the tolerance reaches the fine measure's error, the outline could collapse and the shape was reported as thinner than the width (a 1e12 by 0.0011 pt rectangle at 0.001 pt was removed although a 0.001 pt circle fits inside it). Such a shape is now not measured and is left as it is. --- crates/pathops/src/thickness.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/pathops/src/thickness.rs b/crates/pathops/src/thickness.rs index a4bffb998a..67771c66a3 100644 --- a/crates/pathops/src/thickness.rs +++ b/crates/pathops/src/thickness.rs @@ -7,7 +7,7 @@ use std::collections::BinaryHeap; use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape as _}; use vectorcraft_geom::{FillRule, PathData}; -use crate::boolean::{fill_bezpath, normalize_bez}; +use crate::boolean::{eps_for, fill_bezpath, normalize_bez}; /// Most line pieces the outline of one shape is measured with. pub const MAX_THICKNESS_PIECES: usize = 100_000; @@ -28,7 +28,8 @@ const ROUGH_PARTS: f64 = 8.0; /// A shape within a small fraction of `width` of the limit is taken as thick enough. /// /// `None` when it can't be told: `width` isn't a finite positive number, a coordinate isn't -/// finite, the fill can't be resolved into outlines, or measuring it would take more than +/// finite, the fill can't be resolved into outlines (or only so coarsely, for a shape that large, +/// that edges closer than `width` would merge), or measuring it would take more than /// [`MAX_THICKNESS_PIECES`] pieces of outline or a search too long. pub fn thinner_than(path: &PathData, rule: FillRule, width: f64) -> Option { thinner_than_within(path, rule, width, &mut ThicknessBudget::new(MAX_WORK)) @@ -118,6 +119,11 @@ pub fn thinner_than_within(path: &PathData, rule: FillRule, width: f64, budget: } // The fill's own outlines: where subpaths overlap or a path crosses itself, the edges inside the // fill are no outline of it. A spot within the fine pieces' error of the radius counts as one. + // The sweep snaps points within its tolerance together, which grows with the shape's size: one + // as coarse as the fine pieces could close up a fill that holds the circle, so it isn't measured. + if eps_for([&bp]).ok()? >= fine { + return None; + } let contours = normalize_bez(&bp, rule).ok()?; edges.clear(); for c in contours.contours() { @@ -545,6 +551,16 @@ mod tests { assert_eq!(thinner_than_within(&square, FillRule::NonZero, 0.085, &mut spent), Some(false)); } + /// A shape so long that resolving its outline snaps edges closer than the width together is not + /// measured, while the same height at an ordinary length is. + #[test] + fn a_shape_too_long_to_resolve_at_the_width_cannot_be_measured() { + let rect = |w: f64| one(&[(0.0, 0.0), (w, 0.0), (w, 0.0011), (0.0, 0.0011)]); + assert_eq!(thinner_than(&rect(1e12), FillRule::NonZero, 0.001), None); + assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.001), Some(false)); + assert_eq!(thinner_than(&rect(1.0), FillRule::NonZero, 0.0012), Some(true)); + } + #[test] fn a_width_or_a_coordinate_that_is_no_finite_number_cannot_be_measured() { let sliver = one(&[(0.0, 0.0), (40.0, 30.0), (0.001, 0.0015)]); From d26ae6f344f62ab7729abc0a0dc3bbe7df5a8a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:16:39 -0800 Subject: [PATCH 035/153] 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 ece34c6ba732f797b4ed46f597679b8793479d7b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:51:53 -0800 Subject: [PATCH 036/153] Plug-ins: translated names keep their English text in messages and the heavy-budget prompt - A choice's options are compared for repeats as dialogs show them, with control and bidirectional characters escaped, so a translation can no longer give one option the text another option's value shows as. - Installing a heavy filter that asks for nothing else now shows its ID and file SHA-256, and the manifest's own name when the prompt names it by a translation. - Shortcut conflict messages name a plug-in's filter and commands by the manifest's own text, as they name every other entry in English, while Keyboard Shortcuts still lists them in the UI language. - Keyboard Shortcuts builds its list again when the UI language changed since it was last open. Docs: docs/plugins.md, ui.installPlugin params. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/plugins/src/translations.rs | 22 +++++- crates/ui-egui/src/io/open.rs | 13 ++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/shortcut_editor.rs | 101 ++++++++++++++++++++---- crates/ui-egui/src/shortcuts/tests.rs | 1 + crates/ui-egui/src/tests/plugin_runs.rs | 31 ++++++++ crates/ui-egui/src/tests/plugins.rs | 29 +++++++ docs/plugins.md | 4 +- 9 files changed, 181 insertions(+), 24 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..d06ba12484 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1999,7 +1999,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.installPlugin", "Install Plug-in…", "", - "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", + "{path?: a .wasm file | dataBase64?: the module, name?: the file name shown as its source (with dataBase64), replace?: bool (true: the user agreed it takes the place of the plug-in with its id, as plugin.install), hash?: the module's SHA-256 (as plugin.install)} install a WebAssembly plug-in (plugin.install); without a path pick one (the web opens the browser's file picker; File › Open of a .wasm installs it too). A plug-in that lists permissions the user hasn't granted it asks the user first, showing its name, id, version, file SHA-256 and what each permission lets it do, so does a filter that asks for a heavy budget, showing its id and file SHA-256, and so does one without replace that would take the place of another module with its id and get its settings and cache (needsReplace in plugin.inspect), showing its id and file SHA-256: OK installs it if the file still has the SHA-256 shown, Cancel installs nothing. Only a person can press OK: ui.dialog.confirm, answer_dialog and synthetic input are refused. When automation asked (a control or MCP request, synthetic input, or a file dialog one of them opened, even when the person picked the file), replace: true doesn't skip the question about replacing, and nothing in the dialog installs it, the person's OK included: the person chooses Object › Plug-ins › Install Plug-in… to install it → plugin.install's result | {pending: \"pluginInstall\"} while it asks | {pending: \"pluginInstall\", approval: \"personMustStartInstall\"} while it asks what automation asked | null on the web without path or dataBase64, once the browser's file picker opens (the picked file is handled as above)", ), ( "plugin.cancelRuns", diff --git a/crates/plugins/src/translations.rs b/crates/plugins/src/translations.rs index f940a635cd..76c8f65046 100644 --- a/crates/plugins/src/translations.rs +++ b/crates/plugins/src/translations.rs @@ -170,6 +170,13 @@ fn key(path: &[&str]) -> String { format!("`translations.{}`", parts.join(".")) } +/// Text `s` as a dialog shows it: each line with its control and bidirectional characters escaped +/// and cut at [`MAX_HELP`] characters. +fn shown_text(s: &str) -> String { + let lines: Vec = s.split('\n').map(|l| permissions::display_text(l, MAX_HELP)).collect(); + lines.join("\n") +} + /// Checks text `s` at `path` against `max` characters (`lines`: `\n` allowed). fn check_text(s: &str, max: usize, lines: bool, path: &[&str]) -> Result<()> { if fits(s, max, lines) { @@ -277,11 +284,13 @@ impl Manifest { } /// Checks that no two options of a choice show the same label in language `lang`, naming the - /// choice's `options` under `path`. + /// choice's `options` under `path`. Labels are compared as dialogs show them, with control and + /// bidirectional characters escaped, so an option value holding U+202E and a translation + /// giving the text `\u{202E}` count as the same label. fn check_option_labels(&self, lang: &str, path: &[&str]) -> Result<()> { for (k, p) in &self.params { let ParamSpec::Choice { options, .. } = &p.spec else { continue }; - let shown: Vec<&str> = options.iter().map(|o| self.option_label_in(k, o, lang)).collect(); + let shown: Vec = options.iter().map(|o| shown_text(self.option_label_in(k, o, lang))).collect(); if shown.iter().enumerate().any(|(i, s)| shown.get(..i).is_some_and(|before| before.contains(s))) { let at = key(&[path, &[k.as_str(), "options"]].concat()); return Err(Error::Manifest(format!("{at} gives two options the same label"))); @@ -488,6 +497,15 @@ mod tests { let e = Manifest::parse(with(&translations).as_bytes()).unwrap_err().to_string(); assert!(e.contains(says), "{translations}: {e}"); } + // An option value holding U+202E shows as the text `\u{202E}`, so a translation giving + // that text for another option shows the same label. + let escaped = format!( + r#"{{"id":"a","name":"x","kind":"filter","params":{{"mode":{{"type":"choice","options":["soft","{}"]}}}}, + "translations":{{"de":{{"params":{{"mode":{{"options":{{"soft":"\\u{{202E}}"}}}}}}}}}}}}"#, + esc(0x202E) + ); + let e = Manifest::parse(escaped.as_bytes()).unwrap_err().to_string(); + assert!(e.contains("`translations.de.params.mode.options` gives two options the same label"), "{e}"); // Keys and types serde reads: an unknown key, a repeated one, and a value of the wrong type. for (translations, says) in [ (r#"{"de":{"title":"X"}}"#, "unknown field `title`"), diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 63c2e82b15..5ccf65a813 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -247,10 +247,11 @@ fn permission_words(name: &str, commands: &[String]) -> String { /// Installs the plug-in module that `module` names (`plugin.install`'s `path`, or `dataBase64` /// with `name`) → `plugin.install`'s result. A plug-in that lists permissions no person has granted /// it yet asks first, showing its name, id, version, file hash and what each permission lets it -/// do, so does a filter that asks for a heavy budget, and so does a module that would take the -/// place of another one with its id and get its settings and cache (`replace`); OK installs it if -/// the module still has the hash the prompt showed, Cancel installs nothing → `{pending}` while it -/// asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves. +/// do, so does a filter that asks for a heavy budget, showing its id and file hash, and so does a +/// module that would take the place of another one with its id and get its settings and cache +/// (`replace`). When the name shown is a translation, the id lines also give the manifest's own +/// name. OK installs it if the module still has the hash the prompt showed, Cancel installs +/// nothing → `{pending}` while it asks. The `grant` and `allowHeavy` of a request are ignored: only the dialog's OK approves. /// Every question opens the approval dialog ([`dialogs::plugin::ask_install`]). When automation /// asked ([`VectorcraftApp::automation_asked`]), the question has no OK that installs, its /// `replace: true` doesn't skip asking about replacing, and the answer while it asks adds @@ -323,6 +324,10 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result, } /// The editor's entries, the Effect menu's effect items and Object › Plug-ins' filter items while @@ -454,6 +458,7 @@ fn build_snapshot(revision: u64, lang: &'static str) -> Arc { group: e.group.clone(), is_tool: false, shows_key: false, + english: vectorcraft_plugins::effect::plugin_id(&e.effect).and_then(|id| own_plugin_text(id, lang, &e.group, &e.label)), })) .chain(filters.iter().map(|f| Entry { key: format!("plugin:{}", f.id), @@ -461,18 +466,21 @@ fn build_snapshot(revision: u64, lang: &'static str) -> Arc { group: f.group.clone(), is_tool: false, shows_key: false, + english: own_plugin_text(&f.id, lang, &f.group, &f.label), })) .chain(vectorcraft_engine::cmd::plugin::command_specs().into_iter().map(|c| { // A plug-in command's label and its plug-in's name in `lang`, as its menu shows them. + let own = (c.menu.join(" › "), c.label.to_string()); let (label, group) = match vectorcraft_engine::cmd::plugin::command_of(c.id) { Some((plugin, command)) => { let m = plugin.manifest(); let path: Vec = c.menu.iter().take(2).map(|s| s.to_string()).chain([m.shown_name(lang)]).collect(); (m.shown_command_label(&command, lang), path.join(" › ")) } - None => (c.label.to_string(), c.menu.join(" › ")), + None => (own.1.clone(), own.0.clone()), }; - Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false } + let english = (own != (group.clone(), label.clone())).then_some(own); + Entry { key: c.id.into(), label, group, is_tool: false, shows_key: false, english } })) .chain(tail.iter().cloned()) .collect(); @@ -480,6 +488,29 @@ fn build_snapshot(revision: u64, lang: &'static str) -> Arc { Arc::new(Snapshot { revision, lang, effects, filters, entries: entries.into() }) } +/// The group and label of plug-in `id`'s menu item, shown as `group` and `label` in UI language +/// `lang`, with the manifest's own name in place of the name its translations give there +/// ([`Entry::english`]); `None` when no such plug-in is installed or `lang` shows its own name. +fn own_plugin_text(id: &str, lang: &str, group: &str, label: &str) -> Option<(String, String)> { + use vectorcraft_plugins::permissions; + let plugin = vectorcraft_plugins::registry::get(id)?; + let m = plugin.manifest(); + let (shown, own) = (m.shown_name(lang), permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME)); + if shown == own { + return None; + } + // A plug-in with commands of its own has a submenu named after it. + let parts: Vec<&str> = group.split(" › ").collect(); + let submenu = matches!(parts.as_slice(), ["Object" | "Effect", "Plug-ins", name, ..] if *name == shown); + let group = parts.iter().enumerate().map(|(i, s)| if submenu && i == 2 { own.as_str() } else { *s }).collect::>().join(" › "); + let label = match label.strip_prefix(shown.as_str()) { + Some(rest) if own.ends_with('…') => format!("{own}{}", rest.trim_start_matches('…')), + Some(rest) => format!("{own}{rest}"), + None => label.to_string(), + }; + Some((group, label)) +} + /// Every tool, command and panel the editor can give a shortcut; [`listed`] says which it lists. pub fn entries() -> Arc<[Entry]> { snapshot().entries.clone() @@ -491,7 +522,14 @@ fn fixed_entries() -> &'static (Vec, Vec) { static E: OnceLock<(Vec, Vec)> = OnceLock::new(); E.get_or_init(|| { let mut v: Vec = vectorcraft_tools::catalog::all_tools() - .map(|t| Entry { key: format!("tool:{}", t.id), label: t.label.to_string(), group: "Tools".into(), is_tool: true, shows_key: false }) + .map(|t| Entry { + key: format!("tool:{}", t.id), + label: t.label.to_string(), + group: "Tools".into(), + is_tool: true, + shows_key: false, + english: None, + }) .collect(); let mut seen = HashSet::new(); // The commands listed only because an item of the menu bar runs them as a key press would @@ -506,7 +544,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { by_the_menu_bar.insert(c.id); } let group = if c.menu.is_empty() { id_group(c.id) } else { c.menu.join(" › ") }; - v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false }); + v.push(Entry { key: c.id.into(), label: c.label.into(), group, is_tool: false, shows_key: false, english: None }); } v.extend(crate::state::all_panels().map(|(id, label)| Entry { key: format!("panel:{id}"), @@ -514,6 +552,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { group: "Window".into(), is_tool: false, shows_key: false, + english: None, })); // Each effect of the Effect menu comes next, by its own key (#3296): see [`snapshot`]. let mut tail = vec![]; @@ -525,7 +564,7 @@ fn fixed_entries() -> &'static (Vec, Vec) { if !own { by_the_menu_bar.insert(id); } - tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false }); + tail.push(Entry { key: id.to_string(), label: label.to_string(), group: id_group(id), is_tool: false, shows_key: false, english: None }); } // A command listed only because an item of the menu bar runs it can have the group and // label of another entry. When that entry is an engine command that no item of the menu bar @@ -679,9 +718,13 @@ pub(crate) fn shown_name(e: &Entry) -> String { name_of(e, &shown_group(&e.group), shown_label(e)) } -/// [`shown_name`] in English, for a status or error message, which is translated when shown. +/// [`shown_name`] in English, for a status or error message, which is translated when shown; a +/// plug-in item by its manifest's own text ([`Entry::english`]). fn english_name(e: &Entry) -> String { - name_of(e, &e.group, &e.label) + match &e.english { + Some((group, label)) => name_of(e, group, label), + None => name_of(e, &e.group, &e.label), + } } /// Entry `e`'s name with its group and label as `group` and `label`. @@ -713,8 +756,13 @@ fn distinct_names(entries: &mut [Entry]) { // The entries of each name that more than one entry has. fn shared(entries: &[Entry]) -> Vec> { let mut by_name: HashMap> = HashMap::new(); + // A plug-in item counts under the name it shows and under its manifest's own name. for (i, e) in entries.iter().enumerate() { - by_name.entry(english_name(e)).or_default().push(i); + let (shown, english) = (name_of(e, &e.group, &e.label), english_name(e)); + if english != shown { + by_name.entry(english).or_default().push(i); + } + by_name.entry(shown).or_default().push(i); } by_name.into_values().filter(|list| list.len() > 1).collect() } @@ -1872,8 +1920,8 @@ pub fn is_recording(app: &VectorcraftApp) -> bool { // ---------- dialog ---------- /// The dialog's working set as a keymap, with the entries it lists, each entry's shortcut text (in -/// their order) and the number of conflicts, kept between frames while the set and the installed -/// plug-ins are unchanged. +/// their order) and the number of conflicts, kept between frames while the set, the installed +/// plug-ins and the UI language are unchanged. struct DialogView { /// The dialog's `overrides` field this was built from. source: Value, @@ -1881,6 +1929,8 @@ struct DialogView { backtick: Option, /// The plug-in revision of `entries`. revision: u64, + /// The UI language `entries` name plug-in items in ([`Snapshot::lang`]). + lang: &'static str, entries: Arc<[Entry]>, keymap: Keymap, texts: Vec>, @@ -1898,6 +1948,7 @@ impl DialogView { source: stored::to_value(&crate::keymap::effect_keys_in(&overrides, &snapshot.effects)), backtick, revision: snapshot.revision, + lang: snapshot.lang, entries: snapshot.entries.clone(), keymap, texts, @@ -1905,15 +1956,18 @@ impl DialogView { } } - /// The view of `d`'s working set, from the cache unless the set, the backtick key's character - /// or the installed plug-ins changed. The dialog's `overrides` field is left in its stored form. + /// The view of `d`'s working set, from the cache unless the set, the backtick key's character, + /// the installed plug-ins or the UI language changed. The dialog's `overrides` field is left in + /// its stored form. fn of(ctx: &egui::Context, d: &mut Dialog) -> Arc { let id = egui::Id::unique("dialog-shortcuts-view"); let source = d.fields.get("overrides").unwrap_or(&Value::Null); let backtick = backtick_text(); let revision = menus::plugin_revision(); - if let Some(v) = - ctx.data(|m| m.get_temp::>(id)).filter(|v| v.source == *source && v.backtick == backtick && v.revision == revision) + let lang = crate::i18n::current().code(); + if let Some(v) = ctx + .data(|m| m.get_temp::>(id)) + .filter(|v| v.source == *source && v.backtick == backtick && v.revision == revision && v.lang == lang) { return v; } @@ -3600,6 +3654,7 @@ mod tests { group: group.into(), is_tool: false, shows_key: false, + english: None, }; let menu = "Object › Plug-ins"; let mut rows = vec![ @@ -3625,6 +3680,24 @@ mod tests { ); } + /// The dialog's view is built again when the UI language changes, so reopening Keyboard + /// Shortcuts after a change of language lists plug-in items in the new language. + #[test] + fn the_dialog_view_is_built_again_when_the_language_changes() { + let ctx = egui::Context::default(); + let mut d = Dialog::new("shortcuts", json!({})); + let (en, again, de) = with_steady_plugins(|| { + let en = DialogView::of(&ctx, &mut d); + let again = DialogView::of(&ctx, &mut d); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let de = DialogView::of(&ctx, &mut d); + crate::i18n::set_current(crate::i18n::Lang::EN); + (en, again, de) + }); + assert!(Arc::ptr_eq(&en, &again), "kept while nothing changes"); + assert_eq!((en.lang, de.lang), ("en", "de")); + } + /// A command with items in more than one menu is shown under the path of its first item with /// no params, or else of its first item: Recolor Artwork… under Edit › Edit Colors, not Edit › /// Edit Colors › Recolor with Preset. diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index 063d63bb14..1d8e0ad34b 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -3548,6 +3548,7 @@ fn a_filter_plugin_row_translates_its_path_and_not_its_name() { group: "Object › Plug-ins".into(), is_tool: false, shows_key: false, + english: None, }; let path = format!("{} › {}", crate::i18n::tr(zh, "Object"), crate::i18n::tr(zh, "Plug-ins")); let (filter, command) = (crate::shortcut_editor::shown_name(&entry("plugin:a.b")), crate::shortcut_editor::shown_name(&entry("object.group"))); diff --git a/crates/ui-egui/src/tests/plugin_runs.rs b/crates/ui-egui/src/tests/plugin_runs.rs index 32cc241027..930eb41fc4 100644 --- a/crates/ui-egui/src/tests/plugin_runs.rs +++ b/crates/ui-egui/src/tests/plugin_runs.rs @@ -90,6 +90,37 @@ fn installing_a_heavy_filter_asks_first() { assert!(registry::get(id).is_none()); } +/// The heavy-budget question gives the filter's ID and file SHA-256, and also the manifest's own +/// name when the name it asks with is a translation. +#[test] +fn the_heavy_budget_question_shows_the_id_hash_and_manifest_name() { + let mut app = app(); + let id = "test.ui.heavy.translated"; + let manifest = + format!(r#"{{"id":"{id}","name":"Route","version":"1","kind":"filter","budget":"heavy","translations":{{"de":{{"name":"Fräsen"}}}}}}"#); + let bytes = wat::parse_str(tpl::spinning(&manifest, 1, r#"{"objects":[]}"#)).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(&bytes); + let data = vectorcraft_format::base64_encode(&bytes); + let ask = |app: &mut VectorcraftApp, lang: &str| { + crate::i18n::set_current(crate::i18n::Lang::from_code(lang).unwrap()); + let r = app.run("ui.installPlugin", json!({ "dataBase64": data })); + let pending = app.pending_plugin_install.as_ref().map(|p| (p.message.clone(), p.detail.clone())); + crate::i18n::set_current(crate::i18n::Lang::EN); + dialogs::cancel(app); + assert_eq!(r.unwrap()["pending"], dialogs::plugin::INSTALL_KIND); + pending.unwrap() + }; + let (message, detail) = ask(&mut app, "de"); + assert!(message.contains("Fräsen") && !message.contains("Route"), "{message}"); + for shown in [id, "Route", hash.as_str()] { + assert!(detail.contains(shown), "{shown}: {detail}"); + } + let (message, detail) = ask(&mut app, "en"); + assert_eq!(message, "Install “Route”, which asks for a heavy budget?"); + assert!(detail.starts_with(&format!("ID: {id}\nFile SHA-256: {hash}\n\n")), "no second name line: {detail}"); + assert!(registry::get(id).is_none()); +} + /// The dialog has no Preview; OK closes it and the filter runs in the background, the status bar /// saying so, and its result is one undo step named after it, selected. #[test] diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 81046387f3..030b6bfb55 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -864,6 +864,35 @@ fn keyboard_shortcuts_leave_a_plugin_commands_text_as_the_plugin_gives_it() { assert_eq!(shown, Some(expected)); } +/// A shortcut conflict names a translated plug-in's filter and command by the manifest's own text, +/// as status and error messages name every entry in English, while Keyboard Shortcuts lists them in +/// the UI language. +#[test] +fn a_shortcut_conflict_names_a_translated_plugin_by_its_own_text() { + let mut app = app(); + let id = "test.ui.translated.conflict"; + // Names no other test's plug-in has, since tests running beside this one share the registry. + let manifest = format!( + r#"{{"id":"{id}","name":"Neaten","kind":"filter","commands":[{{"id":"grow","label":"Grow Rim"}}],"translations":{{"de":{{"name":"Ordnen","commands":{{"grow":{{"label":"Rand wachsen"}}}}}}}}}}"# + ); + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + let (grow, own) = (format!("plugin.{id}.grow"), format!("plugin:{id}")); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + let conflict = |first: &str, second: &str| { + let mut ov = craft_keymap::Overrides::new(); + crate::shortcut_editor::assign(&mut ov, first, Some("Cmd+Alt+Shift+F10"), false).unwrap(); + crate::shortcut_editor::assign(&mut ov, second, Some("Cmd+Alt+Shift+F10"), false).unwrap_err() + }; + let (by_command, by_filter) = (conflict(&grow, &own), conflict(&own, &grow)); + let label = crate::shortcut_editor::entry(&grow).map(|e| e.label); + crate::i18n::set_current(crate::i18n::Lang::EN); + app.run("plugin.remove", json!({"id": id})).unwrap(); + assert_eq!(label.as_deref(), Some("Rand wachsen"), "the row is in German"); + assert!(by_command.ends_with("is already used by Object › Plug-ins › Neaten › Grow Rim"), "{by_command}"); + assert!(by_filter.ends_with("is already used by Object › Plug-ins › Neaten › Neaten"), "{by_filter}"); +} + /// A filter's and an importer's menu item show their names as prompts do, a right-to-left override /// escaped, as a filter with commands already showed its submenu. #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 42a20023c5..7a3f5b3665 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -177,8 +177,8 @@ an importer an import's). Each of its runs gets 1 G instructions (20 times a lig and 300 s (`vectorcraft_plugins::{HEAVY_FUEL, HEAVY_WALL_TIME_MS}`). Its output can't add to the budget: the host learns how much there is only once the run has ended. -- **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, and install it once the - user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`, +- **Installing asks first.** Install Plug-in… and File › Open show what the filter asks for, with its ID and file + SHA-256, and install it once the user clicks OK (see [Permissions](#permissions) for who can). `plugin.install` refuses it without `allowHeavy: true`, and refuses `allowHeavy` from a request except in a session started with `vectorcraft-cli --allow-plugin-grants` (`plugin.inspect` shows the budget beforehand). A filter kept in the `Plug-ins` folder was agreed to and is installed again at startup. The Additional Plug-ins Folder skips heavy filters with a note in its report, since loading a folder From 8e093c9e148b592929f682e30167402dc5cab4b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:35:16 -0800 Subject: [PATCH 037/153] Command palette: a translated plug-in is still found by its manifest name A filter or live-effect plug-in whose name the UI language translates shows the translation in the palette, and a search for the manifest's own name finds it too. Export Text's test compares its rows with the names the dialog shows, which for a plug-in with an English translation differ from the manifest text that messages use. --- crates/ui-egui/src/palette.rs | 59 ++++++++++++++++++++++++--- crates/ui-egui/src/shortcut_editor.rs | 12 +++++- 2 files changed, 64 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index eabb023ad4..644952aaee 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -109,6 +109,10 @@ struct Draft { /// Is this a plug-in command, whose label and plug-in name come from the plug-in's own /// translations? plugin_command: bool, + /// For a filter or live-effect plug-in item whose path and label give the plug-in's name in the + /// UI language from its translations: the path and label with the manifest's own text, which a + /// query also matches ([`Draft::plain`]). + own: Option<(String, String)>, id: String, shortcut: String, /// Has [`distinct_names`] given the result its [`context`]? @@ -124,6 +128,7 @@ impl Draft { label: label.to_string(), translates: true, plugin_command: false, + own: None, id, shortcut: shortcut.to_string(), in_context: false, @@ -157,6 +162,16 @@ impl Draft { let name = if self.path.is_empty() { label.to_string() } else { format!("{} › {label}", shown_label(lang, &self.path)) }; if self.keyed { format!("{name} ({})", self.id) } else { name } } + + /// The English name a query matches before [`distinct_names`] runs: a plug-in item that shows + /// a translated name by the manifest's own text ([`Draft::own`]). + fn plain(&self) -> String { + match &self.own { + Some((path, label)) if path.is_empty() => label.clone(), + Some((path, label)) => format!("{path} › {label}"), + None => self.name(crate::i18n::Lang::EN), + } + } } /// The palette's results before their names are made distinct: every listed engine command and @@ -203,9 +218,12 @@ fn drafts() -> Vec { } // An Effect menu item runs what its item runs; a live-effect plug-in's name does not translate. for e in crate::shortcut_editor::effect_items().iter() { + let plugin = vectorcraft_plugins::effect::plugin_id(&e.effect).is_some(); + let id = format!("effect:{}", e.effect); out.push(Draft { - translates: vectorcraft_plugins::effect::plugin_id(&e.effect).is_none(), - ..Draft::new(&e.group, &e.label, format!("effect:{}", e.effect), crate::shortcut_editor::effect_shortcut(&e.effect).unwrap_or("")) + translates: !plugin, + own: if plugin { crate::shortcut_editor::own_plugin_text_of(&id) } else { None }, + ..Draft::new(&e.group, &e.label, id, crate::shortcut_editor::effect_shortcut(&e.effect).unwrap_or("")) }); } out @@ -429,11 +447,15 @@ fn build(lang: crate::i18n::Lang) -> Vec { fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { let homes = search::menu_homes(native); let mut drafts = drafts(); - drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| Draft { - translates: false, - ..Draft::new(&f.group, &f.label, format!("plugin:{}", f.id), crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("")) + drafts.extend(crate::shortcut_editor::filter_items().iter().map(|f| { + let id = format!("plugin:{}", f.id); + Draft { + translates: false, + own: crate::shortcut_editor::own_plugin_text_of(&id), + ..Draft::new(&f.group, &f.label, id, crate::shortcut_editor::filter_shortcut(&f.id).unwrap_or("")) + } })); - let plain: Vec = drafts.iter().map(|d| d.name(crate::i18n::Lang::EN)).collect(); + let plain: Vec = drafts.iter().map(Draft::plain).collect(); distinct_names(&mut drafts, &[crate::i18n::Lang::EN, lang]); drafts .into_iter() @@ -3306,6 +3328,31 @@ mod tests { assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); } + /// A filter whose name the UI language translates shows the translation, English included, and + /// a search for the manifest's own name still finds it. + #[test] + fn a_translated_filter_is_found_by_its_manifest_name() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_translated_filter"; + let manifest = format!( + r#"{{"id":"{id}","name":"Polish Edges","version":"1","kind":"filter","translations":{{"de":{{"name":"Kanten polieren"}},"en":{{"name":"Smooth Edges"}}}}}}"# + ); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let found = |lang: Lang| { + crate::i18n::set_current(lang); + let found = build(lang).into_iter().find(|e| e.id == format!("plugin:{id}")).map(|e| (e.shown, e.haystack)); + crate::i18n::set_current(Lang::EN); + found + }; + let (de, en) = (found(Lang::from_code("de").unwrap()), found(Lang::EN)); + vectorcraft_plugins::registry::remove(id); + for (found, name) in [(de, "Kanten polieren"), (en, "Smooth Edges")] { + let (shown, haystack) = found.expect("the filter is a result"); + assert!(shown.ends_with(name), "{shown}"); + assert!(haystack.contains("polish edges"), "{haystack}"); + } + } + /// A plug-in's name in the path of its own item, in the submenu a plug-in with commands gets, /// stays as the plug-in gives it where it matches text the app translates ("Open" in German). #[test] diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 7c1d4fc044..96b87827b0 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1151,6 +1151,16 @@ pub fn entry(key: &str) -> Option { entries().iter().find(|e| e.key == key).cloned() } +/// The group and label of plug-in item `key` (`plugin:` or `effect:`) with the manifest's +/// own text, when the item shows the plug-in's name in the UI language from its translations +/// ([`Entry::english`]); `None` for every other entry. +pub(crate) fn own_plugin_text_of(key: &str) -> Option<(String, String)> { + if !key.starts_with("plugin:") && !key.starts_with("effect:") { + return None; + } + entries().iter().find(|e| e.key == key).and_then(|e| e.english.clone()) +} + /// Entries (other than `except`) whose effective shortcut equals `chord`. pub fn conflicts_with(overrides: &Overrides, chord: &str, except: &str) -> Vec { let Some(c) = vc_chord(chord) else { return vec![] }; @@ -2788,7 +2798,7 @@ mod tests { let text = export_text("VectorCraft Defaults", &ov); let km = keymap_with(&ov); let names = |tools: bool| -> Vec { - entries().iter().filter(|e| e.is_tool == tools && listed(km.overrides(), e)).map(|e| format!("{}\t", english_name(e))).collect() + entries().iter().filter(|e| e.is_tool == tools && listed(km.overrides(), e)).map(|e| format!("{}\t", shown_name(e))).collect() }; let rows = (names(true), names(false)); (text, km, rows.0, rows.1) From 64ba4f59d1a3f05e7c01b0249c2ce584e56d39a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:51:40 -0800 Subject: [PATCH 038/153] Last Effect: a plug-in's translated name is not translated again Last Effect shows a live-effect plug-in's name in the UI language as the plug-in's translations give it, even where it matches text the app translates ("Open" in German stays "Open"). --- crates/ui-egui/src/menus/labels.rs | 4 +++- crates/ui-egui/src/tests/plugins.rs | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 365315facb..c1a06ea48a 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -194,8 +194,10 @@ pub fn display_label(app: &VectorcraftApp, id: &str, label: &str) -> String { } "effect.last" => match &app.last_effect { Some((e, _)) => { + // A plug-in's name is already in the UI language from its translations. let name = last_effect_name(e); - fmt(tl!("Last Effect: {name}"), &[("name", crate::i18n::tr_id(lang, e, name))]) + let name = if vectorcraft_plugins::effect::plugin_id(e).is_some() { name } else { crate::i18n::tr_id(lang, e, name) }; + fmt(tl!("Last Effect: {name}"), &[("name", name)]) } None => crate::i18n::tr_id(lang, id, label).to_string(), }, diff --git a/crates/ui-egui/src/tests/plugins.rs b/crates/ui-egui/src/tests/plugins.rs index 030b6bfb55..dec0b39419 100644 --- a/crates/ui-egui/src/tests/plugins.rs +++ b/crates/ui-egui/src/tests/plugins.rs @@ -845,6 +845,26 @@ fn plugin_menus_show_the_plugins_names_in_the_ui_language() { } } +/// Last Effect shows a live-effect plug-in's translated name as the plug-in gives it, even where it +/// matches text the app translates: "Open" in German stays "Open". +#[test] +fn last_effect_leaves_a_plugins_translated_name_as_it_gives_it() { + let mut app = app(); + let effect = "test.ui.translated.last_effect"; + let manifest = format!(r#"{{"id":"{effect}","name":"Unseal","kind":"effect","translations":{{"de":{{"name":"Open"}}}}}}"#); + let module = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + app.run("plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&module)})).unwrap(); + app.last_effect = Some((vectorcraft_plugins::effect::effect_id(effect), json!({}))); + let de = crate::i18n::Lang::from_code("de").unwrap(); + crate::i18n::set_current(de); + let shown = menus::display_label(&app, "effect.last", "Last Effect…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + app.last_effect = None; + app.run("plugin.remove", json!({"id": effect})).unwrap(); + assert_ne!(crate::i18n::tr(de, "Open"), "Open", "German translates the app's Open"); + assert_eq!(shown, crate::i18n::fmt(crate::i18n::tr(de, "Last Effect: {name}"), &[("name", "Open")])); +} + /// Keyboard Shortcuts shows a plug-in command's label and its plug-in's name as the plug-in gives /// them, even where they match text the app translates: in German, a command labeled "Open" of a /// plug-in named "Close" keeps both, as in its menu. From e84336a5c7ad04e93f17a16498023fed5c59146e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:05:42 -0800 Subject: [PATCH 039/153] Command palette: a plug-in command is found by its manifest's own text A plug-in command whose plug-in translates its name and label into English shows the translation, and a search for the manifest's own name and label still finds it. --- crates/ui-egui/src/palette.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 644952aaee..852c0ddeb3 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -164,8 +164,17 @@ impl Draft { } /// The English name a query matches before [`distinct_names`] runs: a plug-in item that shows - /// a translated name by the manifest's own text ([`Draft::own`]). + /// a translated name by the manifest's own text ([`Draft::own`]), and a plug-in command by its + /// plug-in's own name and its own label. fn plain(&self) -> String { + if self.plugin_command + && let Some((plugin, command)) = vectorcraft_engine::cmd::plugin::command_of(&self.id) + { + use vectorcraft_plugins::permissions; + let own = permissions::display_text(plugin.manifest().name.trim(), permissions::MAX_SHOWN_NAME); + let top = self.path.rsplit_once(" › ").map_or("", |(top, _)| top); + return format!("{top} › {own} › {}", command.shown_label()); + } match &self.own { Some((path, label)) if path.is_empty() => label.clone(), Some((path, label)) => format!("{path} › {label}"), @@ -3328,6 +3337,25 @@ mod tests { assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); } + /// A plug-in command whose plug-in translates its name and label into English shows the + /// translation, and a search for the manifest's own text still finds it. + #[test] + fn a_plugin_command_with_english_translations_is_found_by_its_own_text() { + use vectorcraft_plugins::wat as tpl; + let id = "test.UI.palette_english_command"; + let manifest = format!( + r#"{{"id":"{id}","name":"Trim Pack","version":"1","kind":"filter","commands":[{{"id":"shave","label":"Shave Ends"}}], + "translations":{{"en":{{"name":"Trimmer","commands":{{"shave":{{"label":"Cut Tips"}}}}}}}}}}"# + ); + vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); + let key = format!("plugin.{id}.shave"); + let found = build(Lang::EN).into_iter().find(|e| e.id == key).map(|e| (e.shown, e.haystack)); + vectorcraft_plugins::registry::remove(id); + let (shown, haystack) = found.expect("the command is a result"); + assert!(shown.ends_with("Trimmer › Cut Tips"), "{shown}"); + assert!(haystack.contains("trim pack › shave ends"), "{haystack}"); + } + /// A filter whose name the UI language translates shows the translation, English included, and /// a search for the manifest's own name still finds it. #[test] From 7615aed3ee6b719c299f2c29c0c5fa5829e46aa2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:16:11 -0800 Subject: [PATCH 040/153] JavaScript: a .mjs script runs as an ECMAScript 2015 module script.run, File > Scripts and Other Script... run a file ending in .mjs as a module: strict code with import and export declarations at its top level. parse_module reads the module grammar and its early errors, and Realm::start_module and Realm::run_module load the module graph through the host, link every import before any module runs, and run each module once, after the modules it imports. Imports read the exporting binding each time; a read before initialization is a ReferenceError and an assignment is a TypeError. import * as ns gives a namespace object that is not extensible, and Object.isSealed and Object.isFrozen on it throw a ReferenceError for an export its module has not initialized. Specifiers are ./ and ../ paths to .mjs and .js files, resolved against the importing file and read only through the script's file scope, so a module can import only from the script's folder and the folders below it. Bare names, URLs and absolute paths are a SyntaxError that names the specifier. Module files count against the #include limits: 64 files besides the script, 16 imports deep. import and export stay syntax errors in .js and .jsx scripts; import() is not read. script.listInstalled lists .mjs files. The test262 runner also runs the module tests under language/module-code, import and export, reading the fixture files they import from the suite. --- crates/engine/src/cmd/scripts.rs | 8 +- crates/engine/src/script/folder.rs | 4 +- crates/engine/src/script/include.rs | 129 ++++++- crates/engine/src/script/mod.rs | 35 +- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_modules.rs | 227 +++++++++++ crates/engine/tests/script_corpus.rs | 2 +- crates/js/src/ast.rs | 52 +++ crates/js/src/builtins.rs | 4 +- crates/js/src/builtins/object.rs | 6 +- crates/js/src/compiler.rs | 14 + crates/js/src/heap.rs | 55 ++- crates/js/src/interp.rs | 200 +++++++++- crates/js/src/lib.rs | 47 ++- crates/js/src/module.rs | 448 ++++++++++++++++++++++ crates/js/src/module_tests.rs | 419 ++++++++++++++++++++ crates/js/src/parser.rs | 8 + crates/js/src/parser/module.rs | 299 +++++++++++++++ crates/js/src/realm.rs | 89 ++++- crates/js/tests/test262.rs | 172 ++++++++- crates/mcp/src/ui_catalog.rs | 4 +- crates/ui-egui/src/dialogs/script_run.rs | 4 +- crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tests.rs | 4 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/menus/ui_commands.rs | 4 +- crates/ui-egui/src/tests/script_run.rs | 2 +- docs/mcp.md | 38 +- docs/target-app-parity.md | 5 +- 52 files changed, 2270 insertions(+), 110 deletions(-) create mode 100644 crates/engine/src/tests/script_modules.rs create mode 100644 crates/js/src/module.rs create mode 100644 crates/js/src/module_tests.rs create mode 100644 crates/js/src/parser/module.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..67d6556bbe 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -18,7 +18,7 @@ use crate::script; pub const EXTS: &[&str] = &["jsx", "jsxinc", "jsxbin"]; /// The extensions of the scripts `script.run` takes as a file, in any case. -pub const RUN_EXTS: &[&str] = &["js", "jsx"]; +pub const RUN_EXTS: &[&str] = &["js", "mjs", "jsx"]; /// Does `path` name a file `script.run` takes? pub fn runs(path: &str) -> bool { @@ -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; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns 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 script file (.js, .mjs or .jsx) | 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. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, and an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. 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; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns 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 ), @@ -86,7 +86,7 @@ pub fn specs() -> Vec { "List Installed Scripts", [], None, - "{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", + "{} list the .js, .mjs and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}", always, list_installed ), @@ -188,7 +188,7 @@ fn run(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Other(COMPILED.to_string())); } if !runs(path) { - return Err(param("`path` must name a .js or .jsx file")); + return Err(param("`path` must name a .js, .mjs or .jsx file")); } // One byte more than a script may have shows that the file is too large. let bytes = super::fileio::read_file_head(path, script::MAX_SOURCE_BYTES + 1)?; diff --git a/crates/engine/src/script/folder.rs b/crates/engine/src/script/folder.rs index d071195df6..8226fa0711 100644 --- a/crates/engine/src/script/folder.rs +++ b/crates/engine/src/script/folder.rs @@ -1,4 +1,4 @@ -//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a +//! The Scripts folder: the `.js`, `.mjs` and `.jsx` files File › Scripts lists, with each subfolder as a //! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]). //! //! A listing reads names and file types only, never a script's text. It follows no link: a symbolic @@ -256,7 +256,7 @@ fn plain(path: &Path, folder: bool, shown: bool) -> bool { .is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m))) } -/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most +/// Is `path` a script a listing of `root` can hold now: a `.js`, `.mjs` or `.jsx` file at most /// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there /// and none is a link, and neither the file nor a folder below `root` is marked hidden or system? pub fn holds(root: &Path, path: &Path) -> bool { diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index a024949a35..8de325cb70 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -37,11 +37,21 @@ //! //! The expanded source keeps a [`SourceMap`], so an error is reported at the line and column of //! the file it is in. +//! +//! A `.mjs` script is a module ([`module_script`]): it has no preprocessor lines, and the modules +//! it imports are read by [`Files::module`]. A specifier is a path relative to the importing +//! module's file, starting with `./` or `../` and naming a `.mjs` or `.js` file; a bare name, a URL +//! and any other form are a `SyntaxError`. Its `..` names are taken off by name, and one that would +//! lead above the script's folder is refused. Modules are read through the same [`ScriptScope`], +//! so a link that leads out of the script's folder is refused as well. Module files count against +//! the same limits as included files, and the paths of one file (two spellings, a link, or names +//! that differ only in letter case on Windows) give one module. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; -use vectorcraft_js::{DirectiveName, Options}; +use vectorcraft_js::{DirectiveName, LoadError, Options}; use crate::file_access::{ScriptRead, ScriptScope}; @@ -219,13 +229,57 @@ pub(crate) struct Files { frames: Vec, /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. es2015: bool, + /// The modules a module run has read, by key ([`module_key`]): the names of the folders each + /// is in, below the script's folder. + module_dirs: HashMap>, + /// The key of each module path read, below the script's folder. + module_paths: HashMap, } /// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in -/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as -/// ECMAScript 5.1 with the ExtendScript extensions. +/// `.js` or `.mjs` (in any letter case); a `.jsx` script, any other file and a script given as text +/// run as ECMAScript 5.1 with the ExtendScript extensions. pub(crate) fn es2015_script(path: Option<&str>) -> bool { - path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js") || e.eq_ignore_ascii_case("mjs")) +} + +/// A script at `path` runs as a module when its file name ends in `.mjs` (in any letter case). +pub(crate) fn module_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("mjs")) +} + +/// What names the file at the real path `real` among a run's modules: on Unix its device and file +/// number, so two paths to one file give one module; elsewhere its path, in lowercase on Windows, +/// whose file names ignore letter case. +fn module_key(real: &Path) -> String { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if let Ok(m) = std::fs::metadata(real) { + return format!("{}:{}", m.dev(), m.ino()); + } + } + let shown = display(real).to_string(); + if cfg!(windows) { shown.to_lowercase() } else { shown } +} + +/// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between +/// names and names a `.mjs` or `.js` file. A specifier in any other form is a syntax error. +fn specifier_names(specifier: &str) -> Result, LoadError> { + let wrong = |why: &str| Err(LoadError::Syntax(format!("module specifier '{specifier}' {why}"))); + if !(specifier.starts_with("./") || specifier.starts_with("../")) { + return wrong("must start with './' or '../'"); + } + if specifier.chars().any(|c| matches!(c, '\\' | ':' | '\0') || c.is_control()) { + return wrong("must not contain \\, : or control characters"); + } + let names: Vec<&str> = specifier.split('/').collect(); + let file = names.last().copied().unwrap_or_default(); + let ext = Path::new(file).extension().and_then(|e| e.to_str()).unwrap_or_default(); + if !(ext.eq_ignore_ascii_case("mjs") || ext.eq_ignore_ascii_case("js")) { + return wrong("must name a .mjs or .js file"); + } + Ok(names) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -321,9 +375,76 @@ impl Files { levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], es2015: es2015_script(path), + module_dirs: HashMap::new(), + module_paths: HashMap::new(), } } + /// The module `text`, the script's own, as a source of one file. → its key and the source. + pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> { + self.bytes = self.bytes.saturating_add(text.len()); + let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); + let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default(); + self.module_dirs.insert(key.clone(), Vec::new()); + let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; + Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None })) + } + + /// The module `specifier` names for the module `referrer` (a key [`Files::module_entry`] or + /// this function gave). → the module's key, with its text and source map the first time the + /// run reads it. + pub(crate) fn module(&mut self, referrer: &str, specifier: &str) -> Result<(String, Option<(String, SourceMap)>), LoadError> { + let names = specifier_names(specifier)?; + let mut path = self.module_dirs.get(referrer).cloned().ok_or_else(|| LoadError::Other(format!("module not found: '{referrer}'")))?; + for name in names { + match name { + "" | "." => {} + ".." => { + if path.pop().is_none() { + return Err(LoadError::Other(format!("module path leads out of the script's folder: '{specifier}'"))); + } + } + name => path.push(name.to_string()), + } + } + let relative = path.join("/"); + if let Some(key) = self.module_paths.get(&relative) { + return Ok((key.clone(), None)); + } + let root = + self.frames.first().and_then(|f| f.dir.clone()).ok_or_else(|| LoadError::Other(format!("script file read refused: {specifier}")))?; + self.probes += 1; + if self.probes > MAX_PROBES { + return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached"))); + } + let candidate = path.iter().fold(root, |p, name| p.join(name)); + let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + Ok(found) => found, + Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))), + Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))), + Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))), + Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))), + }; + if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { + return Err(LoadError::Range("script source limit reached (32 MiB)".to_string())); + } + self.bytes += bytes.len(); + let key = module_key(&real); + self.module_paths.insert(relative, key.clone()); + if self.module_dirs.contains_key(&key) { + return Ok((key, None)); + } + if self.files >= MAX_FILES { + return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); + } + self.files += 1; + let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + path.pop(); + self.module_dirs.insert(key.clone(), path); + let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; + Ok((key, Some((text, map)))) + } + /// The options a file of this run is parsed with, preprocessor lines aside. pub(crate) fn options(&self) -> Options { Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index a01453a627..e318c0abb6 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -62,7 +62,8 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use vectorcraft_js::{ - Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, Options, Progress, Realm, RunError, RunErrorKind, + Data, DataLimits, HostError, HostFunction, HostItem, Interrupt, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, + Realm, RunError, RunErrorKind, }; use crate::{ @@ -1575,6 +1576,19 @@ fn explained(e: &RunError) -> String { } } +/// The module `specifier` names for the module `referrer` of the run of `host`, read through the +/// run's files. Its source map is kept with the maps of the sources the run evaluates, in the order +/// the modules are read, which is the order of their sources' tags. +fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result { + let (key, read) = host.files.borrow_mut().module(referrer, specifier)?; + let source = read.map(|(text, map)| { + host.eval_maps.borrow_mut().push(map); + host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::>()); + text + }); + Ok(LoadedModule { key, source }) +} + /// The error of a run that stopped in its preprocessor lines (`f`), as the realm gives its own. fn preprocessor_error(f: include::Failure) -> (RunError, Option>) { let (kind, message) = match f.kind { @@ -1937,7 +1951,16 @@ impl Session { self.script_stop.clear(); self.script_report = None; let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env()); - let expanded = files.expand_script(&request.source); + // A `.mjs` script is a module, with no preprocessor lines; `module_key` names it among the + // modules it imports. + let (expanded, module_key) = if include::module_script(request.file.as_deref()) { + match files.module_entry(&request.source) { + Ok((key, expanded)) => (Ok(expanded), Some(key)), + Err(f) => (Err(f), None), + } + } else { + (files.expand_script(&request.source), None) + }; let name = match &expanded { Ok(include::Expanded { name: Some(name), .. }) if !request.name_given => name.clone(), _ => request.name, @@ -2083,7 +2106,13 @@ impl Session { .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { - let r = realm.start(&expanded.source); + let r = match &module_key { + None => realm.start(&expanded.source), + Some(key) => { + let limits = ModuleLimits { modules: include::MAX_FILES + 1, depth: include::MAX_DEPTH }; + realm.start_module(key, &expanded.source, limits, &mut |referrer, specifier| load_module(&host, referrer, specifier)) + } + }; // Source that does not compile defines no code, so its map is not kept. if !matches!(&r, Err(e) if e.kind == RunErrorKind::Syntax) { host.script_tag.set(realm.script_tag()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..cfaf6649ba 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -176,6 +176,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_modules; mod script_run; mod scripts; mod select_effects; diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs new file mode 100644 index 0000000000..9727abb927 --- /dev/null +++ b/crates/engine/src/tests/script_modules.rs @@ -0,0 +1,227 @@ +//! `.mjs` scripts: modules, the modules they import from the script's folder, the refusals of +//! specifiers and paths, the run's limits, and errors at the file they are in. + +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +use crate::*; + +/// A fresh folder for test `name`, with a `main` folder inside it for the script. +fn folder(name: &str) -> PathBuf { + let base = std::env::temp_dir().join(format!("vc-script-modules-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + base +} + +fn write(path: &Path, text: &str) { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).unwrap(); + } + std::fs::write(path, text).unwrap(); +} + +/// Runs `main/` in `base`, with the text `text`. +fn run_file(base: &Path, file: &str, text: &str) -> (Result, Session) { + let main = base.join("main").join(file); + write(&main, text); + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})); + (r, s) +} + +fn run(base: &Path, text: &str) -> Result { + run_file(base, "main.mjs", text).0 +} + +/// The report of the run of `main/main.mjs` that failed. +fn failed(base: &Path, text: &str) -> Value { + let (r, s) = run_file(base, "main.mjs", text); + assert!(r.is_err(), "the run failed: {r:?}"); + s.script_report().unwrap().clone() +} + +fn message(report: &Value) -> &str { + report["message"].as_str().unwrap_or_default() +} + +#[test] +fn script_module_imports_from_its_folder_and_below() { + let base = folder("imports"); + write(&base.join("main/lib/count.mjs"), "export let n = 0;\nexport function inc() { n++; }\nexport default 'lib';"); + write( + &base.join("main/lib/use.mjs"), + "import { inc } from './count.mjs';\nimport name from '../lib/count.mjs';\nexport const used = name;\ninc();", + ); + let text = "import { n, inc } from './lib/count.mjs';\nimport { used } from './lib/use.mjs';\ninc();\nvc.log([n, used, this === undefined, /main\\.mjs$/.test($.fileName)]);"; + let r = run(&base, text).unwrap(); + // count.mjs ran once: use.mjs and the script share its binding. + assert_eq!(r["log"], json!([[2, "lib", true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_two_modules_import_each_other() { + let base = folder("cycle"); + write(&base.join("main/a.mjs"), "import { b } from './b.mjs';\nexport function a() { return 'a' + b(); }"); + write(&base.join("main/b.mjs"), "import { a } from './a.mjs';\nexport function b() { return 'b'; }\nexport const viaA = () => a();"); + let r = run(&base, "import { a } from './a.mjs';\nimport { viaA } from './b.mjs';\nvc.log([a(), viaA()]);").unwrap(); + assert_eq!(r["log"], json!([["ab", "ab"]])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_path_above_the_script_folder_is_refused() { + let base = folder("above"); + write(&base.join("outside.mjs"), "export var leaked = 1;"); + let report = failed(&base, "vc.log(1);\nimport { leaked } from '../outside.mjs';"); + assert!(message(&report).contains("module path leads out of the script's folder: '../outside.mjs'"), "{report}"); + assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(2), json!([])), "{report}"); + // `..` names that stay inside are read by name. + write(&base.join("main/sub/x.mjs"), "export var x = 'x';"); + let r = run(&base, "import { x } from './sub/../sub/./x.mjs';\nvc.log(x);").unwrap(); + assert_eq!(r["log"], json!(["x"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_missing_file_is_named() { + let base = folder("missing"); + write(&base.join("main/a.mjs"), "import './nope.mjs';"); + let report = failed(&base, "import './a.mjs';"); + assert!(message(&report).contains("module file not found: ./nope.mjs"), "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("a.mjs"), "{report}"); + assert_eq!(report["line"], 1); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_specifiers_other_than_relative_paths_are_syntax_errors() { + let base = folder("specifiers"); + // The specifier as the script writes it, as the error names it, and why it is refused. + for (written, shown, why) in [ + ("lib", "lib", "must start with './' or '../'"), + ("lib/x.mjs", "lib/x.mjs", "must start with './' or '../'"), + ("https://example.com/x.mjs", "https://example.com/x.mjs", "must start with './' or '../'"), + ("/abs/x.mjs", "/abs/x.mjs", "must start with './' or '../'"), + ("./C:x.mjs", "./C:x.mjs", "must not contain"), + ("./a\\u005cb.mjs", "./a\\b.mjs", "must not contain"), + ("./x.txt", "./x.txt", "must name a .mjs or .js file"), + ("./x", "./x", "must name a .mjs or .js file"), + ] { + let report = failed(&base, &format!("import '{written}';")); + let expected = format!("SyntaxError: module specifier '{shown}' {why}"); + assert!(message(&report).starts_with(&expected), "{written}: {report}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_errors_are_at_the_file_they_are_in() { + let base = folder("errors"); + write(&base.join("main/bad.mjs"), "export var a = 1;\nexport var = 2;"); + let report = failed(&base, "import { a } from './bad.mjs';"); + assert_eq!(report["kind"], "syntax", "{report}"); + assert!(report["file"].as_str().unwrap().ends_with("bad.mjs"), "{report}"); + assert_eq!(report["line"], 2); + write(&base.join("main/thrower.mjs"), "export var a = 1;\n\nthrow new Error('from thrower');"); + let report = failed(&base, "import { a } from './thrower.mjs';\nvc.log(a);"); + assert!(report["file"].as_str().unwrap().ends_with("thrower.mjs"), "{report}"); + assert_eq!((report["line"].as_u64(), report["log"].clone()), (Some(3), json!([])), "{report}"); + let report = failed(&base, "import { b } from './thrower.mjs';"); + assert!(message(&report).contains("the module './thrower.mjs' has no export named 'b'"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_preprocessor_lines_and_scripts_differ_by_extension() { + let base = folder("kinds"); + write(&base.join("main/lib.jsxinc"), "var included = 1;"); + // A module has no preprocessor lines. + let report = failed(&base, "#include \"lib.jsxinc\"\n"); + assert_eq!(report["kind"], "syntax", "{report}"); + // A .js or .jsx script does not read import or export. + for file in ["main.js", "main.jsx"] { + let (r, s) = run_file(&base, file, "import { a } from './a.mjs';"); + assert!(r.is_err(), "{file}"); + assert_eq!(s.script_report().unwrap()["kind"], "syntax", "{file}"); + } + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_files_count_against_the_include_limits() { + let base = folder("limits"); + for i in 0..70 { + write(&base.join(format!("main/m{i}.mjs")), &format!("import './m{}.mjs';", i + 1)); + } + let report = failed(&base, "import './m0.mjs';"); + assert!(message(&report).contains("limit"), "{report}"); + assert_eq!(report["log"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_paths_of_one_file_give_one_module() { + let base = folder("same"); + write(&base.join("main/once.mjs"), "vc.log('ran');\nexport var v = 1;"); + let mut text = "import { v } from './once.mjs';\nimport { v as w } from './sub/../once.mjs';\n".to_string(); + // Windows file names ignore letter case. + if cfg!(windows) { + text.push_str("import { v as u } from './ONCE.mjs';\n"); + } + let r = run(&base, &text).unwrap(); + assert_eq!(r["log"], json!(["ran"])); + let _ = std::fs::remove_dir_all(base); +} + +/// Makes `link` lead to the folder `target`: a junction on Windows, a symbolic link elsewhere. +/// `false` when the system does not allow it here. +fn link_folder(target: &Path, link: &Path) -> bool { + #[cfg(windows)] + { + let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().is_ok_and(|o| o.status.success()); + made && std::fs::canonicalize(link).ok() == std::fs::canonicalize(target).ok() + } + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, link).is_ok() + } + #[cfg(not(any(unix, windows)))] + { + let _ = (target, link); + false + } +} + +#[test] +fn script_module_link_out_of_the_folder_is_refused() { + let base = folder("link"); + write(&base.join("outside/x.mjs"), "export var leaked = 1;"); + if !link_folder(&base.join("outside"), &base.join("main").join("away")) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let report = failed(&base, "import { leaked } from './away/x.mjs';\nvc.log(leaked);"); + assert!(message(&report).contains("script file read refused: ./away/x.mjs"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_is_listed_and_taken_by_path() { + assert!(cmd::scripts::runs("tool.MJS")); + let base = folder("text"); + let root = base.join("Scripts"); + write(&root.join("tool.mjs"), "export var a = 1;"); + let mut s = Session::new(); + s.attach_scripts_dir(root.clone()); + let listed = s.execute("script.listInstalled", &json!({})).unwrap(); + assert_eq!(listed["scripts"], json!([{"path": root.join("tool.mjs").to_string_lossy(), "label": "tool", "folders": []}])); + // A script given as text is not a module, whatever its name. + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "export var a = 1;", "name": "t.mjs"})); + assert!(r.is_err()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/tests/script_corpus.rs b/crates/engine/tests/script_corpus.rs index 870bfbabc2..b4ad5c5a61 100644 --- a/crates/engine/tests/script_corpus.rs +++ b/crates/engine/tests/script_corpus.rs @@ -118,7 +118,7 @@ fn a_script_refused_before_it_runs_has_not_started() { let r = result(&mut session(), &json!({"path": "notes.txt", "maxFuel": FUEL, "answers": []})); assert_eq!(r["started"], false); assert_eq!(r["ok"], false); - assert!(r["message"].as_str().unwrap().contains(".js or .jsx"), "{r}"); + assert!(r["message"].as_str().unwrap().contains(".js, .mjs or .jsx"), "{r}"); } #[test] diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index c015e3fa38..a5d39c0b06 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -471,6 +471,58 @@ pub struct Program { pub(crate) es2015: bool, } +/// The name an import takes from the module it names, or an export from a module it re-exports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ImportName { + /// The export of this name (`default` for a default import). + Name(String), + /// The module's namespace object (`* as ns`). + Namespace, +} + +/// A module a module imports or re-exports from: the specifier as written and where it stands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModuleRequest { + pub specifier: String, + pub span: Span, +} + +/// One name an import declaration binds (ECMA-262 2015 section 15.2.1.16, ImportEntry). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImportEntry { + /// The index of the module in [`ModuleInfo::requests`]. + pub request: usize, + pub import: ImportName, + /// The name bound in the importing module. + pub local: Name, +} + +/// One name a module exports (ExportEntry). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExportEntry { + /// `export_name` is the module's own binding `local` (`*default*` for a default export of an + /// expression or an anonymous function). + Local { export_name: String, local: String, span: Span }, + /// `export_name` is the export `import` of the module `request` (`export { a as b } from`, + /// `export * as ns from`, or an exported import). + Indirect { export_name: String, request: usize, import: ImportName, span: Span }, + /// Every export of the module `request` but `default` (`export * from`). + Star { request: usize, span: Span }, +} + +/// What a module imports and exports, read by [`crate::parse_module`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ModuleInfo { + /// The modules it names, each specifier once, in the order they first appear. + pub requests: Vec, + pub imports: Vec, + pub exports: Vec, +} + +/// The binding name of a default export that has no name of its own (ECMA-262 2015 section +/// 15.2.3.5); no identifier can name it. +pub const DEFAULT_BINDING: &str = "*default*"; + impl Program { /// The line and column (both from 1, the column in UTF-16 code units) of a source offset. pub fn line_column(&self, offset: u32) -> (u32, u32) { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index f2c02bdf4c..b85780cdc5 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -433,7 +433,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some())) + Ok(Value::Bool(interp.own_property(o, &k)?.is_some())) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -452,7 +452,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_property(o, &k)?.is_some_and(|p| p.enumerable()))) + Ok(Value::Bool(interp.own_property(o, &k)?.is_some_and(|p| p.enumerable()))) } // ---- Function ---- diff --git a/crates/js/src/builtins/object.rs b/crates/js/src/builtins/object.rs index af41bb7782..419fbe57c5 100644 --- a/crates/js/src/builtins/object.rs +++ b/crates/js/src/builtins/object.rs @@ -130,7 +130,7 @@ fn get_own_property_descriptor(interp: &mut Interp, _: Value, args: &[Value], _: let o = interp.to_object(&arg(args, 0))?; interp.rooted(&[Value::Object(o)], |interp| { let k = interp.to_key(&arg(args, 1))?; - match interp.get_own_property(o, &k)? { + match interp.own_property(o, &k)? { Some(p) => from_prop(interp, &p), None => Ok(Value::Undefined), } @@ -265,7 +265,7 @@ fn locked(interp: &mut Interp, v: &Value, frozen: bool) -> JsResult { let o = *o; for k in interp.own_keys(o)? { interp.use_fuel()?; - let Some(prop) = interp.get_own_property(o, &k)? else { continue }; + let Some(prop) = interp.own_property(o, &k)? else { continue }; if prop.configurable() || (frozen && matches!(prop, Prop::Data { flags, .. } if flags & WRITABLE != 0)) { return Ok(Value::Bool(false)); } @@ -294,7 +294,7 @@ fn keys(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult, kin c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() }) } +/// Compiles a module's statements ([`crate::parse_module`]): strict code that runs in an +/// environment of its own, as strict eval code does, and returns `undefined`. +pub(crate) fn compile_module(program: &crate::Program, source: &Rc) -> CResult> { + let mut c = FnCompiler::new(&program.ast, source, CodeKind::Eval, true, 0); + c.es2015 = true; + let hoisted = c.hoist(&program.body, &[])?; + let top_scope = c.list_scope(&program.body, false)?; + c.stmts(&program.body)?; + c.emit(Op::Undefined); + c.emit(Op::Return); + let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX); + c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() }) +} + /// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program /// must be that one parenthesized function expression and nothing else. The name `anonymous` is /// not bound inside the function (section 15.3.2.1). diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 0750204403..f158f45a0f 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -246,6 +246,9 @@ pub(crate) enum Class { }, /// A `.( )` filter in progress. XmlFilter(Box), + /// A module namespace object (ECMA-262 2015 section 9.4.6): its own properties are the + /// module's exports, read live from the bindings they name. + ModuleNamespace(Box), } /// What an XML value is. @@ -322,6 +325,8 @@ impl Class { Class::String(_) => "String", Class::RegExp(_) => "RegExp", Class::Date(_) => "Date", + // The value of a namespace object's @@toStringTag (ECMA-262 2015 section 26.3.1). + Class::ModuleNamespace(_) => "Module", } } } @@ -353,17 +358,49 @@ pub(crate) struct Binding { /// A `let` or `const` binding, or a function declared in a block: a `var` that eval code /// declares cannot take its name. pub(crate) lexical: bool, + /// A module's import of another module's binding (ECMA-262 2015 section 8.1.1.5.5, + /// CreateImportBinding): reading it reads the binding of that name in that environment, and + /// writing it is a `TypeError`. `value` is unused. + pub(crate) import: Option<(EnvId, Key)>, } impl Binding { /// An initialized binding. pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self { - Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false } + Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false, import: None } } /// A `let` (or with `constant`, a `const`) binding not yet initialized. pub(crate) fn lexical(constant: bool) -> Self { - Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true } + Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true, import: None } + } + + /// An import of the binding `name` of the environment `env`. + pub(crate) fn import(env: EnvId, name: Key) -> Self { + Self { + value: Value::Undefined, + mutable: false, + deletable: false, + uninitialized: false, + constant: true, + lexical: true, + import: Some((env, name)), + } + } +} + +/// A module namespace object's exports (ECMA-262 2015 section 9.4.6): each exported name, in +/// code unit order, with the environment and name of the binding it reads, or `None` for an export +/// whose value is fixed (another module's namespace object), kept in the object's own property. +#[derive(Clone, Debug, Default)] +pub(crate) struct ModuleExports { + pub(crate) bindings: Vec<(Key, Option<(EnvId, Key)>)>, +} + +impl ModuleExports { + /// The binding the export `name` reads, when it reads one. + pub(crate) fn binding(&self, name: &[u16]) -> Option<&(EnvId, Key)> { + self.bindings.binary_search_by(|(k, _)| (**k).cmp(name)).ok().and_then(|i| self.bindings.get(i)).and_then(|(_, b)| b.as_ref()) } } @@ -674,6 +711,16 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = BOUND_ARG_BYTES * args.len(); } Class::Arguments(map) => work.push(map.env.0), + Class::ModuleNamespace(exports) => { + for (k, b) in &exports.bindings { + strings.add_key(k); + if let Some((env, name)) = b { + work.push(env.0); + strings.add_key(name); + } + } + extra = PROP_BYTES * exports.bindings.len(); + } Class::String(s) => strings.add(s), Class::RegExp(re) => { if strings.seen.insert(Rc::as_ptr(re) as *const () as usize) { @@ -730,6 +777,10 @@ fn trace_env(e: &Env, work: &mut Vec, strings: &mut StringSizes) -> usize { for (k, b) in bindings.iter() { strings.add_key(k); mark_value(&b.value, work, strings); + if let Some((env, name)) = &b.import { + work.push(env.0); + strings.add_key(name); + } } ENV_BYTES + PROP_BYTES * bindings.len() } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index dc0e678e91..ae755f3aa3 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -24,8 +24,8 @@ use crate::ast::BinaryOp; use crate::bytecode::{Code, CodeKind, Op, Source}; use crate::compiler::{CompileFail, compile_program}; use crate::heap::{ - ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, NativeKind, OBJECT_BYTES, OPEN, ObjId, - Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, + ArgMap, Binding, CONFIGURABLE, Class, ENUMERABLE, ENV_BYTES, Env, EnvId, ForIn, Func, HIDDEN, Heap, Key, ModuleExports, NativeKind, OBJECT_BYTES, + OPEN, ObjId, Object, PROP_BYTES, Prop, PropMap, ROPE_BYTES, Roots, WRITABLE, code_bytes, key, string_bytes, }; use crate::string_builtins::flat_charged; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; @@ -184,6 +184,10 @@ pub(crate) struct Frame { completion: Value, /// Returning from this frame returns from the Rust call that pushed it. boundary: bool, + /// The frame runs a module that another module of the same run waits under (ECMA-262 2015 + /// section 15.2.1.16.5): its completion value is dropped when it returns, and an exception + /// that leaves it ends the run at the boundary frame without stopping in the frames between. + chained: bool, } /// Where the exception being thrown was raised: the code and the instruction. @@ -949,7 +953,11 @@ impl Interp { } let Some(frame) = self.frames.pop() else { return Err(Abrupt::Throw(v)) }; self.stack.truncate(frame.base); - if frame.boundary { + if frame.chained { + // The modules under it have not started, so no handler of theirs takes it. + self.abort_to_boundary(); + } + if frame.boundary || frame.chained { self.passing = v.clone(); return Err(Abrupt::Throw(v)); } @@ -983,6 +991,9 @@ impl Interp { if frame.boundary { return Ok(Some(v)); } + if frame.chained { + return Ok(None); + } self.push(v)?; Ok(None) } @@ -1245,6 +1256,15 @@ impl Interp { matches!(self.heap.env(env), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.uninitialized)) } + /// The binding the binding `name` of the declarative environment `env` imports, when it is a + /// module's import. + fn import_of(&self, env: EnvId, name: &[u16]) -> Option<(EnvId, Key)> { + match self.heap.env(env) { + Some(Env::Decl { bindings, .. }) => bindings.get(name).and_then(|b| b.import.clone()), + _ => None, + } + } + fn not_initialized(&mut self, name: &[u16]) -> Abrupt { let ident = String::from_utf16_lossy(name); self.throw(ErrorType::Reference, &format!("{ident} is used before it is initialized")) @@ -1257,6 +1277,14 @@ impl Interp { /// GetValue of a reference whose base was resolved earlier (section 8.7.1). fn get_resolved(&mut self, r: Resolved, name: &Key) -> JsResult<(Value, Value)> { + if let Resolved::Decl(e) = r + && let Some((target, target_name)) = self.import_of(e, name) + { + if self.uninitialized(target, &target_name) { + return Err(self.not_initialized(name)); + } + return Ok((self.binding_value(target, &target_name)?, Value::Undefined)); + } match r { Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)), Resolved::Decl(e) => Ok((self.binding_value(e, name)?, Value::Undefined)), @@ -1276,6 +1304,12 @@ impl Interp { /// PutValue of a reference whose base was resolved earlier (section 8.7.2). fn set_resolved(&mut self, r: Resolved, name: &Key, v: Value) -> JsResult<()> { let strict = self.strict(); + if let Resolved::Decl(e) = r + && self.import_of(e, name).is_some() + { + let ident = String::from_utf16_lossy(name); + return Err(self.type_error(&format!("assignment to the import '{ident}'"))); + } match r { Resolved::Decl(e) if self.uninitialized(e, name) => Err(self.not_initialized(name)), Resolved::Decl(e) if matches!(self.heap.env(e), Some(Env::Decl { bindings, .. }) if bindings.get(name).is_some_and(|b| b.constant)) => { @@ -1464,11 +1498,38 @@ impl Interp { return Ok(Some(Prop::Data { value: self.binding_value(map.env, name)?, flags })); } } + Class::ModuleNamespace(exports) => { + if let Some((env, name)) = exports.binding(k) + && let Some(Prop::Data { flags, .. }) = o.props.get(k) + { + return Ok(Some(Prop::Data { value: self.binding_value(*env, name)?, flags: *flags })); + } + } _ => {} } Ok(o.props.get(k).cloned()) } + /// [[GetOwnProperty]] as a script reaches it (`hasOwnProperty`, `Object.keys` and the like): + /// [`Self::get_own_property`], except that an export of a module namespace object read before + /// its module initialized it is a `ReferenceError` (ECMA-262 2015 section 9.4.6.5). + pub(crate) fn own_property(&mut self, id: ObjId, k: &[u16]) -> JsResult> { + self.check_namespace_export(id, k)?; + self.get_own_property(id, k) + } + + /// A `ReferenceError` when `k` is an export of the module namespace object `id` that its module + /// has not initialized yet. + fn check_namespace_export(&mut self, id: ObjId, k: &[u16]) -> JsResult<()> { + if let Some(Class::ModuleNamespace(exports)) = self.heap.object(id).map(|o| &o.class) + && let Some((env, name)) = exports.binding(k) + && self.uninitialized(*env, name) + { + return Err(self.not_initialized(k)); + } + Ok(()) + } + /// [[GetProperty]]: the property found on the object or its prototype chain. pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { let mut cur = Some(id); @@ -1492,6 +1553,9 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + // A module's export read before the module ran is in its temporal dead zone (ECMA-262 + // 2015 section 9.4.6.8). + self.check_namespace_export(start, k)?; match self.find_property(start, k)? { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), @@ -1600,10 +1664,26 @@ impl Interp { } Ok(true) } + Class::ModuleNamespace(_) => self.define_namespace_export(id, &k, desc, throw), _ => self.define_ordinary(id, k, desc, throw), } } + /// A module namespace object's [[DefineOwnProperty]] (ECMA-262 2020 section 9.4.6.6): only a + /// descriptor that leaves an export as it is (enumerable, writable, not configurable, its + /// current value) succeeds, and it changes nothing. + fn define_namespace_export(&mut self, id: ObjId, k: &[u16], desc: &Desc, throw: bool) -> JsResult { + let Some(Prop::Data { value, .. }) = self.own_property(id, k)? else { + return self.reject_bool(throw, k, "a module namespace object is not extensible"); + }; + let unchanged = desc.configurable != Some(true) + && desc.enumerable != Some(false) + && !desc.is_accessor() + && desc.writable != Some(false) + && desc.value.as_ref().is_none_or(|v| same_value(v, &value)); + if unchanged { Ok(true) } else { self.reject_bool(throw, k, "a module namespace object is read-only") } + } + fn reject_bool(&mut self, throw: bool, k: &[u16], why: &str) -> JsResult { if throw { let key = String::from_utf16_lossy(k); @@ -1768,6 +1848,10 @@ impl Interp { /// [[Put]] (section 8.12.5). pub(crate) fn put(&mut self, id: ObjId, k: Key, v: Value, throw: bool) -> JsResult<()> { + // A module namespace object takes no writes (ECMA-262 2015 section 9.4.6.9). + if matches!(self.object(id)?.class, Class::ModuleNamespace(_)) { + return self.reject(throw, &k, "a module namespace object is read-only"); + } match self.get_own_property(id, &k)? { Some(Prop::Data { flags, .. }) => { if flags & WRITABLE == 0 { @@ -2586,7 +2670,14 @@ impl Interp { // listed or their bytes reserved must not free it. let saved = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); + // Listing a namespace object's exports reads each one (ECMA-262 2015 section 9.4.6.5). let keys = self.enumerable_keys(o).and_then(|keys| { + for k in &keys { + self.check_namespace_export(o, k)?; + } + Ok(keys) + }); + let keys = keys.and_then(|keys| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); @@ -2862,6 +2953,7 @@ impl Interp { construct, completion: Value::Undefined, boundary, + chained: false, }); Ok(()) } @@ -3135,6 +3227,22 @@ impl Interp { }) } + /// Parses and compiles a module's source ([`crate::parse_module`]), counting it against the + /// source limit, with [`Self::source_tag`] as its source's tag. + pub(crate) fn compile_module_source(&mut self, units: &[u16]) -> Result<(Rc, crate::ModuleInfo), CompileError> { + self.source_units = self.source_units.saturating_add(units.len()); + let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len())); + let options = Options { max_source_units: remaining, ..self.options.clone() }; + let (program, info) = crate::parse_module_utf16(units, &options).map_err(CompileError::Syntax)?; + let writes = self.writes_mode(); + let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes }); + let code = crate::compiler::compile_module(&program, &source).map_err(|e| match e { + CompileFail::Syntax(s) => CompileError::Syntax(s), + CompileFail::Internal(m) => CompileError::Internal(m), + })?; + Ok((code, info)) + } + /// Turns a compile failure inside a running script into what it throws. pub(crate) fn compile_error_to_abrupt(&mut self, e: CompileError) -> Abrupt { match e { @@ -3316,10 +3424,96 @@ impl Interp { construct: None, completion: Value::Undefined, boundary, + chained: false, }); Ok(()) } + /// Declaration binding instantiation for a module's code (ECMA-262 2015 section 15.2.1.16.4, + /// ModuleDeclarationInstantiation, its imports aside): a new environment inside the global + /// scope holds its variables and functions, and one inside that its `let` and `const` names, + /// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary + /// roots for the caller to remove. + pub(crate) fn instantiate_module(&mut self, code: &Rc) -> JsResult<(EnvId, EnvId)> { + self.charge_code(code, declaration_bytes(code).saturating_add(ENV_BYTES))?; + let scope = self.global_lex; + let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); + self.temp_envs.push(env); + let lex = self.instantiate_global(code, env, env, true)?; + self.temp_envs.push(lex); + Ok((lex, env)) + } + + /// Adds `binding` (an import) to the module environment `env`, which must not have `name`. + pub(crate) fn add_import(&mut self, env: EnvId, name: Key, binding: Binding) -> JsResult<()> { + self.use_fuel()?; + // The binding's value (a namespace object) stays reachable while room is made. + self.temp_roots.push(binding.value.clone()); + let reserved = self.reserve_heap(binding_bytes(name.len())); + self.temp_roots.pop(); + reserved?; + self.env_insert(env, name, binding) + } + + /// The environment that holds `name` of a module whose code runs in `lex` inside `env`. + pub(crate) fn module_binding(&self, lex: EnvId, env: EnvId, name: &[u16]) -> Option { + [lex, env].into_iter().find(|e| matches!(self.heap.env(*e), Some(Env::Decl { bindings, .. }) if bindings.contains(name))) + } + + /// A module namespace object for the exports `exports`, each `(name, binding)` with the + /// binding it reads or, for `None`, the value `fixed` gives. The names must be in code unit + /// order and distinct. + pub(crate) fn module_namespace(&mut self, exports: Vec<(Key, Option<(EnvId, Key)>)>, fixed: &[(Key, Value)]) -> JsResult { + let bytes = exports.iter().map(|(k, _)| binding_bytes(k.len()).saturating_mul(2)).sum::(); + self.reserve_heap(OBJECT_BYTES.saturating_add(bytes))?; + let mut object = Object::new(Class::ModuleNamespace(Box::default()), None); + object.extensible = false; + for (name, _) in &exports { + self.use_fuel()?; + let value = fixed.iter().find(|(k, _)| k == name).map_or(Value::Undefined, |(_, v)| v.clone()); + object.props.insert(name.clone(), Prop::Data { value, flags: WRITABLE | ENUMERABLE }); + } + object.class = Class::ModuleNamespace(Box::new(ModuleExports { bindings: exports })); + Ok(self.heap.alloc_object(object)) + } + + /// Pushes the frames of a run of modules: `modules` in the order they run, each with its code, + /// the environment it runs in and the outer one. The last is the boundary frame, pushed first; + /// each of the others is pushed above the one that runs after it, so the first to run is on + /// top. + pub(crate) fn push_module_frames(&mut self, modules: &[(Rc, EnvId, EnvId)]) -> JsResult<()> { + for (i, (code, env, var_env)) in modules.iter().enumerate().rev() { + let last = i + 1 == modules.len(); + self.push_code_frame(code.clone(), *env, *var_env, Value::Undefined, last)?; + if let Some(frame) = self.frames.last_mut() { + frame.chained = !last; + } + } + Ok(()) + } + + /// Ends module linking: drops the temporary roots from `mark` on. + pub(crate) fn drop_temp_envs(&mut self, mark: usize) { + self.temp_envs.truncate(mark); + } + + pub(crate) fn temp_envs_mark(&self) -> usize { + self.temp_envs.len() + } + + /// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it. + pub(crate) fn hold(&mut self, v: Value) { + self.temp_roots.push(v); + } + + pub(crate) fn temp_roots_mark(&self) -> usize { + self.temp_roots.len() + } + + pub(crate) fn drop_temp_roots(&mut self, mark: usize) { + self.temp_roots.truncate(mark); + } + /// Declaration binding instantiation for global and eval code (section 10.5). The caller has /// reserved [`declaration_bytes`] of `code`; each declaration takes a unit of fuel. /// diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index f1fa58730f..8f99275192 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -55,8 +55,14 @@ //! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and //! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again //! before each element, strings and `String` objects by code point, and objects with a `length` by -//! index; other values are a `TypeError`. Destructuring, `for … of`, classes, -//! generators and modules stay syntax errors. +//! index; other values are a `TypeError`. Destructuring, `for … of`, classes and generators stay +//! syntax errors, and so do `import` and `export` in a script. +//! +//! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import` +//! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a +//! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module +//! once, after the modules it imports, with each import reading the exporting module's binding. +//! Dynamic `import()` is a syntax error. #![forbid(unsafe_code)] pub mod ast; @@ -71,6 +77,7 @@ mod heap; mod host; mod interp; mod lexer; +mod module; mod number; mod number_builtins; mod parser; @@ -86,13 +93,15 @@ mod xml_builtins; mod xpath; pub use ast::{ - AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program, - Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, + AssignOp, Ast, BinaryOp, CatchClause, DEFAULT_BINDING, ExportEntry, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, + ImportEntry, ImportName, LexKind, LogicalOp, ModuleInfo, ModuleRequest, Name, Program, Property, PropertyKey, PropertyValue, Stmt, StmtId, + SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier, }; pub use builtins::extensions::Localization; pub use error::{SyntaxError, TOO_DEEP, TOO_LONG}; pub use host::{Arg, CallSite, Data, DataLimits, HostError, HostFunction, HostItem, ScriptItem, SiteFunction}; pub use lexer::{Goal, Lexer}; +pub use module::{LoadError, LoadedModule, ModuleLimits, ModuleLoader}; pub use number::to_string as number_to_string; pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, SourceLocator, UNKNOWN_SOURCE}; pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind}; @@ -140,6 +149,34 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result Result<(Program, ModuleInfo), SyntaxError> { + let units = to_utf16(source, options)?; + parse_module_utf16(&units, options) +} + +/// Parses `source`, in UTF-16 code units, as a module ([`parse_module`]). +pub fn parse_module_utf16(source: &[u16], options: &Options) -> Result<(Program, ModuleInfo), SyntaxError> { + check_length(source.len(), options)?; + parser::Parser::new(source, &module_options(options), false)?.parse_module().map(|(program, info, _)| (program, info)) +} + +/// The tokens of `source` as [`tokenize`] gives them, with `source` read as a module +/// ([`parse_module`]). The source must be a valid module. +pub fn tokenize_module(source: &str, options: &Options) -> Result, SyntaxError> { + let units = to_utf16(source, options)?; + check_length(units.len(), options)?; + parser::Parser::new(&units, &module_options(options), true)?.parse_module().map(|(_, _, tokens)| tokens) +} + +/// `options` as a module is read with them. +pub(crate) fn module_options(options: &Options) -> Options { + Options { strict: true, es2015: true, preprocessor_lines: false, ..options.clone() } +} + /// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and /// each `/` read as division or as the start of a regular expression literal as the grammar /// decides. The source must be a valid script. @@ -227,6 +264,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod module_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs new file mode 100644 index 0000000000..b706c280f5 --- /dev/null +++ b/crates/js/src/module.rs @@ -0,0 +1,448 @@ +//! Running modules (ECMA-262 2015 section 15.2.1): loading a module and the modules it imports, +//! linking their imports to the bindings their exports name, and readying them to run, each once, +//! the modules a module imports before it. +//! +//! The host maps each specifier to a module ([`ModuleLoader`], the role of section 15.2.1.17, +//! HostResolveImportedModule): it gives a key that names the module, and its source the first time +//! it gives that key. Every module is parsed and compiled before any runs, and every import is +//! linked before any runs, so a syntax error, a missing or ambiguous export, or a module the host +//! cannot give ends the run before any of its code runs. The run's [`ModuleLimits`] bound how many +//! modules it loads and how deep its imports go; parsing takes fuel for each code unit, and each +//! binding made in linking takes a unit. +//! +//! An import reads the exporting module's binding itself, so it sees each later assignment, and a +//! read before that binding is initialized (a module that imports one that imports it back) is a +//! `ReferenceError`. A module namespace object (`import * as ns`) is not extensible, has no +//! prototype, takes no writes and has the module's export names, in code unit order, as its +//! properties. `export *` passes on every name but `default`; a name two `export *` give from +//! different bindings is left out of a namespace and is a `SyntaxError` to import. + +use std::collections::HashMap; +use std::rc::Rc; + +use crate::ast::{ExportEntry, ImportName, ModuleInfo}; +use crate::bytecode::Code; +use crate::heap::{Binding, EnvId, ObjId, Prop, key}; +use crate::interp::{Abrupt, CompileError, ErrorType, Interp}; +use crate::value::Value; + +/// What the host gives for a module a run imports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LoadedModule { + /// What names the module: two specifiers that give one key import one module, which runs once. + pub key: String, + /// The module's source, given the first time the host gives its key in a run. `None` for a key + /// the host gave before in the same run. + pub source: Option, +} + +/// Why the host cannot give a module, which ends the run before any module runs: the error the +/// `import` raises, with its message. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum LoadError { + /// A specifier the host does not read: a `SyntaxError`. + Syntax(String), + /// A limit of the host's: a `RangeError`. + Range(String), + /// A module that is missing, refused or unreadable: an `Error`. + Other(String), +} + +/// The host's map from a specifier to a module: called with the key of the importing module and +/// the specifier as written. +pub type ModuleLoader<'a> = dyn FnMut(&str, &str) -> Result + 'a; + +/// Bounds on the modules of one run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ModuleLimits { + /// The most modules a run loads, the first included. + pub modules: usize, + /// The most imports from the first module to any other, along the shortest chain. + pub depth: usize, +} + +impl Default for ModuleLimits { + fn default() -> Self { + Self { modules: 64, depth: 16 } + } +} + +/// The most modules a run loads, whatever its limits say: [`resolve_export`] and +/// [`exported_names`] recurse once for each module at most. +const MAX_MODULES: usize = 1024; +/// The most `(module, name)` pairs one export's resolution visits. +const MAX_RESOLVE_STEPS: usize = 1024; + +/// A loaded module. +struct Record { + key: String, + info: ModuleInfo, + code: Rc, + tag: u32, + /// The module each of `info.requests` names, by index. + requested: Vec, + /// The environment its code runs in and the outer one, once instantiated. + envs: Option<(EnvId, EnvId)>, + namespace: Option, +} + +/// Why a module run could not start. +pub(crate) enum LinkFail { + /// A module does not parse; `tag` is its source's. + Syntax { tag: u32, error: crate::SyntaxError }, + /// An exception, raised at `line` and `column` of the module whose source has `tag`. + At { tag: u32, line: u32, column: u32, abrupt: Abrupt }, + /// A limit or an internal error, not at any place. + Run(Abrupt), +} + +/// Where an export resolves to (ResolvedBinding). +#[derive(Clone, PartialEq, Eq)] +enum Resolution { + /// The binding `name` of module `module`. + Binding { module: usize, name: String }, + /// The namespace object of module `module` (`export * as ns from`). + Namespace(usize), +} + +/// An export that two `export *` declarations give from different places. +struct Ambiguous; + +/// The modules of a run, loaded and linked. +struct Graph<'a, 'l> { + interp: &'a mut Interp, + records: Vec, + by_key: HashMap, + load: &'a mut ModuleLoader<'l>, +} + +/// Loads the module `key` with `source` and every module it imports, instantiates and links them, +/// and gives them in the order they run, each with its code, the environment it runs in and the +/// outer one. The first module's source has tag `entry_tag`; each module loaded after it takes +/// the next tag. The environments stay in the interpreter's temporary roots for the caller to +/// remove once their frames are pushed. +pub(crate) fn link( + interp: &mut Interp, + key_name: &str, + source: &str, + entry_tag: u32, + limits: ModuleLimits, + load: &mut ModuleLoader<'_>, +) -> Result, EnvId, EnvId)>, LinkFail> { + let mut graph = Graph { interp, records: Vec::new(), by_key: HashMap::new(), load }; + if limits.modules == 0 { + return Err(graph.fail_at(0, 0, ErrorType::Range, "module limit (0) reached")); + } + graph.add(key_name.to_string(), source, entry_tag)?; + graph.load_imports(limits)?; + graph.instantiate()?; + graph.link_imports()?; + Ok(graph.evaluation_order()) +} + +impl Graph<'_, '_> { + /// Parses and compiles a module's source under `tag`. + fn add(&mut self, key_name: String, source: &str, tag: u32) -> Result { + let interp = &mut *self.interp; + interp.prepare_source(source.len()).map_err(LinkFail::Run)?; + let saved = std::mem::replace(&mut interp.source_tag, tag); + let compiled = interp.encode_source(source).and_then(|units| interp.compile_module_source(&units)); + interp.source_tag = saved; + let (code, info) = match compiled { + Ok(c) => c, + Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }), + Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))), + }; + self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None }); + let index = self.records.len() - 1; + self.by_key.insert(key_name, index); + Ok(index) + } + + /// An exception of type `t` with `message`, at the source offset `offset` of module `m`. + fn fail_at(&mut self, m: usize, offset: u32, t: ErrorType, message: &str) -> LinkFail { + let (tag, (line, column)) = match self.records.get(m) { + Some(r) => (r.tag, r.code.source.lines.line_column(offset)), + None => (crate::realm::UNKNOWN_SOURCE, (0, 0)), + }; + LinkFail::At { tag, line, column, abrupt: self.interp.throw(t, message) } + } + + /// Loads the modules each loaded module imports, breadth first, so a module's depth is the + /// length of the shortest chain of imports to it. + fn load_imports(&mut self, limits: ModuleLimits) -> Result<(), LinkFail> { + let max_modules = limits.modules.min(MAX_MODULES); + let mut depths = vec![0usize]; + let mut i = 0; + while i < self.records.len() { + let requests: Vec<(String, u32)> = self.records[i].info.requests.iter().map(|r| (r.specifier.clone(), r.span.start)).collect(); + let depth = depths.get(i).copied().unwrap_or(0); + for (specifier, offset) in requests { + self.interp.use_fuel().map_err(LinkFail::Run)?; + let referrer = self.records[i].key.clone(); + let loaded = match (self.load)(&referrer, &specifier) { + Ok(loaded) => loaded, + Err(LoadError::Syntax(why)) => return Err(self.fail_at(i, offset, ErrorType::Syntax, &why)), + Err(LoadError::Range(why)) => return Err(self.fail_at(i, offset, ErrorType::Range, &why)), + Err(LoadError::Other(why)) => return Err(self.fail_at(i, offset, ErrorType::Error, &why)), + }; + let target = match (self.by_key.get(&loaded.key), loaded.source) { + (Some(&j), _) => j, + (None, None) => { + let message = format!("the module '{specifier}' was given without its source"); + return Err(self.fail_at(i, offset, ErrorType::Error, &message)); + } + (None, Some(source)) => { + if depth >= limits.depth { + let message = format!("import depth limit ({}) reached at '{specifier}'", limits.depth); + return Err(self.fail_at(i, offset, ErrorType::Range, &message)); + } + if self.records.len() >= max_modules { + let message = format!("module limit ({max_modules}) reached at '{specifier}'"); + return Err(self.fail_at(i, offset, ErrorType::Range, &message)); + } + let tag = crate::realm::next_tag(self.records.last().map_or(0, |r| r.tag)); + self.interp.evaluated = tag; + depths.push(depth + 1); + self.add(loaded.key, &source, tag)? + } + }; + self.records[i].requested.push(target); + } + i += 1; + } + Ok(()) + } + + /// Makes each module's environments, with its variables, functions and `let` and `const` + /// names. + fn instantiate(&mut self) -> Result<(), LinkFail> { + for i in 0..self.records.len() { + let code = self.records[i].code.clone(); + let envs = self.interp.instantiate_module(&code).map_err(LinkFail::Run)?; + self.records[i].envs = Some(envs); + } + Ok(()) + } + + /// The module the request `request` of module `m` names. + fn target(&self, m: usize, request: usize) -> Option { + self.records.get(m).and_then(|r| r.requested.get(request)).copied() + } + + /// The specifier of request `request` of module `m`, as written. + fn specifier(&self, m: usize, request: usize) -> String { + self.records.get(m).and_then(|r| r.info.requests.get(request)).map(|r| r.specifier.clone()).unwrap_or_default() + } + + /// ResolveExport (section 15.2.1.16.3): where the export `name` of module `m` comes from, + /// `None` when the module has no such export (or only through a cycle). + fn resolve_export(&mut self, m: usize, name: &str, seen: &mut Vec<(usize, String)>) -> Result, Ambiguous>, LinkFail> { + if seen.iter().any(|(sm, sn)| *sm == m && sn == name) { + return Ok(Ok(None)); + } + if seen.len() >= MAX_RESOLVE_STEPS { + let message = format!("export resolution limit ({MAX_RESOLVE_STEPS} steps) reached for '{name}'"); + return Err(LinkFail::Run(self.interp.throw(ErrorType::Range, &message))); + } + self.interp.use_fuel().map_err(LinkFail::Run)?; + seen.push((m, name.to_string())); + let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); + for e in &exports { + match e { + ExportEntry::Local { export_name, local, .. } if export_name == name => { + return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))); + } + ExportEntry::Indirect { export_name, request, import, .. } if export_name == name => { + let Some(t) = self.target(m, *request) else { return Ok(Ok(None)) }; + return match import { + ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))), + ImportName::Name(n) => self.resolve_export(t, n, seen), + }; + } + _ => {} + } + } + if name == "default" { + return Ok(Ok(None)); + } + let mut star = None; + for e in &exports { + let ExportEntry::Star { request, .. } = e else { continue }; + let Some(t) = self.target(m, *request) else { continue }; + match self.resolve_export(t, name, seen)? { + Err(Ambiguous) => return Ok(Err(Ambiguous)), + Ok(None) => {} + Ok(Some(r)) => match &star { + None => star = Some(r), + Some(s) if *s == r => {} + Some(_) => return Ok(Err(Ambiguous)), + }, + } + } + Ok(Ok(star)) + } + + /// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its + /// `export *` modules but `default` included, each once. + fn exported_names(&mut self, m: usize, star: bool, visited: &mut Vec, names: &mut Vec) -> Result<(), LinkFail> { + if visited.contains(&m) { + return Ok(()); + } + visited.push(m); + let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); + for e in &exports { + self.interp.use_fuel().map_err(LinkFail::Run)?; + match e { + ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { + if !(star && export_name == "default") && !names.contains(export_name) { + names.push(export_name.clone()); + } + } + ExportEntry::Star { request, .. } => { + if let Some(t) = self.target(m, *request) { + self.exported_names(t, true, visited, names)?; + } + } + } + } + Ok(()) + } + + /// The environment and name of the binding `name` of module `m`. + fn binding_of(&self, m: usize, name: &str) -> Option<(EnvId, crate::heap::Key)> { + let (lex, env) = self.records.get(m)?.envs?; + let k = key(name); + self.interp.module_binding(lex, env, &k).map(|e| (e, k)) + } + + /// GetModuleNamespace (section 15.2.1.18): module `m`'s namespace object, made the first time. + fn namespace(&mut self, m: usize) -> Result { + if let Some(ns) = self.records.get(m).and_then(|r| r.namespace) { + return Ok(ns); + } + let mut names = Vec::new(); + self.exported_names(m, false, &mut Vec::new(), &mut names)?; + let mut resolved = Vec::new(); + for name in names { + if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { + resolved.push((key(&name), r)); + } + } + resolved.sort_by(|(a, _), (b, _)| a.cmp(b)); + let mut exports = Vec::new(); + let mut later = Vec::new(); + for (k, r) in resolved { + match r { + Resolution::Binding { module, name } => match self.binding_of(module, &name) { + Some(b) => exports.push((k, Some(b))), + None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))), + }, + Resolution::Namespace(module) => { + exports.push((k.clone(), None)); + later.push((k, module)); + } + } + } + let ns = self.interp.module_namespace(exports, &[]).map_err(LinkFail::Run)?; + self.interp.hold(Value::Object(ns)); + if let Some(r) = self.records.get_mut(m) { + r.namespace = Some(ns); + } + // A namespace that holds another is made first, so two that hold each other end. + for (k, module) in later { + let inner = self.namespace(module)?; + let flags = crate::heap::WRITABLE | crate::heap::ENUMERABLE; + self.interp.define(ns, k, Prop::Data { value: Value::Object(inner), flags }).map_err(LinkFail::Run)?; + } + Ok(ns) + } + + /// Binds each module's imports (section 15.2.1.16.4, steps 9 and 12), after checking that + /// each re-export resolves. + fn link_imports(&mut self) -> Result<(), LinkFail> { + for m in 0..self.records.len() { + let exports = self.records[m].info.exports.clone(); + for e in &exports { + let ExportEntry::Indirect { export_name, request, span, .. } = e else { continue }; + if self.target(m, *request).is_none() { + continue; + } + match self.resolve_export(m, export_name, &mut Vec::new())? { + Ok(Some(_)) => {} + Ok(None) => { + let message = format!("the module '{}' has no export to give as '{export_name}'", self.specifier(m, *request)); + return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message)); + } + Err(Ambiguous) => { + let message = format!("the export '{export_name}' is ambiguous"); + return Err(self.fail_at(m, span.start, ErrorType::Syntax, &message)); + } + } + } + let imports = self.records[m].info.imports.clone(); + let Some((_, env)) = self.records[m].envs else { return Err(LinkFail::Run(Abrupt::Internal("module not instantiated".into()))) }; + for imp in imports { + let Some(t) = self.target(m, imp.request) else { continue }; + let local = key(&imp.local.name); + let binding = match &imp.import { + ImportName::Namespace => self.namespace_binding(t)?, + ImportName::Name(n) => match self.resolve_export(t, n, &mut Vec::new())? { + Ok(Some(Resolution::Binding { module, name })) => match self.binding_of(module, &name) { + Some((target_env, target_name)) => Binding::import(target_env, target_name), + None => return Err(LinkFail::Run(Abrupt::Internal(format!("module binding '{name}' not found")))), + }, + Ok(Some(Resolution::Namespace(module))) => self.namespace_binding(module)?, + Ok(None) => { + let message = format!("the module '{}' has no export named '{n}'", self.specifier(m, imp.request)); + return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message)); + } + Err(Ambiguous) => { + let message = format!("the export '{n}' of the module '{}' is ambiguous", self.specifier(m, imp.request)); + return Err(self.fail_at(m, imp.local.span.start, ErrorType::Syntax, &message)); + } + }, + }; + self.interp.add_import(env, local, binding).map_err(LinkFail::Run)?; + } + } + Ok(()) + } + + /// An immutable binding of module `m`'s namespace object. + fn namespace_binding(&mut self, m: usize) -> Result { + let ns = self.namespace(m)?; + Ok(Binding { constant: true, lexical: true, ..Binding::new(Value::Object(ns), false, false) }) + } + + /// The modules in the order they run (section 15.2.1.16.5, ModuleEvaluation): each module + /// after the modules it imports, in the order it imports them, and each once; a module an + /// import cycle reaches again while it waits is not waited for. + fn evaluation_order(&self) -> Vec<(Rc, EnvId, EnvId)> { + let mut state = vec![0u8; self.records.len()]; + let mut order = Vec::new(); + let mut stack = vec![(0usize, 0usize)]; + if let Some(s) = state.first_mut() { + *s = 1; + } + while let Some(top) = stack.last_mut() { + let m = top.0; + let requested = self.records.get(m).map_or(&[][..], |r| r.requested.as_slice()); + if let Some(&t) = requested.get(top.1) { + top.1 += 1; + if let Some(s @ 0) = state.get_mut(t) { + *s = 1; + stack.push((t, 0)); + } + continue; + } + stack.pop(); + if let Some(r) = self.records.get(m) + && let Some((lex, env)) = r.envs + { + order.push((r.code.clone(), lex, env)); + } + } + order + } +} diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs new file mode 100644 index 0000000000..26f453b652 --- /dev/null +++ b/crates/js/src/module_tests.rs @@ -0,0 +1,419 @@ +use std::collections::{HashMap, HashSet}; + +use crate::{ + JsValue, LimitKind, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Realm, RunError, RunErrorKind, parse, parse_module, +}; + +fn es() -> Realm { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits::default()); + // Modules declare no globals, so they report through this array. + assert!(realm.run("var out = [];").is_ok()); + realm +} + +/// A loader over `files`: each specifier is its own key, given with its source the first time. +fn loader(files: &[(&str, &str)]) -> impl FnMut(&str, &str) -> Result + use<> { + let map: HashMap = files.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let mut given = HashSet::new(); + move |_, specifier| { + if !specifier.starts_with('.') && specifier != "main" { + return Err(LoadError::Syntax(format!("bare specifier: {specifier}"))); + } + let source = map.get(specifier).ok_or_else(|| LoadError::Other(format!("module not found: {specifier}")))?; + let first = given.insert(specifier.to_string()); + Ok(LoadedModule { key: specifier.to_string(), source: first.then(|| source.clone()) }) + } +} + +/// Runs `entry` with the modules `files`. → the result and `out` joined with `|`. +fn run_with(realm: &mut Realm, entry: &str, files: &[(&str, &str)], limits: ModuleLimits) -> (Result, String) { + let mut load = loader(files); + let result = realm.run_module("main.mjs", entry, limits, &mut load); + let out = match realm.run("out.join('|')") { + Ok(JsValue::String(s)) => s, + other => panic!("{other:?}"), + }; + (result, out) +} + +fn run(entry: &str, files: &[(&str, &str)]) -> String { + match run_with(&mut es(), entry, files, ModuleLimits::default()) { + (Ok(v), out) => { + assert_eq!(v, JsValue::Undefined); + out + } + (Err(e), _) => panic!("{entry}\n{e:?}"), + } +} + +/// The run ends with an error whose message starts with `start`, and `out` holds `ran`. +fn fails(entry: &str, files: &[(&str, &str)], start: &str, ran: &str) -> RunError { + match run_with(&mut es(), entry, files, ModuleLimits::default()) { + (Err(e), out) => { + assert!(e.message.starts_with(start), "{entry}: {e:?}"); + assert_eq!(out, ran, "{entry}"); + e + } + (Ok(_), out) => panic!("{entry}: completed with {out}"), + } +} + +fn syntax(src: &str) { + assert!(parse_module(src, &Options::default()).is_err(), "{src}"); +} + +#[test] +fn an_import_reads_the_exporting_binding_each_time() { + let counter = "export let count = 0; export function inc() { count++; }"; + let out = run("import { count, inc } from './c.mjs'; out.push(count); inc(); inc(); out.push(count);", &[("./c.mjs", counter)]); + assert_eq!(out, "0|2"); +} + +#[test] +fn imports_can_be_renamed_and_combined() { + let m = "export default 'd'; export var a = 1; export const b = 2;"; + let out = run("import d, { a as x, b } from './m.mjs'; out.push(d, x, b);", &[("./m.mjs", m)]); + assert_eq!(out, "d|1|2"); + let out = run("import d, * as ns from './m.mjs'; out.push(d, ns.a, ns['default']);", &[("./m.mjs", m)]); + assert_eq!(out, "d|1|d"); +} + +#[test] +fn default_exports_of_expressions_and_functions() { + let out = run("import v from './v.mjs'; out.push(v * 2);", &[("./v.mjs", "export default 20 + 1;")]); + assert_eq!(out, "42"); + let out = run("import f from './f.mjs'; out.push(f());", &[("./f.mjs", "export default function () { return 'anon'; }")]); + assert_eq!(out, "anon"); + // A named default function is a declaration: hoisted, and its name is bound in the module. + let f = "out.push(typeof g); export default function g() { return 'g'; }"; + let out = run("import h from './f.mjs'; out.push(h());", &[("./f.mjs", f)]); + assert_eq!(out, "function|g"); +} + +#[test] +fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() { + let m = "export var zeta = 1; export let alpha = 2; export function mid() {} export default 3;"; + let out = run( + "import * as ns from './m.mjs'; + out.push(Object.keys(ns).join(','), Object.prototype.toString.call(ns), Object.isExtensible(ns), Object.getPrototypeOf(ns) === null); + try { ns.alpha = 5; } catch (e) { out.push(e.name); } + try { ns.added = 5; } catch (e) { out.push(e.name); } + try { delete ns.alpha; } catch (e) { out.push(e.name); } + out.push(ns.alpha, Object.getOwnPropertyDescriptor(ns, 'zeta').writable);", + &[("./m.mjs", m)], + ); + assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true"); +} + +#[test] +fn a_namespace_takes_only_definitions_that_change_nothing() { + let m = "export var a = 1;"; + let out = run( + "import * as ns from './m.mjs'; + out.push(Object.seal(ns) === ns, Object.isSealed(ns), Object.isFrozen(ns)); + out.push(Object.defineProperty(ns, 'a', { value: 1, writable: true, enumerable: true, configurable: false }) === ns); + var ds = [{ value: 2 }, { writable: false }, { enumerable: false }, { configurable: true }, { get: function () {} }]; + for (var i = 0; i < ds.length; i++) { + try { Object.defineProperty(ns, 'a', ds[i]); out.push('defined'); } catch (e) { out.push(e.name); } + } + try { Object.defineProperty(ns, 'b', { value: 1 }); } catch (e) { out.push(e.name); } + try { Object.freeze(ns); } catch (e) { out.push(e.name); } + out.push(ns.a);", + &[("./m.mjs", m)], + ); + assert_eq!(out, "true|true|false|true|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|1"); +} + +#[test] +fn a_namespace_reads_live_values() { + let m = "export var n = 1; export function bump() { n = n + 1; }"; + let out = run("import * as ns from './m.mjs'; ns.bump(); out.push(ns.n);", &[("./m.mjs", m)]); + assert_eq!(out, "2"); +} + +#[test] +fn assigning_to_an_import_is_a_type_error() { + let m = "export var a = 1;"; + let out = run("import { a } from './m.mjs'; try { a = 2; } catch (e) { out.push(e.name); } out.push(a);", &[("./m.mjs", m)]); + assert_eq!(out, "TypeError|1"); + let out = run("import * as ns from './m.mjs'; try { ns = 2; } catch (e) { out.push(e.name); }", &[("./m.mjs", m)]); + assert_eq!(out, "TypeError"); +} + +#[test] +fn a_cycle_of_two_modules_runs_each_once_dependency_first() { + // main imports b, b imports main back: b runs first and sees main's hoisted function. + let b = "import { fa } from 'main'; out.push('b ' + fa()); export const b = 'B';"; + let mut realm = es(); + let mut load = loader(&[("./b.mjs", b), ("main", "")]); + let mut load = |referrer: &str, specifier: &str| { + if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { load(referrer, specifier) } + }; + let entry = "import { b } from './b.mjs'; export function fa() { return 'fa'; } out.push('a ' + b);"; + let r = realm.run_module("main.mjs", entry, ModuleLimits::default(), &mut load); + assert_eq!(r, Ok(JsValue::Undefined)); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b fa|a B".into()))); +} + +#[test] +fn reading_an_import_before_its_module_ran_is_a_reference_error() { + let b = "import { a } from 'main'; out.push('b'); out.push(a);"; + let mut realm = es(); + let mut inner = loader(&[("./b.mjs", b)]); + let mut load = |referrer: &str, specifier: &str| { + if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) } + }; + let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load); + match r { + Err(e) => assert!(e.message.starts_with("ReferenceError"), "{e:?}"), + other => panic!("{other:?}"), + } + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("b".into()))); +} + +#[test] +fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { + let b = "import * as ns from 'main'; + var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'), + () => Object.getOwnPropertyDescriptor(ns, 'a'), () => { for (var k in ns) {} }, () => Object.isSealed(ns), () => Object.isFrozen(ns), + () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns)]; + tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } }); + out.push('a' in ns, Object.getOwnPropertyNames(ns).join());"; + let mut realm = es(); + let mut inner = loader(&[("./b.mjs", b)]); + let mut load = |referrer: &str, specifier: &str| { + if specifier == "main" { Ok(LoadedModule { key: "main.mjs".into(), source: None }) } else { inner(referrer, specifier) } + }; + let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load); + assert_eq!(r, Ok(JsValue::Undefined)); + let errors = "ReferenceError|".repeat(12); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}true|a")))); +} + +#[test] +fn a_module_two_modules_import_runs_once() { + let shared = "out.push('shared'); export var s = 1;"; + let a = "import { s } from './shared.mjs'; out.push('a' + s);"; + let b = "import { s } from './shared.mjs'; out.push('b' + s);"; + let out = run("import './a.mjs'; import './b.mjs'; out.push('main');", &[("./shared.mjs", shared), ("./a.mjs", a), ("./b.mjs", b)]); + assert_eq!(out, "shared|a1|b1|main"); +} + +#[test] +fn re_exports_pass_names_on() { + let base = "export var x = 1, y = 2; export default 'base';"; + let mid = "export { x as renamed } from './base.mjs'; export * from './base.mjs'; export * as all from './base.mjs';"; + let out = run( + "import { renamed, x, y, all } from './mid.mjs'; import * as m from './mid.mjs'; out.push(renamed, x, y, all['default'], Object.keys(m).join(','));", + &[("./base.mjs", base), ("./mid.mjs", mid)], + ); + // `export *` does not pass `default` on. + assert_eq!(out, "1|1|2|base|all,renamed,x,y"); +} + +#[test] +fn an_exported_import_is_a_re_export() { + let base = "export var v = 'v';"; + let mid = "import { v } from './base.mjs'; import * as ns from './base.mjs'; export { v as w, ns };"; + let out = run("import { w, ns } from './mid.mjs'; out.push(w, ns.v);", &[("./base.mjs", base), ("./mid.mjs", mid)]); + assert_eq!(out, "v|v"); +} + +#[test] +fn a_name_two_stars_give_is_ambiguous() { + let files = + [("./a.mjs", "export var n = 1;"), ("./b.mjs", "export var n = 2;"), ("./both.mjs", "export * from './a.mjs'; export * from './b.mjs';")]; + fails("import { n } from './both.mjs'; out.push('ran');", &files, "SyntaxError: the export 'n'", ""); + // The namespace leaves the name out. + let out = run("import * as ns from './both.mjs'; out.push(Object.keys(ns).length);", &files); + assert_eq!(out, "0"); +} + +#[test] +fn a_missing_export_ends_the_run_before_any_module_runs() { + let files = [("./m.mjs", "out.push('m'); export var a = 1;")]; + let e = fails("import { nope } from './m.mjs';\nout.push('main');", &files, "SyntaxError: the module './m.mjs' has no export named 'nope'", ""); + assert_eq!((e.line, e.column), (1, 10)); + let files = [("./m.mjs", "export { nothing as gone } from './n.mjs';"), ("./n.mjs", "")]; + fails("import './m.mjs';", &files, "SyntaxError: the module './n.mjs' has no export to give as 'gone'", ""); +} + +#[test] +fn a_module_the_loader_cannot_give_is_named_in_the_error() { + let e = fails("out.push(1);\nimport { a } from './missing.mjs';", &[], "Error: module not found: ./missing.mjs", ""); + assert_eq!(e.line, 2); + fails("import x from 'lib';", &[], "SyntaxError: bare specifier: lib", ""); +} + +#[test] +fn a_syntax_error_in_an_imported_module_names_its_source() { + let mut realm = es(); + let mut load = loader(&[("./a.mjs", "out.push('a');"), ("./bad.mjs", "\nvar = ;")]); + let r = realm.run_module("main.mjs", "import './a.mjs'; import './bad.mjs';", ModuleLimits::default(), &mut load); + let e = r.err().unwrap_or_else(|| panic!("ran")); + assert_eq!((e.kind, e.line), (RunErrorKind::Syntax, 2)); + // The entry is source 0, then each module in the order it was loaded. + assert_eq!(realm.error_source(), 2); + assert_eq!(realm.run("out.length"), Ok(JsValue::Number(0.0))); +} + +#[test] +fn module_code_is_strict_and_its_this_is_undefined() { + let out = run("out.push(this === undefined, (() => this)() === undefined); try { undeclared = 1; } catch (e) { out.push(e.name); }", &[]); + assert_eq!(out, "true|true|ReferenceError"); + // Its declarations stay in the module. + let mut realm = es(); + let (r, _) = run_with(&mut realm, "var hidden = 1; function also() {}", &[], ModuleLimits::default()); + assert_eq!(r, Ok(JsValue::Undefined)); + assert_eq!(realm.run("typeof hidden + typeof also"), Ok(JsValue::String("undefinedundefined".into()))); +} + +#[test] +fn an_exception_in_a_module_ends_the_run_and_the_modules_after_it_do_not_run() { + let files = [("./a.mjs", "out.push('a'); throw new TypeError('stop');"), ("./b.mjs", "try { out.push('b'); } catch (e) { out.push('caught'); }")]; + fails("import './a.mjs'; import './b.mjs'; try { out.push('main'); } catch (e) {}", &files, "TypeError: stop", "a"); +} + +#[test] +fn the_module_count_and_import_depth_are_limited() { + let files = [("./a.mjs", "import './b.mjs';"), ("./b.mjs", "import './c.mjs';"), ("./c.mjs", "out.push('c');")]; + let mut realm = es(); + let (r, out) = run_with(&mut realm, "import './a.mjs';", &files, ModuleLimits { modules: 3, depth: 16 }); + assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (3) reached at './c.mjs'")), "{r:?}"); + assert_eq!(out, ""); + let (r, _) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 }); + assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: import depth limit (2) reached at './c.mjs'")), "{r:?}"); + let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 4, depth: 3 }); + assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "c")); +} + +#[test] +fn a_module_at_the_depth_limit_may_import_a_module_already_loaded() { + let files = [("./a.mjs", "import './b.mjs'; out.push('a');"), ("./b.mjs", "import './a.mjs'; out.push('b');")]; + let (r, out) = run_with(&mut es(), "import './a.mjs';", &files, ModuleLimits { modules: 64, depth: 2 }); + assert_eq!((r, out.as_str()), (Ok(JsValue::Undefined), "b|a")); +} + +#[test] +fn a_module_limit_of_zero_runs_no_module() { + let (r, out) = run_with(&mut es(), "out.push('main');", &[], ModuleLimits { modules: 0, depth: 16 }); + assert!(r.as_ref().is_err_and(|e| e.message.starts_with("RangeError: module limit (0) reached")), "{r:?}"); + assert_eq!(out, ""); +} + +#[test] +fn a_module_run_is_held_to_the_fuel_limit() { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { fuel: 50, ..Limits::default() }); + let mut load = loader(&[("./m.mjs", &"var a = 1;\n".repeat(20))]); + let r = realm.run_module("main.mjs", "import './m.mjs';", ModuleLimits::default(), &mut load); + assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Limit(LimitKind::Fuel))); +} + +#[test] +fn a_module_run_advances_in_slices_and_runs_each_module_in_turn() { + let mut realm = es(); + let mut load = loader(&[("./a.mjs", "for (var i = 0; i < 200; i++) {} out.push('a');")]); + let entry = "import './a.mjs'; for (var j = 0; j < 200; j++) {} out.push('main');"; + assert_eq!(realm.start_module("main.mjs", entry, ModuleLimits::default(), &mut load), Ok(())); + let mut slices = 0; + loop { + match realm.advance(10) { + Ok(Progress::Paused) => slices += 1, + Ok(Progress::Done(v)) => { + assert_eq!(v, JsValue::Undefined); + break; + } + Err(e) => panic!("{e:?}"), + } + } + assert!(slices > 20, "{slices}"); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("a|main".into()))); +} + +#[test] +fn an_es5_realm_runs_no_module() { + let mut realm = Realm::new(); + let mut load = loader(&[]); + let r = realm.run_module("main.mjs", "export var a = 1;", ModuleLimits::default(), &mut load); + assert_eq!(r.map_err(|e| e.kind), Err(RunErrorKind::Syntax)); +} + +#[test] +fn a_script_does_not_read_import_or_export() { + for src in ["import a from './a.mjs';", "export var a = 1;", "import './a.mjs';"] { + assert!(parse(src, &Options { es2015: true, ..Options::default() }).is_err(), "{src}"); + assert!(es().run(src).is_err_and(|e| e.kind == RunErrorKind::Syntax), "{src}"); + } +} + +#[test] +fn module_early_errors() { + for src in [ + "export var a; export { a };", + "export { undeclared };", + "export default 1; export default 2;", + "import { a } from './x.mjs'; var a;", + "var a; import a from './x.mjs';", + "import { a, a } from './x.mjs';", + "function f() { import a from './x.mjs'; }", + "{ export var a; }", + "import { default } from './x.mjs';", + "export { default };", + "import a from x;", + "import * from './x.mjs';", + "with (a) {}", + "export default class {}", + "import('./x.mjs');", + "#include 'x.js'\n", + // Top-level functions are lexical declarations in a module. + "function f() {} function f() {}", + "var f; function f() {}", + "function f() {} var f;", + "let f; function f() {}", + ] { + syntax(src); + } + for src in [ + "import { default as d, if as i } from './x.mjs'; export { d as default, i as if };", + "import {} from './x.mjs'; export {};", + "export function f() {} export { f as g };", + "var as = 1, from = 2; export { as, from };", + "export * as default from './x.mjs';", + "function f() {} { function f() {} } function g() { var g; function h() {} var h; }", + ] { + assert!(parse_module(src, &Options::default()).is_ok(), "{src}"); + } +} + +#[test] +fn a_module_lists_what_it_imports_and_exports() { + let (_, info) = + match parse_module("import a, { b as c } from './x.mjs'; export { c as d }; export * from './y.mjs'; import './x.mjs';", &Options::default()) + { + Ok(p) => p, + Err(e) => panic!("{e:?}"), + }; + let specifiers: Vec<&str> = info.requests.iter().map(|r| r.specifier.as_str()).collect(); + assert_eq!(specifiers, ["./x.mjs", "./y.mjs"]); + assert_eq!(info.imports.len(), 2); + assert!( + matches!(&info.exports[..], [crate::ExportEntry::Star { request: 1, .. }, crate::ExportEntry::Indirect { export_name, request: 0, .. }] if export_name == "d") + ); +} + +#[test] +fn modules_survive_a_collection_while_they_link() { + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() }); + assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok()); + let m = "export var v = 'kept'; export function f() { return v; }"; + let mut load = loader(&[("./m.mjs", m)]); + let r = realm.run_module( + "main.mjs", + "import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());", + ModuleLimits::default(), + &mut load, + ); + assert_eq!(r, Ok(JsValue::Undefined)); + realm.collect_garbage(); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into()))); +} diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index edc6b22c9a..28b7cd5f72 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -7,6 +7,7 @@ //! stack, and prefix operators, assignment chains, `else if` chains and labels with loops, so long //! runs of them do not nest at all. +mod module; mod xml; use std::collections::{HashMap, HashSet}; @@ -101,6 +102,9 @@ pub(crate) struct Parser<'s> { es2015: bool, /// The scopes open around the current token, outermost first (only with `es2015`). scopes: Vec, + /// Read a module ([`Parser::parse_module`]): its top-level function declarations are lexical + /// declarations (ECMA-262 2015 section 15.2.1.11). + module: bool, } impl<'s> Parser<'s> { @@ -125,6 +129,7 @@ impl<'s> Parser<'s> { e4x: options.e4x, es2015: options.es2015, scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() }, + module: false, }; parser.tok = parser.next_significant()?; Ok(parser) @@ -342,6 +347,9 @@ impl<'s> Parser<'s> { /// body or the script, lexical in a block. fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> { let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) }; + if self.module && self.scopes.len() == 1 { + return self.declare_lexical(&name, true); + } match self.scopes.last_mut() { Some(scope) if scope.function => { if scope.lexical.contains_key(&name.name) { diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs new file mode 100644 index 0000000000..ec39092afb --- /dev/null +++ b/crates/js/src/parser/module.rs @@ -0,0 +1,299 @@ +//! Module code (ECMA-262 2015 section 15.2): the import and export declarations at the top of a +//! module, read into a [`ModuleInfo`], and their early errors (section 15.2.1.1). +//! +//! A module is strict mode code throughout. An import binds its names as lexical declarations at +//! the top of the module, so a `var`, `let`, `const`, function or another import of the same name +//! is a redeclaration. An exported declaration is kept as the declaration; `export default` of an +//! expression or an anonymous function binds [`DEFAULT_BINDING`]. Each exported name may be +//! exported once, and a name an `export { … }` list exports from the module itself must be one it +//! declares or imports. + +use std::collections::HashSet; + +use super::{Parser, Result, describe}; +use crate::ast::{ + DEFAULT_BINDING, ExportEntry, FunctionKind, ImportEntry, ImportName, LexKind, ModuleInfo, ModuleRequest, Name, Program, Stmt, StmtId, VarDecl, +}; +use crate::token::{Keyword, Punct, Span, Token, TokenKind}; + +/// A name an `export { … }` list without `from` exports: the module's own binding (or import) +/// `local`, exported as `export_name`. +struct ClauseExport { + export_name: String, + local: String, + span: Span, +} + +impl Parser<'_> { + /// Reads the source as a module: its statements, without its import and export declarations + /// but with the declarations they export, and what it imports and exports. + pub(crate) fn parse_module(mut self) -> Result<(Program, ModuleInfo, Vec)> { + self.module = true; + let mut info = ModuleInfo::default(); + let mut clause = Vec::new(); + let mut body = Vec::new(); + while self.tok.kind != TokenKind::Eof { + if self.at_keyword(Keyword::Import) { + self.import_declaration(&mut info)?; + } else if self.at_keyword(Keyword::Export) { + if let Some(stmt) = self.export_declaration(&mut info, &mut clause)? { + body.push(stmt); + } + } else { + body.push(self.parse_statement_item()?); + } + } + self.finish_exports(&mut info, clause)?; + if let Some(tokens) = &mut self.tokens { + tokens.push(self.tok.clone()); + } + let program = Program { ast: self.ast, body, strict: true, directives: self.directives, lines: self.lines, es2015: self.es2015 }; + Ok((program, info, self.tokens.unwrap_or_default())) + } + + /// The current token is the contextual keyword `word` (`as` or `from`), written without escapes. + fn at_contextual(&self, word: &str) -> bool { + self.tok.ident() == Some(word) && !self.tok.escaped + } + + fn expect_contextual(&mut self, word: &str) -> Result<()> { + if self.at_contextual(word) { + self.bump()?; + return Ok(()); + } + Err(self.error_at_token(&self.tok, format!("expected '{word}' but found {}", describe(&self.tok)))) + } + + /// A module specifier: a string literal, added to the module's requests once. → its index. + fn module_specifier(&mut self, info: &mut ModuleInfo) -> Result { + let TokenKind::String(units) = &self.tok.kind else { + return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok)))); + }; + let Ok(specifier) = String::from_utf16(units) else { + return Err(self.error_at_token(&self.tok, "a module specifier must be valid text")); + }; + let span = self.bump()?.span; + if let Some(i) = info.requests.iter().position(|r| r.specifier == specifier) { + return Ok(i); + } + info.requests.push(ModuleRequest { specifier, span }); + Ok(info.requests.len() - 1) + } + + /// A name as an import or export list gives it: any identifier name, keywords included. → the + /// name and whether it was an identifier (not a keyword). + fn list_name(&mut self) -> Result<(Name, bool)> { + let Some(name) = self.tok.identifier_name().map(str::to_string) else { + return Err(self.error_at_token(&self.tok, format!("expected a name but found {}", describe(&self.tok)))); + }; + let ident = matches!(self.tok.kind, TokenKind::Ident(_)); + let token = self.bump()?; + Ok((Name { name, span: token.span }, ident)) + } + + /// `import …;` (section 15.2.2). Each name it binds is declared in the module's scope. + fn import_declaration(&mut self, info: &mut ModuleInfo) -> Result<()> { + let import = self.bump()?; + if self.at(Punct::LParen) { + return Err(self.error_at_token(&import, "import() is not supported")); + } + if matches!(self.tok.kind, TokenKind::String(_)) { + self.module_specifier(info)?; + return self.semicolon(); + } + let mut bound: Vec<(ImportName, Name)> = Vec::new(); + let mut list = true; + if matches!(self.tok.kind, TokenKind::Ident(_)) { + let local = self.binding_identifier()?; + bound.push((ImportName::Name("default".into()), local)); + list = self.eat(Punct::Comma)?; + } + if list { + if self.eat(Punct::Star)? { + self.expect_contextual("as")?; + let local = self.binding_identifier()?; + bound.push((ImportName::Namespace, local)); + } else { + self.expect(Punct::LBrace)?; + while !self.at(Punct::RBrace) { + if matches!(self.tok.kind, TokenKind::Ident(_)) && !self.next_is_as() { + // A name without `as` binds itself, so it must be one a declaration may bind. + let local = self.binding_identifier()?; + bound.push((ImportName::Name(local.name.clone()), local)); + } else { + let (imported, _) = self.list_name()?; + self.expect_contextual("as")?; + let local = self.binding_identifier()?; + bound.push((ImportName::Name(imported.name), local)); + } + if !self.eat(Punct::Comma)? { + break; + } + } + self.expect(Punct::RBrace)?; + } + } + self.expect_contextual("from")?; + let request = self.module_specifier(info)?; + self.semicolon()?; + for (import, local) in bound { + self.declare_lexical(&local, false)?; + info.imports.push(ImportEntry { request, import, local }); + } + Ok(()) + } + + /// The token after the current one is the contextual keyword `as`. + fn next_is_as(&self) -> bool { + self.peek().is_some_and(|t| !t.escaped && t.ident() == Some("as")) + } + + /// `export …` (section 15.2.3). → the declaration it exports, which runs in place. + fn export_declaration(&mut self, info: &mut ModuleInfo, clause: &mut Vec) -> Result> { + let export = self.bump()?; + let span = export.span; + if self.eat(Punct::Star)? { + if self.at_contextual("as") { + self.bump()?; + let (name, _) = self.list_name()?; + self.expect_contextual("from")?; + let request = self.module_specifier(info)?; + self.semicolon()?; + info.exports.push(ExportEntry::Indirect { export_name: name.name, request, import: ImportName::Namespace, span: name.span }); + return Ok(None); + } + self.expect_contextual("from")?; + let request = self.module_specifier(info)?; + self.semicolon()?; + info.exports.push(ExportEntry::Star { request, span }); + return Ok(None); + } + if self.at(Punct::LBrace) { + self.bump()?; + // Each name: the name it refers to (and whether that was an identifier) and the name it + // is exported as. + let mut names: Vec<(Name, bool, Name)> = Vec::new(); + while !self.at(Punct::RBrace) { + let (local, ident) = self.list_name()?; + let exported = if self.at_contextual("as") { + self.bump()?; + self.list_name()?.0 + } else { + local.clone() + }; + names.push((local, ident, exported)); + if !self.eat(Punct::Comma)? { + break; + } + } + self.expect(Punct::RBrace)?; + if self.at_contextual("from") { + self.bump()?; + let request = self.module_specifier(info)?; + self.semicolon()?; + for (local, _, exported) in names { + let import = ImportName::Name(local.name); + info.exports.push(ExportEntry::Indirect { export_name: exported.name, request, import, span: exported.span }); + } + return Ok(None); + } + self.semicolon()?; + for (local, ident, exported) in names { + // Without `from`, each name refers to a binding of the module (section 15.2.3.1). + if !ident || crate::token::strict_reserved(&local.name) { + return Err(self.error_at_offset(local.span.start, format!("'{}' cannot be exported as a binding", local.name))); + } + clause.push(ClauseExport { export_name: exported.name, local: local.name, span: local.span }); + } + return Ok(None); + } + if self.at_keyword(Keyword::Default) { + self.bump()?; + return self.export_default(info, span).map(Some); + } + let exportable = self.at_keyword(Keyword::Var) || self.at_keyword(Keyword::Function) || self.at_lexical_declaration().is_some(); + if !exportable { + return Err(self.error_at_token(&self.tok, format!("expected a declaration after 'export' but found {}", describe(&self.tok)))); + } + let stmt = self.parse_statement_item()?; + let names: Vec = match self.ast.stmt(stmt) { + Some(Stmt::Var(decls) | Stmt::Lexical(_, decls)) => decls.iter().map(|d| d.name.clone()).collect(), + Some(Stmt::FunctionDecl(fid)) => self.ast.function(*fid).and_then(|f| f.name.clone()).into_iter().collect(), + _ => return Err(self.error_at_offset(span.start, "expected a declaration after 'export'")), + }; + for name in names { + info.exports.push(ExportEntry::Local { export_name: name.name.clone(), local: name.name, span: name.span }); + } + Ok(Some(stmt)) + } + + /// `export default …` after `default`: a function declaration (named or not) or an expression. + fn export_default(&mut self, info: &mut ModuleInfo, span: Span) -> Result { + if self.at_keyword(Keyword::Class) { + return Err(self.error_at_token(&self.tok, "classes are not supported")); + } + if self.at_keyword(Keyword::Function) { + self.enter()?; + let result = self.default_function(); + self.leave(); + let (stmt, fid, local) = result?; + self.declare_function(fid)?; + info.exports.push(ExportEntry::Local { export_name: "default".into(), local, span }); + return Ok(stmt); + } + let start = self.tok.span; + let value = self.parse_assignment(false)?; + self.semicolon()?; + let name = Name { name: DEFAULT_BINDING.into(), span: start }; + let stmt = self.ast.push_stmt(Stmt::Lexical(LexKind::Const, vec![VarDecl { name, init: Some(value) }]), self.span_from(start)); + info.exports.push(ExportEntry::Local { export_name: "default".into(), local: DEFAULT_BINDING.into(), span }); + Ok(stmt) + } + + /// `function name(…) {…}` or `function (…) {…}` after `export default`: a declaration of + /// `name`, or of [`DEFAULT_BINDING`] for a function without one. + fn default_function(&mut self) -> Result<(StmtId, crate::ast::FunctionId, String)> { + let keyword = self.expect_keyword(Keyword::Function)?; + let start = keyword.span; + let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { + self.function_name()? + } else { + (Name { name: DEFAULT_BINDING.into(), span: start }, keyword) + }; + let local = name.0.name.clone(); + let fid = self.parse_function_rest(FunctionKind::Declaration, Some(name), start)?; + let stmt = self.ast.push_stmt(Stmt::FunctionDecl(fid), self.span_from(start)); + Ok((stmt, fid, local)) + } + + /// The early errors of the exports as a whole (section 15.2.1.1): no name exported twice, and + /// each name an `export { … }` list takes from the module itself declared or imported there. An + /// exported import becomes a re-export of what it imports (section 15.2.1.16.1; a namespace + /// import as ECMA-262 2020 reads `export * as ns from`). + fn finish_exports(&self, info: &mut ModuleInfo, clause: Vec) -> Result<()> { + let top = self.scopes.first(); + for c in clause { + let declared = top.is_some_and(|s| s.lexical.contains_key(&c.local) || s.vars.contains(&c.local)); + if !declared { + return Err(self.error_at_offset(c.span.start, format!("'{}' is exported but not declared in the module", c.local))); + } + let imported = info.imports.iter().find(|i| i.local.name == c.local); + let entry = match imported { + Some(i) => ExportEntry::Indirect { export_name: c.export_name, request: i.request, import: i.import.clone(), span: c.span }, + None => ExportEntry::Local { export_name: c.export_name, local: c.local, span: c.span }, + }; + info.exports.push(entry); + } + let mut seen = HashSet::new(); + for e in &info.exports { + let (name, span) = match e { + ExportEntry::Local { export_name, span, .. } | ExportEntry::Indirect { export_name, span, .. } => (export_name, span), + ExportEntry::Star { .. } => continue, + }; + if !seen.insert(name.as_str()) { + return Err(self.error_at_offset(span.start, format!("'{name}' is exported more than once"))); + } + } + Ok(()) + } +} diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 728839949c..1765d6d9d1 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -7,9 +7,14 @@ use std::sync::atomic::{AtomicBool, Ordering}; use crate::bytecode::CodeKind; use crate::heap::{Func, HIDDEN, Object, Prop, key}; use crate::interp::{Abrupt, CompileError, Interp}; +use crate::module::{LinkFail, ModuleLimits, ModuleLoader}; use crate::value::Value; use crate::{Options, SyntaxError}; +fn internal_error(message: &str) -> RunError { + RunError { kind: RunErrorKind::Internal, message: message.to_string(), line: 0, column: 0, authored: false } +} + /// The limits a run is held to. Reaching one ends the run with [`RunErrorKind::Limit`]; scripts /// cannot catch it, and their `finally` blocks do not run. #[derive(Clone, Debug, PartialEq, Eq)] @@ -255,6 +260,75 @@ impl Realm { /// Compiles `source` and readies the realm for a run. fn compile(&mut self, source: &str) -> Result, RunError> { + self.reset_run()?; + let interp = &mut self.interp; + let strict = interp.options.strict; + interp.evaluated = next_tag(interp.evaluated); + self.script_tag = interp.evaluated; + interp.source_tag = self.script_tag; + let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); + interp.source_tag = UNKNOWN_SOURCE; + match code { + Ok(code) => Ok(code), + Err(CompileError::Syntax(e)) => { + interp.error_tag = self.script_tag; + Err(e.into()) + } + Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), + } + } + + /// Begins a run of the module `key` with `source` (ECMA-262 2015 section 15.2), which + /// [`Realm::advance`] carries on as it does a script [`Realm::start`] began. `load` gives each + /// module a module imports ([`ModuleLoader`]). Every module is loaded, parsed and linked before + /// any runs, so a syntax error, an import of a missing or ambiguous export, a module `load` + /// cannot give or a module past `limits` ends the run here, with no code run. The first module + /// has [`Realm::script_tag`] as its source's tag, and each module loaded after it the next tag, + /// in the order `load` first gave their sources, as the sources an evaluator gives during a run + /// take theirs. A realm without [`Options::es2015`] runs no module: that is a syntax error. + pub fn start_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result<(), RunError> { + self.reset_run()?; + if !self.interp.options.es2015 { + let message = "modules need ECMAScript 2015; this script runs ECMAScript 5".to_string(); + return Err(RunError { kind: RunErrorKind::Syntax, message, line: 0, column: 0, authored: false }); + } + let interp = &mut self.interp; + interp.evaluated = next_tag(interp.evaluated); + self.script_tag = interp.evaluated; + let marks = (interp.temp_envs_mark(), interp.temp_roots_mark()); + let linked = crate::module::link(interp, key, source, self.script_tag, limits, load); + let pushed = match linked { + Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run), + Err(fail) => Err(fail), + }; + let interp = &mut self.interp; + interp.drop_temp_envs(marks.0); + interp.drop_temp_roots(marks.1); + match pushed { + Ok(()) => Ok(()), + Err(LinkFail::Syntax { tag, error }) => { + self.interp.error_tag = tag; + Err(error.into()) + } + Err(LinkFail::At { tag, line, column, abrupt }) => { + let e = self.outcome(Err(abrupt)).err(); + self.interp.error_tag = tag; + Err(e.map_or_else(|| internal_error("a module failed without an error"), |e| RunError { line, column, ..e })) + } + Err(LinkFail::Run(abrupt)) => self.outcome(Err(abrupt)).map(drop), + } + } + + /// Runs the module `key` with `source` to its end ([`Realm::start_module`]) and returns + /// `undefined`. + pub fn run_module(&mut self, key: &str, source: &str, limits: ModuleLimits, load: &mut ModuleLoader<'_>) -> Result { + self.start_module(key, source, limits, load)?; + let result = self.interp.execute(); + self.outcome(result) + } + + /// Readies the realm for a run: its state from the last run cleared and its fuel filled. + fn reset_run(&mut self) -> Result<(), RunError> { self.script_tag = UNKNOWN_SOURCE; let interp = &mut self.interp; if let Some(message) = &interp.install_error { @@ -274,20 +348,7 @@ impl Realm { interp.finally_marks.clear(); interp.finally_sites.clear(); interp.error_mark = None; - let strict = interp.options.strict; - interp.evaluated = next_tag(interp.evaluated); - self.script_tag = interp.evaluated; - interp.source_tag = self.script_tag; - let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)); - interp.source_tag = UNKNOWN_SOURCE; - match code { - Ok(code) => Ok(code), - Err(CompileError::Syntax(e)) => { - interp.error_tag = self.script_tag; - Err(e.into()) - } - Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0, authored: false }), - } + Ok(()) } /// The end of a run: its completion value or error, with the interpreter's stacks emptied. diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 32790b3125..3e3472d634 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -30,7 +30,10 @@ //! //! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`, //! arrow functions, templates, default and rest parameters) without and with that option, and -//! prints both counts; its failures with the option go to `es2015-failures.txt`. +//! prints both counts; its failures with the option go to `es2015-failures.txt`. A sixth test runs +//! the module tests under `test/language/module-code`, `import` and `export` as modules, reading +//! the fixture files they import from the suite, and as scripts for comparison; its failures as +//! modules go to `module-failures.txt`. //! //! Two more tests read the Annex B trees, where tests name any edition's section: one parses every //! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset @@ -46,7 +49,9 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; -use vectorcraft_js::{JsValue, Limits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize}; +use vectorcraft_js::{ + JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, tokenize_module, +}; /// A test file's metadata, from its `/*--- … ---*/` block. #[derive(Default)] @@ -427,6 +432,12 @@ fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: Err(_) => return true, } } + uses_missing_builtin(&lists, missing) +} + +/// The tokens `lists` (of a test and the harness files it includes) use a missing built-in, as +/// [`needs_missing_builtin`] counts them. +fn uses_missing_builtin(lists: &[Vec], missing: &HashSet<&str>) -> bool { let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens)); lists.iter().flatten().any(|t| match &t.kind { TokenKind::Ident(name) => missing.contains(name.as_str()), @@ -793,6 +804,163 @@ fn run_es2015(dir: &Path) { assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display()); } +/// The folders under `test/language/` whose module tests [`modules_run`] reads. +const MODULE_FOLDERS: &[&str] = &["module-code", "import", "export"]; + +/// The feature tags a module test may carry: those of [`ES2015_FEATURES`] and `export * as ns from`. +const MODULE_FEATURES: &[&str] = + &["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters", "export-star-as-namespace-from-module"]; + +#[test] +fn modules_run() { + let Some(dir) = suite_dir() else { + println!("test262 modules: SKIPPED (no suite; run cargo xtask test262)"); + return; + }; + let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_modules(&dir)).unwrap(); + handle.join().unwrap(); +} + +/// The `/`-separated path, from the suite's folder, of the module `specifier` names for the module +/// at `referrer` (a path from the suite's folder too): only a `./` or `../` path that stays inside +/// `test/`. +fn module_path(referrer: &str, specifier: &str) -> Result { + if !(specifier.starts_with("./") || specifier.starts_with("../")) { + return Err(LoadError::Syntax(format!("the runner reads only relative specifiers: '{specifier}'"))); + } + let mut names: Vec<&str> = referrer.split('/').collect(); + names.pop(); + for name in specifier.split('/') { + match name { + "" | "." => {} + ".." if names.len() > 1 => { + names.pop(); + } + ".." => return Err(LoadError::Other(format!("'{specifier}' leads out of the suite's tests"))), + name => names.push(name), + } + } + Ok(names.join("/")) +} + +/// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with +/// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the +/// suite. `Err` describes a failure. A `negative_type` is the error the run must end with: thrown, +/// or, for a `SyntaxError`, also a module that does not parse. +fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> { + let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?; + let mut given = HashSet::new(); + let mut load = |referrer: &str, specifier: &str| { + let key = module_path(referrer, specifier)?; + let path = inside(dir, &key).map_err(LoadError::Other)?; + let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None }; + Ok(LoadedModule { key, source }) + }; + match (realm.run_module(rel, source, ModuleLimits::default(), &mut load), negative_type) { + (Ok(_), None) => Ok(()), + (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), + (Err(e), Some("SyntaxError")) if e.kind == RunErrorKind::Syntax => Ok(()), + (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { + realm.bind_last_thrown("__thrown"); + match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { + Ok(JsValue::Bool(true)) => Ok(()), + _ => Err(format!("threw {} (line {}); a {t} was expected", e.message, e.line)), + } + } + (Err(e), _) => Err(format!("{:?}: {} (line {}, column {})", e.kind, e.message, e.line, e.column)), + } +} + +/// Runs the module tests (`flags: [module]`) under [`MODULE_FOLDERS`] whose feature tags are all in +/// [`MODULE_FEATURES`], leaving out asynchronous tests and those that use a missing built-in: each +/// once as a strict script with [`Options::es2015`], as they could run before modules, and once as +/// a module, and prints both counts. A `negative: phase: parse` test must not parse as a module, +/// and a `phase: resolution` one must end before it runs with the error its `type:` names. +/// Failures as a module go to `module-failures.txt`. +fn run_modules(dir: &Path) { + let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p))); + let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js")); + let missing = missing_builtins(&[TEXT_BUILTINS]); + let options = Options { es2015: true, ..Options::default() }; + let (mut selected, mut skipped) = (0usize, 0usize); + let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize)); + let mut failures = String::new(); + for folder in MODULE_FOLDERS { + let root = or_fail(inside(dir, &format!("test/language/{folder}"))); + assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); + for path in or_fail(test_files(&root)) { + let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/"); + let source = or_fail(read_source(&path)); + let meta = meta(&source); + let has = |flag: &str| meta.flags.iter().any(|f| f == flag); + if !has("module") || !meta.features.iter().all(|f| MODULE_FEATURES.contains(&f.as_str())) { + continue; + } + let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect(); + let phase = meta.negative_phase.as_deref(); + // A module that must not parse has no tokens to look at, and one that does not parse + // runs, to fail. + let missing_builtin = phase != Some("parse") + && match (tokenize_module(&source, &options), tokenize(&includes, &options)) { + (Ok(test), Ok(harness)) => uses_missing_builtin(&[test, harness], &missing), + (Err(_), Ok(_)) => false, + (_, Err(_)) => true, + }; + if has("async") || missing_builtin { + skipped += 1; + continue; + } + selected += 1; + let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution"))); + let as_script = if matches!(phase, Some("parse" | "resolution")) { + parse(&source, &Options { strict: true, ..options.clone() }).is_err() + } else { + run_one(&format!("\"use strict\";\n{prelude}{includes}{source}"), negative_type.as_deref(), &options).is_ok() + }; + if as_script { + before.0 += 1; + } else { + before.1 += 1; + } + let outcome = if phase == Some("parse") { + match vectorcraft_js::parse_module(&source, &options) { + Err(_) => Ok(()), + Ok(_) => Err("parsed; a SyntaxError was expected".to_string()), + } + } else { + let prelude = format!("{prelude}{includes}"); + match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative_type.as_deref(), &options)) { + Ok(r) => r, + Err(_) => Err("PANIC".to_string()), + } + }; + match outcome { + Ok(()) => after.0 += 1, + Err(why) => { + after.1 += 1; + failures.push_str(&format!("{rel}: {why}\n")); + } + } + } + } + assert!(selected > 0, "no module tests under {}", dir.display()); + let report = dir.join("module-failures.txt"); + if let Err(e) = std::fs::write(&report, &failures) { + println!("could not write {}: {e}", report.display()); + } + println!( + "test262 modules: {selected} tests. As scripts: {} passed, {} failed. As modules: {} passed, {} failed. Skipped {skipped} \ + asynchronous or missing-built-in tests. Failures: {}", + before.0, + before.1, + after.0, + after.1, + report.display() + ); + assert!(!failures.contains("PANIC"), "the interpreter panicked; see {}", report.display()); +} + #[test] fn annex_b_runs() { let Some(dir) = suite_dir() else { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..ff97bd9a3e 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -2029,13 +2029,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), ( "ui.runInstalledScript", "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..f281431dc5 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -3,7 +3,7 @@ //! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`. //! //! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it -//! asks for a `.js` or `.jsx` file (the web opens the browser's file picker). With Preferences › +//! asks for a `.js`, `.mjs` or `.jsx` file (the web opens the browser's file picker). With Preferences › //! General › Show External Script Warning off, the chosen script runs at once. Warning fields: //! `name`, `script` (`script.run`'s params) and `dontShow` (true: turn the warning off). //! @@ -145,7 +145,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result { let path = params.get("path").and_then(Value::as_str); if path.is_some_and(|path| !runs(path)) { - return Err("Choose a .js or .jsx script".into()); + return Err("Choose a .js, .mjs or .jsx script".into()); } if !app.session.prefs.show_external_script_warning { return app.run("script.run", params); diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..0150154359 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6427,7 +6427,7 @@ digits Malayalam Malaiàlam Do not show this warning again No tornis a mostrar aquest avís Stop the script and undo what it did? Then quit again. Voleu aturar l'script i desfer el que ha fet? Després, torneu a sortir. This script has added a great many objects. Continue, or stop it and undo what it did? Aquest script ha afegit moltíssims objectes. Voleu continuar, o aturar-lo i desfer el que ha fet? -@msg Choose a .js or .jsx script Trieu un script .js o .jsx +@msg Choose a .js, .mjs or .jsx script Trieu un script .js, .mjs o .jsx @msg Ran {name} S'ha executat {name} @msg The script was stopped and its changes were undone L'script s'ha aturat i s'han desfet els seus canvis @msg a script is running: stop it or wait for it to finish s'està executant un script: atureu-lo o espereu que acabi @@ -6597,7 +6597,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB @msg `path` is empty `path` és buit @msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source` -@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` ha d’indicar un fitxer .js, .mjs o .jsx @msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source` @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..08fa462557 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -5235,7 +5235,7 @@ imageTrace Outline Obrys Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. This script has added a great many objects. Continue, or stop it and undo what it did? Tento skript přidal velmi mnoho objektů. Pokračovat, nebo jej zastavit a vrátit jeho změny? -@msg Choose a .js or .jsx script Vyberte skript .js nebo .jsx +@msg Choose a .js, .mjs or .jsx script Vyberte skript .js, .mjs nebo .jsx @msg Ran {name} Spuštěno: {name} @msg The script was stopped and its changes were undone Skript byl zastaven a jeho změny byly vráceny @msg a script is running: stop it or wait for it to finish běží skript: zastavte jej nebo počkejte na jeho dokončení @@ -5382,7 +5382,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `args` is larger than 1 MiB `args` je větší než 1 MiB @msg `path` is empty `path` je prázdný @msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source` -@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` musí označovat soubor .js, .mjs nebo .jsx @msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source` @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..6ea9ba8e12 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -53,7 +53,7 @@ @msg it decompresses to more than {_1} MB den udpakkes til mere end {_1} MB @msg its editing data is for a different page dens redigeringsdata er til en anden side @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` skal være "emBox", "capHeight", "xHeight" eller "icfBox" -@msg Choose a .js or .jsx script Vælg et .js- eller .jsx-script +@msg Choose a .js, .mjs or .jsx script Vælg et .js-, .mjs- eller .jsx-script @msg Ran {name} Kørte {name} @msg The script was stopped and its changes were undone Scriptet blev stoppet, og dets ændringer blev fortrudt @msg a script is running: stop it or wait for it to finish et script kører: stop det, eller vent, til det er færdigt @@ -241,7 +241,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg `args` is larger than 1 MiB `args` er større end 1 MiB @msg `path` is empty `path` er tom @msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source` -@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil +@msg `path` must name a .js, .mjs or .jsx file `path` skal angive en .js-, .mjs- eller .jsx-fil @msg give exactly one of `path` and `source` angiv præcis én af `path` og `source` @msg Running a script Kører et script @msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..b915221d20 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4820,7 +4820,7 @@ theme Appearance Erscheinungsbild Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. This script has added a great many objects. Continue, or stop it and undo what it did? Dieses Skript hat sehr viele Objekte hinzugefügt. Fortfahren oder das Skript stoppen und seine Änderungen rückgängig machen? -@msg Choose a .js or .jsx script Wählen Sie ein .js- oder .jsx-Skript +@msg Choose a .js, .mjs or .jsx script Wählen Sie ein .js-, .mjs- oder .jsx-Skript @msg Ran {name} {name} ausgeführt @msg The script was stopped and its changes were undone Das Skript wurde gestoppt und seine Änderungen wurden rückgängig gemacht @msg a script is running: stop it or wait for it to finish ein Skript wird ausgeführt: stoppen Sie es oder warten Sie, bis es fertig ist @@ -8434,7 +8434,7 @@ breakText Glyphs Glyphen @msg `args` is larger than 1 MiB `args` ist größer als 1 MiB @msg `path` is empty `path` ist leer @msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source` -@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben +@msg `path` must name a .js, .mjs or .jsx file `path` muss eine .js-, .mjs- oder .jsx-Datei angeben @msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an @msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein @msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..3fdba11d4c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2624,7 +2624,7 @@ axis Both Και τα δύο Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. This script has added a great many objects. Continue, or stop it and undo what it did? Αυτό το σενάριο πρόσθεσε πάρα πολλά αντικείμενα. Συνέχεια, ή διακοπή και αναίρεση όσων έκανε; -@msg Choose a .js or .jsx script Επιλέξτε ένα σενάριο .js ή .jsx +@msg Choose a .js, .mjs or .jsx script Επιλέξτε ένα σενάριο .js, .mjs ή .jsx @msg Ran {name} Εκτελέστηκε: {name} @msg The script was stopped and its changes were undone Το σενάριο διακόπηκε και οι αλλαγές του αναιρέθηκαν @msg a script is running: stop it or wait for it to finish εκτελείται ένα σενάριο: διακόψτε το ή περιμένετε να τελειώσει @@ -2795,7 +2795,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB @msg `path` is empty το `path` είναι κενό @msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source` -@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx +@msg `path` must name a .js, .mjs or .jsx file το `path` πρέπει να ορίζει αρχείο .js, .mjs ή .jsx @msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source` @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..b2e9ad14bd 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4899,7 +4899,7 @@ axis Both Ambos Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. This script has added a great many objects. Continue, or stop it and undo what it did? Este script ha añadido muchísimos objetos. ¿Continuar, o detenerlo y deshacer lo que hizo? -@msg Choose a .js or .jsx script Elija un script .js o .jsx +@msg Choose a .js, .mjs or .jsx script Elija un script .js, .mjs o .jsx @msg Ran {name} Se ejecutó {name} @msg The script was stopped and its changes were undone El script se detuvo y sus cambios se deshicieron @msg a script is running: stop it or wait for it to finish se está ejecutando un script: deténgalo o espere a que termine @@ -5069,7 +5069,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB @msg `path` is empty `path` está vacío @msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source` -@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` debe indicar un archivo .js, .mjs o .jsx @msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source` @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..b715bbc2ec 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5140,7 +5140,7 @@ imageTrace Outline Ääriviiva Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. This script has added a great many objects. Continue, or stop it and undo what it did? Tämä komentosarja on lisännyt hyvin paljon objekteja. Jatketaanko, vai pysäytetäänkö se ja kumotaan sen muutokset? -@msg Choose a .js or .jsx script Valitse .js- tai .jsx-komentosarja +@msg Choose a .js, .mjs or .jsx script Valitse .js-, .mjs- tai .jsx-komentosarja @msg Ran {name} Suoritettu: {name} @msg The script was stopped and its changes were undone Komentosarja pysäytettiin ja sen muutokset kumottiin @msg a script is running: stop it or wait for it to finish komentosarja on käynnissä: pysäytä se tai odota sen valmistumista @@ -5310,7 +5310,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB @msg `path` is empty `path` on tyhjä @msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa -@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto +@msg `path` must name a .js, .mjs or .jsx file `path` on oltava .js-, .mjs- tai .jsx-tiedosto @msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source` @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..ca239421f1 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4881,7 +4881,7 @@ axis Both Les deux Do not show this warning again Ne plus afficher cet avertissement Stop the script and undo what it did? Then quit again. Arrêter le script et annuler ce qu’il a fait ? Quittez ensuite à nouveau. This script has added a great many objects. Continue, or stop it and undo what it did? Ce script a ajouté un très grand nombre d’objets. Continuer, ou l’arrêter et annuler ce qu’il a fait ? -@msg Choose a .js or .jsx script Choisissez un script .js ou .jsx +@msg Choose a .js, .mjs or .jsx script Choisissez un script .js, .mjs ou .jsx @msg Ran {name} {name} exécuté @msg The script was stopped and its changes were undone Le script a été arrêté et ses modifications ont été annulées @msg a script is running: stop it or wait for it to finish un script est en cours d’exécution : arrêtez-le ou attendez qu’il se termine @@ -5027,7 +5027,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `args` is larger than 1 MiB `args` dépasse 1 Mio @msg `path` is empty `path` est vide @msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source` -@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` doit désigner un fichier .js, .mjs ou .jsx @msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source` @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue @msg Running a script Exécution d’un script diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..65579ccc22 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7573,7 +7573,7 @@ arrowhead Feather पंख Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। This script has added a great many objects. Continue, or stop it and undo what it did? इस स्क्रिप्ट ने बहुत सारे ऑब्जेक्ट जोड़े हैं। जारी रखें, या इसे रोककर इसके बदलाव पूर्ववत करें? -@msg Choose a .js or .jsx script .js या .jsx स्क्रिप्ट चुनें +@msg Choose a .js, .mjs or .jsx script .js, .mjs या .jsx स्क्रिप्ट चुनें @msg Ran {name} {name} चलाई गई @msg The script was stopped and its changes were undone स्क्रिप्ट रोकी गई और उसके बदलाव पूर्ववत किए गए @msg a script is running: stop it or wait for it to finish एक स्क्रिप्ट चल रही है: उसे रोकें या पूरा होने की प्रतीक्षा करें @@ -7744,7 +7744,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है @msg `path` is empty `path` खाली है @msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं -@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए +@msg `path` must name a .js, .mjs or .jsx file `path` में किसी .js, .mjs या .jsx फ़ाइल का नाम होना चाहिए @msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..f1b34e6842 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5752,7 +5752,7 @@ imageTrace Outline Körvonal Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés Stop the script and undo what it did? Then quit again. Leállítja a parancsfájlt, és visszavonja a módosításait? Ezután lépjen ki újra. This script has added a great many objects. Continue, or stop it and undo what it did? Ez a parancsfájl nagyon sok objektumot adott hozzá. Folytatja, vagy leállítja és visszavonja a módosításait? -@msg Choose a .js or .jsx script Válasszon .js vagy .jsx parancsfájlt +@msg Choose a .js, .mjs or .jsx script Válasszon .js, .mjs vagy .jsx parancsfájlt @msg Ran {name} Lefutott: {name} @msg The script was stopped and its changes were undone A parancsfájl leállt, a módosításai visszavonva @msg a script is running: stop it or wait for it to finish egy parancsfájl fut: állítsa le, vagy várja meg, hogy befejeződjön @@ -5900,7 +5900,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál @msg `path` is empty a `path` üres @msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket -@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia +@msg `path` must name a .js, .mjs or .jsx file a `path` értékének .js, .mjs vagy .jsx fájlt kell megadnia @msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source` @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..cdb530f77c 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -53,7 +53,7 @@ @msg it decompresses to more than {_1} MB hasil dekompresinya lebih dari {_1} MB @msg its editing data is for a different page data penyuntingannya untuk halaman lain @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` harus "emBox", "capHeight", "xHeight" atau "icfBox" -@msg Choose a .js or .jsx script Pilih skrip .js atau .jsx +@msg Choose a .js, .mjs or .jsx script Pilih skrip .js, .mjs, atau .jsx @msg Ran {name} {name} dijalankan @msg The script was stopped and its changes were undone Skrip dihentikan dan perubahannya dibatalkan @msg a script is running: stop it or wait for it to finish skrip sedang berjalan: hentikan atau tunggu hingga selesai @@ -148,7 +148,7 @@ @msg `args` is larger than 1 MiB `args` lebih besar dari 1 MiB @msg `path` is empty `path` kosong @msg `installed` takes a `path`, not a `source` `installed` menerima `path`, bukan `source` -@msg `path` must name a .js or .jsx file `path` harus menyebut file .js atau .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` harus menyebut file .js, .mjs, atau .jsx @msg give exactly one of `path` and `source` berikan tepat satu dari `path` dan `source` @msg [{j}] `{_1}`: {why} [{j}] `{_1}`: {why} @msg `answers[{i}]` {e} `answers[{i}]` {e} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..8362a90183 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4958,7 +4958,7 @@ axis Both Entrambi Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. This script has added a great many objects. Continue, or stop it and undo what it did? Questo script ha aggiunto moltissimi oggetti. Continuare, oppure interromperlo e annullare ciò che ha fatto? -@msg Choose a .js or .jsx script Scegli uno script .js o .jsx +@msg Choose a .js, .mjs or .jsx script Scegli uno script .js, .mjs o .jsx @msg Ran {name} {name} eseguito @msg The script was stopped and its changes were undone Lo script è stato interrotto e le sue modifiche sono state annullate @msg a script is running: stop it or wait for it to finish è in esecuzione uno script: interrompilo o attendi che finisca @@ -8475,7 +8475,7 @@ breakText Glyphs Glifi @msg `args` is larger than 1 MiB `args` supera 1 MiB @msg `path` is empty `path` è vuoto @msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source` -@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` deve indicare un file .js, .mjs o .jsx @msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source` @msg `answers` must be a list of answers `answers` deve essere un elenco di risposte @msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..0655c91562 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5784,7 +5784,7 @@ variable-list-end {0}, {1} {0}、{1} Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 This script has added a great many objects. Continue, or stop it and undo what it did? このスクリプトは非常に多くのオブジェクトを追加しました。続行しますか、それとも停止して変更を取り消しますか? -@msg Choose a .js or .jsx script .js または .jsx スクリプトを選択してください +@msg Choose a .js, .mjs or .jsx script .js、.mjs または .jsx スクリプトを選択してください @msg Ran {name} {name} を実行しました @msg The script was stopped and its changes were undone スクリプトを停止し、変更を取り消しました @msg a script is running: stop it or wait for it to finish スクリプトの実行中です: 停止するか、終了するまでお待ちください @@ -5931,7 +5931,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg `args` is larger than 1 MiB `args` が 1 MiB を超えています @msg `path` is empty `path` が空です @msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください -@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください +@msg `path` must name a .js, .mjs or .jsx file `path` には .js、.mjs または .jsx ファイルを指定してください @msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..ff7f6aa9a0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2135,7 +2135,7 @@ @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` უნდა იყოს მთელი რიცხვი 1-დან {_1}-მდე @msg `max` must be 1 to {MAX_WORDS} `max` უნდა იყოს 1-დან {MAX_WORDS}-მდე @msg `path` is empty `path` ცარიელია -@msg `path` must name a .js or .jsx file `path` უნდა მიუთითებდეს .js ან .jsx ფაილს +@msg `path` must name a .js, .mjs or .jsx file `path` უნდა მიუთითებდეს .js, .mjs ან .jsx ფაილს @msg `reference` must be a whole number from 0 to 8 `reference` უნდა იყოს მთელი რიცხვი 0-დან 8-მდე @msg `ringSeed` must be below 2^53, not {r} `ringSeed` უნდა იყოს 2^53-ზე ნაკლები და არა {r} @msg `source` is the only path, line or label that graph group `target` stands for `source` ერთადერთი ტრაექტორია, ხაზი ან წარწერაა, რომელსაც დიაგრამის ჯგუფი `target` წარმოადგენს @@ -8453,7 +8453,7 @@ imageTrace Outline კონტური Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. This script has added a great many objects. Continue, or stop it and undo what it did? ამ სკრიპტმა ძალიან ბევრი ობიექტი დაამატა. გაგრძელდეს, თუ შეჩერდეს და გაუქმდეს მისი ცვლილებები? -@msg Choose a .js or .jsx script აირჩიეთ .js ან .jsx სკრიპტი +@msg Choose a .js, .mjs or .jsx script აირჩიეთ .js, .mjs ან .jsx სკრიპტი @msg Ran {name} გაშვებულია: {name} @msg The script was stopped and its changes were undone სკრიპტი შეჩერდა და მისი ცვლილებები გაუქმდა @msg a script is running: stop it or wait for it to finish სკრიპტი მუშაობს: შეაჩერეთ ან დაელოდეთ დასრულებას diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..423ade9b5c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -5713,7 +5713,7 @@ variable-list-end {0}, {1} {0} 및 {1} Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. This script has added a great many objects. Continue, or stop it and undo what it did? 이 스크립트가 매우 많은 개체를 추가했습니다. 계속할까요, 아니면 중지하고 변경 내용을 취소할까요? -@msg Choose a .js or .jsx script .js 또는 .jsx 스크립트를 선택하세요 +@msg Choose a .js, .mjs or .jsx script .js, .mjs 또는 .jsx 스크립트를 선택하세요 @msg Ran {name} {name} 실행됨 @msg The script was stopped and its changes were undone 스크립트를 중지하고 변경 내용을 취소했습니다 @msg a script is running: stop it or wait for it to finish 스크립트 실행 중: 중지하거나 끝날 때까지 기다리세요 @@ -5860,7 +5860,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다 @msg `path` is empty `path`이(가) 비어 있습니다 @msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요 -@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다 +@msg `path` must name a .js, .mjs or .jsx file `path`은(는) .js, .mjs 또는 .jsx 파일을 가리켜야 합니다 @msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..982e687887 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -53,7 +53,7 @@ @msg it decompresses to more than {_1} MB gedecomprimeerd is het groter dan {_1} MB @msg its editing data is for a different page zijn bewerkingsgegevens horen bij een andere pagina @msg `fontHeightReference` must be "emBox", "capHeight", "xHeight" or "icfBox" `fontHeightReference` moet "emBox", "capHeight", "xHeight" of "icfBox" zijn -@msg Choose a .js or .jsx script Kies een .js- of .jsx-script +@msg Choose a .js, .mjs or .jsx script Kies een .js-, .mjs- of .jsx-script @msg Ran {name} {name} uitgevoerd @msg The script was stopped and its changes were undone Het script is gestopt en de wijzigingen ervan zijn ongedaan gemaakt @msg a script is running: stop it or wait for it to finish er wordt een script uitgevoerd: stop het of wacht tot het klaar is @@ -219,7 +219,7 @@ liquify-list-end {0}, {1} {0} en {1} @msg `args` is larger than 1 MiB `args` is groter dan 1 MiB @msg `path` is empty `path` is leeg @msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source` -@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen +@msg `path` must name a .js, .mjs or .jsx file `path` moet een .js-, .mjs- of .jsx-bestand aanwijzen @msg give exactly one of `path` and `source` geef precies een van `path` en `source` @msg Running a script Er wordt een script uitgevoerd @msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..85ecad038e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5063,7 +5063,7 @@ imageTrace Outline Kontur Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. This script has added a great many objects. Continue, or stop it and undo what it did? Ten skrypt dodał bardzo wiele obiektów. Kontynuować, czy zatrzymać go i cofnąć jego zmiany? -@msg Choose a .js or .jsx script Wybierz skrypt .js lub .jsx +@msg Choose a .js, .mjs or .jsx script Wybierz skrypt .js, .mjs lub .jsx @msg Ran {name} Wykonano: {name} @msg The script was stopped and its changes were undone Skrypt został zatrzymany, a jego zmiany cofnięte @msg a script is running: stop it or wait for it to finish skrypt jest uruchomiony: zatrzymaj go lub poczekaj na jego zakończenie @@ -8678,7 +8678,7 @@ breakText Glyphs Glify @msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB @msg `path` is empty `path` jest puste @msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source` -@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` musi wskazywać plik .js, .mjs lub .jsx @msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source` @msg `answers` must be a list of answers `answers` musi być listą odpowiedzi @msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..94b7580994 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -6102,7 +6102,7 @@ variable-list-end {0}, {1} {0} e {1} Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. This script has added a great many objects. Continue, or stop it and undo what it did? Este script adicionou muitíssimos objetos. Continuar, ou pará-lo e desfazer o que ele fez? -@msg Choose a .js or .jsx script Escolha um script .js ou .jsx +@msg Choose a .js, .mjs or .jsx script Escolha um script .js, .mjs ou .jsx @msg Ran {name} {name} executado @msg The script was stopped and its changes were undone O script foi parado e suas alterações foram desfeitas @msg a script is running: stop it or wait for it to finish um script está em execução: pare-o ou aguarde até que termine @@ -9047,7 +9047,7 @@ swatch Yellow Green Verde-amarelado @msg `args` is larger than 1 MiB `args` tem mais de 1 MiB @msg `path` is empty `path` está vazio @msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source` -@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` deve indicar um arquivo .js, .mjs ou .jsx @msg give exactly one of `path` and `source` informe exatamente um de `path` e `source` @msg `answers` must be a list of answers `answers` deve ser uma lista de respostas @msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..48468148a6 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4934,7 +4934,7 @@ axis Both Оба Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. This script has added a great many objects. Continue, or stop it and undo what it did? Этот скрипт добавил очень много объектов. Продолжить или остановить его и отменить его изменения? -@msg Choose a .js or .jsx script Выберите скрипт .js или .jsx +@msg Choose a .js, .mjs or .jsx script Выберите скрипт .js, .mjs или .jsx @msg Ran {name} Выполнено: {name} @msg The script was stopped and its changes were undone Скрипт остановлен, его изменения отменены @msg a script is running: stop it or wait for it to finish выполняется скрипт: остановите его или дождитесь завершения @@ -5091,7 +5091,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `args` is larger than 1 MiB `args` больше 1 МиБ @msg `path` is empty параметр `path` пуст @msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source` -@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` должен указывать на файл .js, .mjs или .jsx @msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source` @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..556baff641 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4796,7 +4796,7 @@ axis Both Båda Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. This script has added a great many objects. Continue, or stop it and undo what it did? Det här skriptet har lagt till väldigt många objekt. Fortsätta, eller stoppa det och ångra det det gjort? -@msg Choose a .js or .jsx script Välj ett .js- eller .jsx-skript +@msg Choose a .js, .mjs or .jsx script Välj ett .js-, .mjs- eller .jsx-skript @msg Ran {name} Körde {name} @msg The script was stopped and its changes were undone Skriptet stoppades och dess ändringar ångrades @msg a script is running: stop it or wait for it to finish ett skript körs: stoppa det eller vänta tills det är klart @@ -4967,7 +4967,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg `args` is larger than 1 MiB `args` är större än 1 MiB @msg `path` is empty `path` är tomt @msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source` -@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil +@msg `path` must name a .js, .mjs or .jsx file `path` måste ange en .js-, .mjs- eller .jsx-fil @msg give exactly one of `path` and `source` ange exakt en av `path` och `source` @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..762714fd4d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5848,7 +5848,7 @@ fn script_run_param_errors_are_translated() { "`args` is larger than 1 MiB", "`path` is empty", "`installed` takes a `path`, not a `source`", - "`path` must name a .js or .jsx file", + "`path` must name a .js, .mjs or .jsx file", "give exactly one of `path` and `source`", ]; let scanned = message_literals(); @@ -5876,7 +5876,7 @@ fn script_run_param_errors_are_translated() { (json!({"source": "1", "args": {"x": "x".repeat(1 << 20)}}), Some("`args` is larger than 1 MiB".into())), (json!({"path": ""}), Some("`path` is empty".into())), (json!({"source": "1", "installed": true}), Some("`installed` takes a `path`, not a `source`".into())), - (json!({"path": "notes.txt"}), Some("`path` must name a .js or .jsx file".into())), + (json!({"path": "notes.txt"}), Some("`path` must name a .js, .mjs or .jsx file".into())), (json!({}), Some("give exactly one of `path` and `source`".into())), (json!({"path": "a.js", "source": "1"}), Some("give exactly one of `path` and `source`".into())), (json!({"path": 1}), Some("`path` must be a string".into())), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..370480f94f 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4648,7 +4648,7 @@ axis Both Her İkisi Do not show this warning again Bu uyarıyı bir daha gösterme Stop the script and undo what it did? Then quit again. Betik durdurulsun ve yaptıkları geri alınsın mı? Ardından yeniden çıkın. This script has added a great many objects. Continue, or stop it and undo what it did? Bu betik çok sayıda nesne ekledi. Devam edilsin mi, yoksa durdurulup yaptıkları geri mi alınsın? -@msg Choose a .js or .jsx script Bir .js veya .jsx betiği seçin +@msg Choose a .js, .mjs or .jsx script Bir .js, .mjs veya .jsx betiği seçin @msg Ran {name} {name} çalıştırıldı @msg The script was stopped and its changes were undone Betik durduruldu ve değişiklikleri geri alındı @msg a script is running: stop it or wait for it to finish bir betik çalışıyor: durdurun veya bitmesini bekleyin @@ -4803,7 +4803,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük @msg `path` is empty `path` boş @msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz -@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır +@msg `path` must name a .js, .mjs or .jsx file `path` bir .js, .mjs veya .jsx dosyasını adlandırmalıdır @msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..07182972fa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4942,7 +4942,7 @@ axis Both Обидві Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. This script has added a great many objects. Continue, or stop it and undo what it did? Цей скрипт додав дуже багато об’єктів. Продовжити чи зупинити його та скасувати його зміни? -@msg Choose a .js or .jsx script Виберіть скрипт .js або .jsx +@msg Choose a .js, .mjs or .jsx script Виберіть скрипт .js, .mjs або .jsx @msg Ran {name} Виконано: {name} @msg The script was stopped and its changes were undone Скрипт зупинено, його зміни скасовано @msg a script is running: stop it or wait for it to finish виконується скрипт: зупиніть його або дочекайтеся завершення @@ -8634,7 +8634,7 @@ breakText Glyphs Гліфи @msg `args` is larger than 1 MiB `args` більший за 1 МіБ @msg `path` is empty параметр `path` порожній @msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source` -@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` має вказувати на файл .js, .mjs або .jsx @msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source` @msg `answers` must be a list of answers `answers` має бути списком відповідей @msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..f24dd20ba4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5420,7 +5420,7 @@ theme Appearance Giao diện Do not show this warning again Không hiện lại cảnh báo này Stop the script and undo what it did? Then quit again. Dừng tập lệnh và hoàn tác những gì nó đã làm? Sau đó hãy thoát lại. This script has added a great many objects. Continue, or stop it and undo what it did? Tập lệnh này đã thêm rất nhiều đối tượng. Tiếp tục, hay dừng lại và hoàn tác những gì nó đã làm? -@msg Choose a .js or .jsx script Chọn một tập lệnh .js hoặc .jsx +@msg Choose a .js, .mjs or .jsx script Chọn một tập lệnh .js, .mjs hoặc .jsx @msg Ran {name} Đã chạy {name} @msg The script was stopped and its changes were undone Tập lệnh đã dừng và các thay đổi của nó đã được hoàn tác @msg a script is running: stop it or wait for it to finish một tập lệnh đang chạy: hãy dừng nó hoặc chờ nó kết thúc @@ -5590,7 +5590,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB @msg `path` is empty `path` trống @msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source` -@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx +@msg `path` must name a .js, .mjs or .jsx file `path` phải chỉ đến tệp .js, .mjs hoặc .jsx @msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source` @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..fa282f2150 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -5449,7 +5449,7 @@ imageTrace Outline 轮廓 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 This script has added a great many objects. Continue, or stop it and undo what it did? 此脚本已添加大量对象。要继续,还是停止并撤销其更改? -@msg Choose a .js or .jsx script 请选择 .js 或 .jsx 脚本 +@msg Choose a .js, .mjs or .jsx script 请选择 .js、.mjs 或 .jsx 脚本 @msg Ran {name} 已运行 {name} @msg The script was stopped and its changes were undone 脚本已停止,其更改已撤销 @msg a script is running: stop it or wait for it to finish 脚本正在运行:请停止它或等待其完成 @@ -8684,7 +8684,7 @@ breakText Glyphs 字形 @msg `args` is larger than 1 MiB `args` 大于 1 MiB @msg `path` is empty `path` 为空 @msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` -@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件 +@msg `path` must name a .js, .mjs or .jsx file `path` 必须指向 .js、.mjs 或 .jsx 文件 @msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个 @msg `answers` must be a list of answers `answers` 必须是回答的列表 @msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..8f2aa2eafb 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2795,7 +2795,7 @@ file-filter Templates 範本 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 This script has added a great many objects. Continue, or stop it and undo what it did? 此指令碼已新增大量物件。要繼續,還是停止並還原其變更? -@msg Choose a .js or .jsx script 請選擇 .js 或 .jsx 指令碼 +@msg Choose a .js, .mjs or .jsx script 請選擇 .js、.mjs 或 .jsx 指令碼 @msg Ran {name} 已執行 {name} @msg The script was stopped and its changes were undone 指令碼已停止,其變更已還原 @msg a script is running: stop it or wait for it to finish 指令碼正在執行:請停止它或等待其完成 @@ -2942,7 +2942,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg `args` is larger than 1 MiB `args` 大於 1 MiB @msg `path` is empty `path` 為空 @msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` -@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案 +@msg `path` must name a .js, .mjs or .jsx file `path` 必須指向 .js、.mjs 或 .jsx 檔案 @msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..33986b055a 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -2030,13 +2030,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.runScript", "Other Script…", "Cmd+F12", - "{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", + "{path? | source?, name?} run a .js, .mjs or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker)", ), ( crate::scripts_menu::COMMAND, "Run Script", "", - "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", + "{path: a script's path as script.listInstalled gives it} run a script of the Scripts folder, as its File › Scripts item does (script.run with installed reads the file once, checks it again and runs that text, so its #include lines and $.evalFile read in the folder that read found), without the warning Other Script… shows; a file that is no longer a .js, .mjs or .jsx file in the folder or a subfolder at most 4 levels below it, or that is or lies behind a link or is hidden, is not run, and the menu's listing is read again", ), ( "ui.checkScript", diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..f8d3d4c39e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -94,7 +94,7 @@ fn only_js_and_jsx_files_are_taken() { let mut app = app(); for name in ["a.txt", "a.jsxbin", "a"] { let e = menus::run_ui_command(&mut app, "ui.runScript", &json!({ "path": name })).unwrap().unwrap_err(); - assert!(e.contains(".js or .jsx"), "{name}: {e}"); + assert!(e.contains(".js, .mjs or .jsx"), "{name}: {e}"); } assert!(app.ui.dialog.is_none()); } diff --git a/docs/mcp.md b/docs/mcp.md index ec6f2d7f76..b34a4ebed6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2611,10 +2611,10 @@ vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` `script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. -File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page +File › Scripts › Other Script… (Cmd+F12) picks a `.js`, `.mjs` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html -describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any -case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is +describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in +any case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and `ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in `.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and @@ -2625,8 +2625,36 @@ before each element, strings and `String` objects by code point, and objects wit throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and an engine that `#targetengine` keeps reads each run the way that run's script does. A -`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the -app through the global object `vc`, and writes to the Script Console and runs other files through `$`: +`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. + +A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module +(https://262.ecma-international.org/6.0/#sec-modules): strict mode code with the forms above, and `import` and +`export` declarations at its top level. `import` and `export` are syntax errors in a `.js` or `.jsx` script. + +- A specifier is a path relative to the file that imports it. It starts with `./` or `../`, separates names with + `/` and names a `.mjs` or `.js` file, which is read as a module. A bare name such as `'lib'`, a URL, an absolute + path, and a specifier with `\`, `:` or a control character end the run with a `SyntaxError` that names the + specifier. +- Modules are read through the script's own file scope: only from the script's folder and the folders below it. + A specifier whose `..` names lead above the script's folder, and a link that leads out of it, end the run with an + error that names the specifier. A missing file ends the run with an error that names the specifier. +- Every module is read, parsed and linked before any of them runs. A syntax error, a missing or refused file, an + import of a name the module does not export, and an import of a name that two `export *` declarations give from + different modules end the run with no code run, at the file, line and column of the module they are in. +- Each module runs once in a run, after the modules it imports, in the order it imports them; two paths to one file + (a link, `sub/../x.mjs`, or names that differ only in letter case on Windows) are one module. An import reads + the exporting module's binding each time, so it sees later assignments, and reading it before that module has + initialized it (in a cycle of imports) throws a `ReferenceError`. Assigning to an import throws a `TypeError`. +- `import * as ns` gives a namespace object: not extensible, with no prototype, its export names in code unit order + as properties that cannot be written or deleted, and `[object Module]` from `Object.prototype.toString`. + `export *` passes on every name but `default`, and `export * as ns from` passes on a namespace. +- A module's top-level names stay in the module, `this` is `undefined` at its top, it has no preprocessor lines, + and `import()` is a syntax error. `vc`, `$` and the other globals are there as in a script. +- Module files count against the limits of `#include` files: 8 MiB a file, 32 MiB of source in all, 64 files + besides the script, imports 16 deep and 1,024 paths looked up. These limits are VectorCraft's own. + +The script reaches the app through the global object `vc`, and writes to the Script Console and runs other files +through `$`: - `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can catch. The documents and the session state the command changed, preferences included, go back, and any file it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 144b20bd1c..15745fc595 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,7 +1079,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. @@ -1161,7 +1162,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). - - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). + - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js, .mjs or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`). From 5edc81e54873b0dfab9fce13c1d01ab234d5a7a7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 12:31:42 -0800 Subject: [PATCH 041/153] Plug-ins: a null translations map is refused A manifest that gives `null` for `translations` or for one of its maps (`params`, `groups`, `commands`, `options`) is refused with an error instead of being read as empty. The palette test of translated plug-in commands uses names no other test's plug-in has. --- crates/plugins/src/translations.rs | 9 ++++++--- crates/ui-egui/src/palette.rs | 9 +++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/plugins/src/translations.rs b/crates/plugins/src/translations.rs index 76c8f65046..849b6b2905 100644 --- a/crates/plugins/src/translations.rs +++ b/crates/plugins/src/translations.rs @@ -64,9 +64,6 @@ impl<'de, T: Deserialize<'de>> Deserialize<'de> for Entries { fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("an object") } - fn visit_unit(self) -> std::result::Result { - Ok(Entries::default()) - } fn visit_map>(self, mut map: A) -> std::result::Result { let mut seen = HashSet::new(); let mut out = Vec::new(); @@ -516,6 +513,12 @@ mod tests { (r#"{"de":{"name":7}}"#, "manifest"), (r#"["de"]"#, "manifest"), (r#""de""#, "manifest"), + ("null", "expected an object"), + (r#"{"de":null}"#, "manifest"), + (r#"{"de":{"params":null}}"#, "expected an object"), + (r#"{"de":{"groups":null}}"#, "expected an object"), + (r#"{"de":{"commands":null}}"#, "expected an object"), + (r#"{"de":{"params":{"mode":{"options":null}}}}"#, "expected an object"), ] { let e = Manifest::parse(with(translations).as_bytes()).unwrap_err().to_string(); assert!(e.contains(says), "{translations}: {e}"); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 852c0ddeb3..c38ba36e0f 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -3319,9 +3319,10 @@ mod tests { fn a_plugin_command_result_shows_the_plugins_translation() { use vectorcraft_plugins::wat as tpl; let id = "test.UI.palette_translated"; + // Names no other test's plug-in has, since tests running beside this one share the registry. let manifest = format!( - r#"{{"id":"{id}","name":"Tidy","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Grow"}}], - "translations":{{"de":{{"name":"Aufräumen","commands":{{"grow":{{"label":"Wachsen"}}}}}}}}}}"# + r#"{{"id":"{id}","name":"Groom","version":"1","kind":"filter","commands":[{{"id":"grow","label":"Expand Rim"}}], + "translations":{{"de":{{"name":"Pflegen","commands":{{"grow":{{"label":"Erweitern"}}}}}}}}}}"# ); vectorcraft_plugins::registry::install_bytes(&wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap()).unwrap(); let key = format!("plugin.{id}.grow"); @@ -3332,9 +3333,9 @@ mod tests { let (de, fr) = (shown("de"), shown("fr")); vectorcraft_plugins::registry::remove(id); let (de, object, plugins) = de.expect("the command is a result"); - assert_eq!(de, format!("{object} › {plugins} › Aufräumen › Wachsen")); + assert_eq!(de, format!("{object} › {plugins} › Pflegen › Erweitern")); let (fr, object, plugins) = fr.expect("the command is a result"); - assert_eq!(fr, format!("{object} › {plugins} › Tidy › Grow")); + assert_eq!(fr, format!("{object} › {plugins} › Groom › Expand Rim")); } /// A plug-in command whose plug-in translates its name and label into English shows the From 4cfa6a8434f66f54d4c839df5f5df3354bd1696d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:54:53 -0800 Subject: [PATCH 042/153] JavaScript: module namespaces, global deletes and module loading follow ES2015 - A read or write that reaches a module namespace through a prototype chain checks the export's temporal dead zone and refuses the write; for-in over a namespace lists its keys without reading the exports. - `delete this.x` and a delete inside `with` remove only the property, so a later `let x` is still a SyntaxError. - An arrow function's `length` is configurable. - `let [` cannot start the body of if, else, while, for or a label. - A specifier with an unpaired surrogate parses; the loader refuses it before reading any file. - Each module's code counts against the heap from when it loads, and export lookups use an index instead of copying export lists. - A module reached again through another path is not read or counted against the 32 MiB source limit again, its relative imports are read from the folder the file is in, and on Windows two files whose names differ only in case in a case-sensitive folder stay two modules. - `$.evalFile` in a module reads beside that module. - `script.run` takes `module`, and a `.mjs` file picked on the web runs as a module. - Without `es2015`, the compiler does not collect the block scopes that only Annex B block functions read. - The test262 runner grades negative module tests by their phase and counts panics on their own. --- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/file_access.rs | 29 +++++- crates/engine/src/script/include.rs | 63 +++++++++---- crates/engine/src/script/mod.rs | 51 +++++++++-- crates/engine/src/tests/script_folder.rs | 1 + crates/engine/src/tests/script_modules.rs | 75 ++++++++++++++++ crates/js/src/ast.rs | 4 + crates/js/src/compiler.rs | 34 ++++--- crates/js/src/es2015_tests.rs | 29 +++++- crates/js/src/heap.rs | 2 +- crates/js/src/host.rs | 19 ++-- crates/js/src/host_tests.rs | 37 ++++++-- crates/js/src/interp.rs | 96 +++++++++++++++----- crates/js/src/lib.rs | 5 +- crates/js/src/module.rs | 90 +++++++++++++------ crates/js/src/module_tests.rs | 103 ++++++++++++++++++++-- crates/js/src/parser.rs | 5 ++ crates/js/src/parser/module.rs | 10 +-- crates/js/src/realm.rs | 3 +- crates/js/tests/test262.rs | 46 ++++++++-- crates/ui-egui/src/dialogs/script_run.rs | 5 +- crates/ui-egui/src/tests/script_run.rs | 12 +++ docs/mcp.md | 13 ++- docs/target-app-parity.md | 2 +- 24 files changed, 604 insertions(+), 134 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 67d6556bbe..fa4d7ea425 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 script file (.js, .mjs or .jsx) | 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. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, and an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. 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; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns 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 script file (.js, .mjs or .jsx) | 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), module?: true or false (default true for a path ending in .mjs, false otherwise; true runs the file or source as a .mjs file runs, as a module, and a source run this way imports no files), 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. A .mjs file runs as an ECMAScript 2015 module: strict code whose import and export declarations at its top name other modules by a path relative to the importing file, starting with ./ or ../ and naming a .mjs or .js file, read in the script's folder and the folders below it (a bare name, a URL or a path that leads above the script's folder ends the run with an error naming it); every module is read, parsed and linked before any runs, so a syntax error, a missing file or an import of a name a module does not export ends the run with no code run; each module runs once, after the modules it imports, except that in a cycle of imports a module does not wait for one that is still waiting for its own imports, and reading a binding of that module before it is initialized throws a ReferenceError; an import reads the exporting module's binding as it is at that moment; its top-level names stay in the module, this is undefined, it has no preprocessor lines, and import() is a syntax error; module files count against the limits of included files. Before a script that does not run as a module runs, its 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; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns 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 ), @@ -173,6 +173,7 @@ fn run(s: &mut Session, p: &Value) -> Result { } let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; + let module = switch_or(p, "module", script::include::module_script(path), "script.run")?; let mut checked_real = None; let text = match (path, source) { (Some(""), None) => return Err(param("`path` is empty")), @@ -217,6 +218,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, + module, }; let name = s.script_start(request)?; if s.script_frames { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index abc7fa0740..cd45cccaaf 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -640,6 +640,15 @@ impl ScriptScope { /// The real path of the file at `path` and its first `max` bytes, at most. pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { + match self.read_unless(path, max, |_| false)? { + (real, Some(bytes)) => Ok((real, bytes)), + (_, None) => Err(ScriptRead::Failed("the file was not read".to_string())), + } + } + + /// [`ScriptScope::read`], except that a file whose real path `known` accepts is not opened: + /// → its real path and no bytes. + pub(crate) fn read_unless(&self, path: &Path, max: usize, known: impl Fn(&Path) -> bool) -> Result<(PathBuf, Option>), ScriptRead> { use std::io::Read; if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { return Err(ScriptRead::Refused); @@ -655,6 +664,9 @@ impl ScriptScope { if !self.allows(&real) { return Err(ScriptRead::Refused); } + if known(&real) { + return Ok((real, None)); + } let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; let meta = file.metadata().map_err(|e| ScriptRead::Failed(e.to_string()))?; if !meta.is_file() { @@ -672,7 +684,7 @@ impl ScriptScope { if std::fs::canonicalize(path).ok().as_ref() != Some(&real) { return Err(ScriptRead::Refused); } - Ok((real, bytes)) + Ok((real, Some(bytes))) } /// The first granted folder, as people read it (`None` for a script given as text). @@ -891,6 +903,21 @@ mod tests { p.to_string_lossy().into_owned() } + /// A file the caller already has is not opened: its size is not checked and no byte is read. + #[test] + fn a_known_script_file_is_not_read_again() { + let (base, _) = folders("known"); + std::fs::write(base.join("in/big.js"), "x".repeat(64)).unwrap(); + let scope = ScriptScope::of_folder(&base.join("in")); + let path = base.join("in/big.js"); + assert_eq!(scope.read(&path, 16).map(|(_, b)| b.len()), Err(ScriptRead::TooLarge)); + let real = std::fs::canonicalize(&path).unwrap(); + assert_eq!(scope.read_unless(&path, 16, |r| r == real), Ok((real.clone(), None))); + assert_eq!(scope.read_unless(&path, 64, |_| false).map(|(_, b)| b.map(|b| b.len())), Ok(Some(64))); + assert_eq!(scope.read_unless(&base.join("outside/secret.svg"), 64, |_| true), Err(ScriptRead::Refused)); + let _ = std::fs::remove_dir_all(base); + } + /// The roots both grant: the deeper of two nested roots, nothing for roots apart, and a kind /// only one grants is not granted. #[test] diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 8de325cb70..bc91914f0b 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -249,8 +249,9 @@ pub(crate) fn module_script(path: Option<&str>) -> bool { } /// What names the file at the real path `real` among a run's modules: on Unix its device and file -/// number, so two paths to one file give one module; elsewhere its path, in lowercase on Windows, -/// whose file names ignore letter case. +/// number, so two paths to one file give one module; elsewhere its real path, which on Windows +/// spells each name in the letter case the folder stores it in, so two spellings of one file in a +/// folder that ignores case give one module and two files in a folder that does not stay two. fn module_key(real: &Path) -> String { #[cfg(unix)] { @@ -259,8 +260,13 @@ fn module_key(real: &Path) -> String { return format!("{}:{}", m.dev(), m.ino()); } } - let shown = display(real).to_string(); - if cfg!(windows) { shown.to_lowercase() } else { shown } + display(real).to_string() +} + +/// The names of the folders from `root` down to `dir`, both real paths, or `None` when `dir` is +/// not `root` or below it, or has a name that is not Unicode. +fn names_below(root: &Path, dir: &Path) -> Option> { + dir.strip_prefix(root).ok()?.components().map(|c| c.as_os_str().to_str().map(str::to_string)).collect() } /// The names of a module specifier's path: one that starts with `./` or `../`, uses `/` between @@ -380,6 +386,11 @@ impl Files { } } + /// Makes the run's files read ECMAScript 2015, as a module run given as text does. + pub(crate) fn read_es2015(&mut self) { + self.es2015 = true; + } + /// The module `text`, the script's own, as a source of one file. → its key and the source. pub(crate) fn module_entry(&mut self, text: &str) -> Result<(String, Expanded), Failure> { self.bytes = self.bytes.saturating_add(text.len()); @@ -417,30 +428,38 @@ impl Files { if self.probes > MAX_PROBES { return Err(LoadError::Range(format!("module search limit ({MAX_PROBES} paths) reached"))); } - let candidate = path.iter().fold(root, |p, name| p.join(name)); - let (real, bytes) = match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) { + let candidate = path.iter().fold(root.clone(), |p, name| p.join(name)); + // Another path to a module already read gives that module: the file is not read again, and + // its text is not counted again. + let loaded = &self.module_dirs; + let read = self.scope.read_unless(&candidate, crate::script::MAX_SOURCE_BYTES, |real| loaded.contains_key(&module_key(real))); + let (real, bytes) = match read { Ok(found) => found, Err(ScriptRead::Missing) => return Err(LoadError::Other(format!("module file not found: {specifier}"))), Err(ScriptRead::Refused) => return Err(LoadError::Other(format!("script file read refused: {specifier}"))), Err(ScriptRead::TooLarge) => return Err(LoadError::Range(format!("script file is too large: {specifier}"))), Err(ScriptRead::Failed(e)) => return Err(LoadError::Other(format!("cannot read script file {specifier}: {e}"))), }; + let key = module_key(&real); + let Some(bytes) = bytes else { + self.module_paths.insert(relative, key.clone()); + return Ok((key, None)); + }; if self.bytes.saturating_add(bytes.len()) > MAX_TOTAL_BYTES { return Err(LoadError::Range("script source limit reached (32 MiB)".to_string())); } - self.bytes += bytes.len(); - let key = module_key(&real); - self.module_paths.insert(relative, key.clone()); - if self.module_dirs.contains_key(&key) { - return Ok((key, None)); - } if self.files >= MAX_FILES { return Err(LoadError::Range(format!("module file limit ({MAX_FILES}) reached"))); } - self.files += 1; let text = decode(&bytes, specifier).map_err(LoadError::Other)?; + self.bytes += bytes.len(); + self.files += 1; + self.module_paths.insert(relative, key.clone()); + // The module's relative imports start from the folder the file is in, whichever path to it + // was read first; the path as written stands in when that folder is not below the script's. path.pop(); - self.module_dirs.insert(key.clone(), path); + let dir = folder_of(&real).and_then(|d| names_below(&root, &d)).unwrap_or(path); + self.module_dirs.insert(key.clone(), dir); let map = SourceMap { files: vec![display(&real)], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; Ok((key, Some((text, map)))) } @@ -483,12 +502,20 @@ impl Files { self.expand(shown, dir, text, true) } - /// The file `path` names for `$.evalFile`, relative to the file being run now, read and with its - /// preprocessor lines read. It becomes the file being run until [`Files::end_eval`]. - pub(crate) fn eval_file(&mut self, path: &str) -> Result { + /// The folder of the module `key` ([`Files::module`] gave it), from the script's folder. + pub(crate) fn module_dir(&self, key: &str) -> Option { + let names = self.module_dirs.get(key)?; + let root = self.frames.first().and_then(|f| f.dir.clone())?; + Some(names.iter().fold(root, |p, name| p.join(name))) + } + + /// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder + /// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It + /// becomes the file being run until [`Files::end_eval`]. + pub(crate) fn eval_file(&mut self, path: &str, module_dir: Option) -> Result { let current = self.frames.last().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); let fail = |kind, message: String| Failure { kind, message, index: 0, file: current.clone(), line: 0, column: 0 }; - let dir = self.frames.last().and_then(|f| f.dir.clone()); + let dir = module_dir.or_else(|| self.frames.last().and_then(|f| f.dir.clone())); let (real, bytes) = self.open(path, dir.as_deref(), false).map_err(|(kind, message)| fail(kind, message))?; let text = self.admit(&real, bytes, path).map_err(|(kind, message)| fail(kind, message))?; let shown = display(&real); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index e318c0abb6..101cdc2bac 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -202,6 +202,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 script runs as an ECMAScript 2015 module, as a `.mjs` file does ([`include::module_script`]). + pub module: bool, } thread_local! { @@ -777,6 +779,9 @@ struct Host { script_map: RefCell, /// The same for each source `$.evalFile` gave, in order. eval_maps: RefCell>, + /// The module key ([`include::Files::module`]) of each of [`Host::eval_maps`] that is a + /// module's, by its index there. + module_maps: RefCell>, /// The file, line and column of each error `$.evalFile` raised for a file it could not run, in /// order: the error's mark ([`HostError::Marked`]) is its index. eval_failures: RefCell, u32, u32)>>, @@ -932,6 +937,18 @@ impl Host { } } + /// The folder of the module whose source has `tag`, when it is a module the script imported + /// (not the script itself, a file `$.evalFile` gave, or code from another run). + fn module_dir_at(&self, tag: u32) -> Option { + let script = self.script_tag.get(); + if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE { + return None; + } + let n = tag.checked_sub(script).filter(|n| *n > 0)?; + let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?; + self.files.borrow().module_dir(&key) + } + /// Adds a line to the run's console and, during a slice, to the session's. fn line(&self, entry: console::Entry, cut: bool) { let line = console::ConsoleLine { run: self.run, name: self.name.clone(), entry }; @@ -1436,6 +1453,7 @@ fn dollar_object(link: &Link, info: dollar::RunInfo, localization: &Rc) -> std::result::Result { +/// run (for a call in a module the script imported, that module's file), with its preprocessor +/// lines read, which the interpreter then runs. `timeout`, in milliseconds, is taken and not +/// waited on: the file is read at once. `args` starts with the call's place, as +/// [`HostItem::Evaluator`] gives it with `site`. +fn eval_file(host: &Host, mut args: Vec) -> std::result::Result { + let tag = match args.first() { + Some(Data::Number(n)) if args.len() >= 3 => *n as u32, + _ => vectorcraft_js::UNKNOWN_SOURCE, + }; + args.drain(..3.min(args.len())); + let module_dir = host.module_dir_at(tag); let Some(Data::String(path)) = args.first().filter(|p| !matches!(p, Data::String(s) if s.is_empty())) else { return Err(HostError::Type(EVAL_NO_PATH.to_string())); }; @@ -1466,7 +1492,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { format!("{}:{}:{}: {}", f.file, f.line, f.column, f.message) } else { f.message }; let error = match f.kind { include::FailKind::Limit => HostError::Abort(message), @@ -1582,7 +1608,10 @@ fn explained(e: &RunError) -> String { fn load_module(host: &Host, referrer: &str, specifier: &str) -> std::result::Result { let (key, read) = host.files.borrow_mut().module(referrer, specifier)?; let source = read.map(|(text, map)| { - host.eval_maps.borrow_mut().push(map); + let mut maps = host.eval_maps.borrow_mut(); + host.module_maps.borrow_mut().insert(maps.len(), key.clone()); + maps.push(map); + drop(maps); host.disk.borrow_mut().saw_code(&text.encode_utf16().collect::>()); text }); @@ -1951,9 +1980,12 @@ impl Session { self.script_stop.clear(); self.script_report = None; let mut files = include::Files::new(request.file.as_deref(), request.checked_real, include::Files::jsinclude_env()); - // A `.mjs` script is a module, with no preprocessor lines; `module_key` names it among the - // modules it imports. - let (expanded, module_key) = if include::module_script(request.file.as_deref()) { + if request.module { + files.read_es2015(); + } + // A module (a `.mjs` file, or a script run with `module`) has no preprocessor lines; + // `module_key` names it among the modules it imports. + let (expanded, module_key) = if request.module { match files.module_entry(&request.source) { Ok((key, expanded)) => (Ok(expanded), Some(key)), Err(f) => (Err(f), None), @@ -1992,7 +2024,7 @@ impl Session { let fresh = realm.is_none(); // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read // code the way the script does. - let es2015 = include::es2015_script(request.file.as_deref()); + let es2015 = request.module || include::es2015_script(request.file.as_deref()); let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; let strict = options.strict; // A kept engine reads each run's code the way that run's script does. @@ -2058,6 +2090,7 @@ impl Session { files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), + module_maps: RefCell::default(), eval_failures: RefCell::default(), script_tag: Cell::new(vectorcraft_js::UNKNOWN_SOURCE), report_name: Arc::from(name.as_str()), diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..e64f7c3ad2 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(), + module: false, }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs index 9727abb927..0dec7ea7da 100644 --- a/crates/engine/src/tests/script_modules.rs +++ b/crates/engine/src/tests/script_modules.rs @@ -225,3 +225,78 @@ fn script_module_is_listed_and_taken_by_path() { assert!(r.is_err()); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn script_module_is_chosen_by_the_module_param() { + let mut s = Session::new(); + let r = s.execute("script.run", &json!({"source": "export var a = 1;\nvc.log([a, this === undefined]);", "module": true})).unwrap(); + assert_eq!(r["log"], json!([[1, true]])); + // A source run as a module imports no files. + let r = s.execute("script.run", &json!({"source": "import { b } from './b.mjs';", "module": true})); + assert!(r.is_err()); + assert!(message(s.script_report().unwrap()).contains("./b.mjs"), "{:?}", s.script_report()); + let r = s.execute("script.run", &json!({"source": "export var a = 1;", "module": "yes"})); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{r:?}"); + // `module: false` runs a .mjs file as a script, where `export` is a syntax error. + let base = folder("param"); + let main = base.join("main").join("main.mjs"); + write(&main, "export var a = 1;"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy(), "module": false})); + assert!(r.is_err()); + assert_eq!(s.script_report().unwrap()["kind"], "syntax"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_read_again_through_another_path_is_not_counted_again() { + let base = folder("budget"); + // 7 MiB, under the 8 MiB a file may have; five reads of it would pass the 32 MiB of a run. + let big = format!("export var v = 1;\n//{}", "x".repeat(7 * 1024 * 1024)); + write(&base.join("main/lib/big.mjs"), &big); + let mut text = String::new(); + for i in 0..5 { + if !link_folder(&base.join("main/lib"), &base.join(format!("main/l{i}"))) { + eprintln!("skipped: a folder link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + text.push_str(&format!("import {{ v as v{i} }} from './l{i}/big.mjs';\n")); + } + text.push_str("vc.log(v0 + v4);"); + let r = run(&base, &text); + assert_eq!(r.map(|r| r["log"].clone()).ok(), Some(json!([2]))); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_imports_are_read_from_the_folder_the_file_is_in() { + let base = folder("realdir"); + write(&base.join("main/real/user.mjs"), "import { d } from './dep.mjs';\nexport const got = d;"); + write(&base.join("main/real/dep.mjs"), "export const d = 'real';"); + write(&base.join("main/other/dep.mjs"), "export const d = 'other';"); + #[cfg(unix)] + let linked = std::os::unix::fs::symlink(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok(); + #[cfg(windows)] + let linked = std::os::windows::fs::symlink_file(base.join("main/real/user.mjs"), base.join("main/other/user.mjs")).is_ok(); + #[cfg(not(any(unix, windows)))] + let linked = false; + if !linked { + eprintln!("skipped: a file link can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let r = run(&base, "import { got } from './other/user.mjs';\nvc.log(got);").unwrap(); + assert_eq!(r["log"], json!(["real"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn script_module_eval_file_reads_beside_the_module_that_calls_it() { + let base = folder("evalfile"); + write(&base.join("main/helper.jsx"), "'top'"); + write(&base.join("main/sub/helper.jsx"), "'sub'"); + write(&base.join("main/sub/m.mjs"), "export const got = $.evalFile('helper.jsx');"); + let r = run(&base, "import { got } from './sub/m.mjs';\nvc.log([got, $.evalFile('helper.jsx')]);").unwrap(); + assert_eq!(r["log"], json!([["sub", "top"]])); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a5d39c0b06..ce1e66f6d1 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -483,7 +483,11 @@ pub enum ImportName { /// A module a module imports or re-exports from: the specifier as written and where it stands. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ModuleRequest { + /// The specifier as text, with each unpaired surrogate written as U+FFFD. pub specifier: String, + /// The specifier's string value, code unit for code unit (ECMA-262 2015 section 15.2.1.16, + /// ModuleRequests). It may hold an unpaired surrogate, which no host path can name. + pub units: Vec, pub span: Span, } diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 537752b9fe..eae7ae1924 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -250,8 +250,10 @@ impl<'a> FnCompiler<'a> { let mut seen = HashSet::new(); // The `let` and `const` names and the block functions of each statement list and loop the // walk enters, with the index of the one around it; the body's are first, and its - // functions are var-scoped. - let mut scopes: Vec<(Option, HashSet, HashSet)> = vec![(None, self.lexical_names(body), HashSet::new())]; + // functions are var-scoped. Only Annex B's block functions read them, so without + // [`crate::Options::es2015`] none is collected. + let top = if self.es2015 { self.lexical_names(body) } else { HashSet::new() }; + let mut scopes: Vec<(Option, HashSet, HashSet)> = vec![(None, top, HashSet::new())]; let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect(); let mut add_var = |out: &mut Hoisted, k: Key| { if seen.insert(k.clone()) { @@ -285,7 +287,7 @@ impl<'a> FnCompiler<'a> { } } Stmt::Block(list) => { - let s = enter(self.lexical_names(list), self.block_function_names(list)); + let s = if inner { enter(self.lexical_names(list), self.block_function_names(list)) } else { scope }; work.extend(list.iter().rev().map(|&st| (st, nested || inner, s))); } Stmt::If { consequent, alternate, .. } => { @@ -293,7 +295,7 @@ impl<'a> FnCompiler<'a> { // (Annex B.3.4). for &branch in alternate.iter().chain(std::iter::once(consequent)) { let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_))); - let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope }; + let s = if alone && inner { enter(HashSet::new(), HashSet::new()) } else { scope }; work.push((branch, nested || inner, s)); } } @@ -322,23 +324,27 @@ impl<'a> FnCompiler<'a> { work.push((*body, nested || inner, s)); } Stmt::Switch { cases, .. } => { - let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect(); - let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect(); - let s = enter(names, funcs); + let s = if inner { + let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect(); + let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect(); + enter(names, funcs) + } else { + scope + }; for case in cases.iter().rev() { work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s))); } } Stmt::Try { block, handler, finalizer } => { if let Some(f) = finalizer { - let s = enter(self.lexical_names(f), self.block_function_names(f)); + let s = if inner { enter(self.lexical_names(f), self.block_function_names(f)) } else { scope }; work.extend(f.iter().rev().map(|&st| (st, nested || inner, s))); } if let Some(h) = handler { - let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body)); + let s = if inner { enter(self.lexical_names(&h.body), self.block_function_names(&h.body)) } else { scope }; work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s))); } - let s = enter(self.lexical_names(block), self.block_function_names(block)); + let s = if inner { enter(self.lexical_names(block), self.block_function_names(block)) } else { scope }; work.extend(block.iter().rev().map(|&st| (st, nested || inner, s))); } Stmt::Expr(_) @@ -921,8 +927,12 @@ impl<'a> FnCompiler<'a> { fn switch_stmt(&mut self, id: StmtId, labels: Vec) -> CResult<()> { let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") }; self.expr(*discriminant)?; - let all: Vec = cases.iter().flat_map(|c| c.body.iter().copied()).collect(); - let scope = self.list_scope(&all, true)?; + let scope = if self.es2015 { + let all: Vec = cases.iter().flat_map(|c| c.body.iter().copied()).collect(); + self.list_scope(&all, true)? + } else { + None + }; if let Some(scope) = scope { self.emit(Op::PushBlock(scope)); self.env_depth += 1; diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index 0173fb2d6c..07032c6506 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -97,8 +97,16 @@ fn redeclarations_and_bad_declarations_are_syntax_errors() { syntax("'use strict'; { function f() {} function f() {} }"); syntax("for (let x = 1 in {}) {}"); syntax("if (1) let x = 1;"); + // No statement starts with `let [`, in a statement list or in the body of an `if` or a loop. + for body in ["if (true) let[0];", "if (false) ; else let[0];", "while (false) let[0];", "for (;false;) let[0];", "lbl: let[0];"] { + syntax(&format!("var let = [1]; {body}")); + } // Outside strict mode code `let` is still a name where no declaration can start. truth("var let = 3; let === 3"); + truth("var let = [1]; var r; if (true) (let[0]); if (true) r = let[0]; r === 1"); + truth("var let = [2]; if (true) let\n; let.length === 1"); + // ECMAScript 5.1 reads it as a property read. + assert_eq!(Realm::new().run("var let = [1]; if (true) let[0];"), Ok(JsValue::Number(1.0))); truth("{ function f() { return 1; } function f() { return 2; } } f() === 2"); } @@ -167,7 +175,7 @@ fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() { assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}"); assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0))); let restricted = realm.run("let undefined = 1;"); - assert!(restricted.is_err(), "{restricted:?}"); + assert!(is_thrown(&restricted, "SyntaxError"), "{restricted:?}"); } #[test] @@ -269,8 +277,14 @@ fn a_global_var_stops_a_later_let_even_on_a_configurable_property() { assert!(is_thrown(&realm.run("let z;"), "SyntaxError")); assert_eq!(realm.run("delete z"), Ok(JsValue::Bool(true))); assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0))); + // Deleting the global object's property, not the variable, leaves the name declared + // (ECMA-262 2015 section 8.1.1.4.7 runs only for `delete w`). assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true))); - assert_eq!(realm.run("let w = 4; w"), Ok(JsValue::Number(4.0))); + let after_property = realm.run("let w = 4; w"); + assert!(is_thrown(&after_property, "SyntaxError"), "{after_property:?}"); + assert_eq!(realm.run("(0, eval)('var v = 1'); with (this) delete v"), Ok(JsValue::Bool(true))); + let after_with = realm.run("let v = 4; v"); + assert!(is_thrown(&after_with, "SyntaxError"), "{after_with:?}"); } #[test] @@ -343,6 +357,17 @@ fn arrow_functions_cannot_be_constructed() { truth("((a, b) => 0).length === 2"); } +#[test] +fn an_arrow_functions_length_is_configurable_and_read_only() { + truth( + "var d = Object.getOwnPropertyDescriptor((a) => a, 'length'); \ + d.configurable && !d.writable && !d.enumerable && d.value === 1", + ); + truth("var f = (a, b) => 0; delete f.length && !f.hasOwnProperty('length')"); + // Other functions keep their attributes. + truth("var d = Object.getOwnPropertyDescriptor(function (a) {}, 'length'); !d.configurable && !d.writable && !d.enumerable"); +} + #[test] fn bad_arrow_functions_are_syntax_errors() { syntax("var f = x\n=> x;"); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index f158f45a0f..34ac97155d 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -186,7 +186,7 @@ pub(crate) enum Func { Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, - Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, + Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc, site: bool }, Bound { target: ObjId, this: Value, args: Rc<[Value]> }, } diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index 4c18d0f76f..156849035f 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -148,11 +148,14 @@ pub enum HostItem { /// that is not a string is the call's result. `end` is called when the source has run, /// normally or not. Each source given has the next tag of [`crate::Realm::error_source`], /// from 1. `strict_writes`, called after `source`, gives [`crate::Realm::set_strict_writes`] - /// for that source alone; with `None` it takes the calling code's. + /// for that source alone; with `None` it takes the calling code's. With `site`, `source` is + /// given the [`CallSite`] of the code that calls it first, as the three numbers its source + /// tag, line and column, and the arguments after them. Evaluator { source: HostFunction, end: Rc, strict_writes: Rc Option>, + site: bool, }, /// A read-only property that reads the interpreter's own state. Script(ScriptItem), @@ -414,7 +417,8 @@ impl Interp { /// source it gives as global code, as an indirect `eval` does, giving that code's completion /// value. A result that is not a string is given to the script as it is. `end` is called once /// the source has run, normally or not. `strict_writes` gives the source's - /// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. + /// [`crate::bytecode::Source::strict_writes`], or `None` for the calling code's. With `site`, + /// `f` is given the calling code's [`CallSite`] before the arguments. pub(crate) fn call_evaluator( &mut self, f: &crate::heap::DataFn, @@ -422,8 +426,13 @@ impl Interp { strict_writes: &Rc Option>, name: &Rc, args: &[Value], + site: bool, ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let caller = site.then(|| self.call_site()); + let mut data = self.read_args(name, args, &ArgRead::Data)?; + if let Some(caller) = caller { + data.splice(0..0, site_data(caller)); + } let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -586,9 +595,9 @@ impl Interp { HostItem::Converted(list, f) => { Prop::Data { value: Value::Object(self.host_function(f, &full, ArgRead::Each(list.into()))), flags: ENUMERABLE } } - HostItem::Evaluator { source, end, strict_writes } => { + HostItem::Evaluator { source, end, strict_writes, site } => { let proto = self.intrinsics.function_proto; - let func = Func::Eval { f: source, end, strict_writes, name: full.into() }; + let func = Func::Eval { f: source, end, strict_writes, name: full.into(), site }; let f = self.heap.alloc_object(Object::new(Class::Function(func), Some(proto))); Prop::Data { value: Value::Object(f), flags: ENUMERABLE } } diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 21cd2c0bc5..2df62d419f 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -284,7 +284,7 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() { Ok(Data::Number(f64::from(s.line))) }); let source: HostFunction = Rc::new(|_| Ok(Data::String("\n\nfunction inEval() { return host.site; }".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("site".into(), HostItem::SiteGetter(site)), ("load".into(), load)]).unwrap(); r.run("function early() {\n return host.site;\n}\nhost.load();").unwrap(); let first = r.script_tag(); @@ -306,6 +306,31 @@ fn a_site_getter_is_told_where_the_code_that_reads_it_is() { assert_eq!(seen.borrow().first().map(|s| s.source), Some(r.script_tag())); } +/// An evaluator made with `site` is given the place of the code that calls it before its +/// arguments; one made without it is given only the arguments. +#[test] +fn an_evaluator_with_site_is_told_where_it_is_called() { + let mut r = realm(10_000_000); + let given: Rc>>> = Rc::default(); + let evaluator = |site: bool| { + let log = given.clone(); + let source: HostFunction = Rc::new(move |a| { + log.borrow_mut().push(a); + Ok(Data::String("1".into())) + }); + HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site } + }; + r.define_host_object("host", vec![("at".into(), evaluator(true)), ("plain".into(), evaluator(false))]).unwrap(); + r.run("\n\n host.at('x');\nhost.plain('y');").unwrap(); + let tag = f64::from(r.script_tag()); + let given = given.borrow(); + assert_eq!(given.len(), 2, "{given:?}"); + assert_eq!(given[0].len(), 4, "{given:?}"); + assert_eq!((&given[0][..2], &given[0][3]), (&[Data::Number(tag), Data::Number(3.0)][..], &Data::String("x".into())), "{given:?}"); + assert!(matches!(given[0][2], Data::Number(c) if c >= 1.0), "{given:?}"); + assert_eq!(given[1], vec![Data::String("y".into())]); +} + #[test] fn a_text_function_takes_each_argument_as_string_gives_it() { let mut r = realm(1_000_000); @@ -658,7 +683,7 @@ fn a_converted_function_reads_each_argument_as_its_list_says() { fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unknown() { let mut r = realm(10_000_000); let source: HostFunction = Rc::new(|_| Ok(Data::String("\nthrow new Error('in eval')".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("load".into(), load)]).unwrap(); r.run("function late() { throw new Error('late'); }").unwrap(); assert!(r.run("host.load()").is_err()); @@ -680,7 +705,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() { let s = seen.clone(); r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("load".into(), load)]).unwrap(); let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); assert_eq!(out, JsValue::Number(49.0)); @@ -695,7 +720,7 @@ fn the_code_observer_sees_every_source_evaluated_at_run_time() { fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); let source: HostFunction = Rc::new(|_| Ok(Data::String("function inEval() { throw new Error('in eval'); }".into()))); - let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; r.define_host_object("host", vec![("load".into(), load)]).unwrap(); assert_eq!(r.script_tag(), UNKNOWN_SOURCE, "no script yet"); r.run("function late() { throw new Error('late'); }\nhost.load(); host.load();").unwrap(); @@ -728,7 +753,7 @@ fn an_evaluators_source_takes_fuel_before_it_is_parsed() { let ends = Rc::new(Cell::new(0)); let ended = ends.clone(); let source: HostFunction = Rc::new(|_| Ok(Data::String(format!("{}7", " ".repeat(1 << 17))))); - let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None) }; + let item = HostItem::Evaluator { source, end: Rc::new(move || ended.set(ended.get() + 1)), strict_writes: Rc::new(|| None), site: false }; let mut r = realm(10_000); r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); let e = r.run("host.evaluate()").unwrap_err(); @@ -749,7 +774,7 @@ fn an_evaluators_whole_source_must_fit_in_the_heap_before_it_is_parsed() { // The source does not parse, so a parse would throw a syntax error instead. let n = (1 << 17) + 1; let source: HostFunction = Rc::new(move |_| Ok(Data::String(format!("{}(", " ".repeat(n - 1))))); - let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + let item = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None), site: false }; let mut r = realm(1_000_000); r.define_host_object("host", vec![("evaluate".into(), item)]).unwrap(); r.interp().collect_for_room(); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ae755f3aa3..a3b62411e1 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1387,7 +1387,17 @@ impl Interp { } _ => return internal("not a declarative environment"), }, - Resolved::Obj { object, .. } => self.delete(object, &name, false)?, + Resolved::Obj { object, with_this } => { + let deleted = self.delete(object, &name, false)?; + // A deleted global variable no longer stops a `let` or `const` of its name: the + // global environment's DeleteBinding drops it from its var names (ECMA-262 2015 + // section 8.1.1.4.7). Deleting the global object's property by any other route + // leaves the name recorded. + if deleted && !with_this && object == self.global { + self.global_vars.remove(&name); + } + deleted + } }; self.push(Value::Bool(result)) } @@ -1532,11 +1542,16 @@ impl Interp { /// [[GetProperty]]: the property found on the object or its prototype chain. pub(crate) fn find_property(&self, id: ObjId, k: &[u16]) -> JsResult> { + Ok(self.find_property_on(id, k)?.map(|(_, p)| p)) + } + + /// [`Self::find_property`], with the object on the prototype chain that has the property. + fn find_property_on(&self, id: ObjId, k: &[u16]) -> JsResult> { let mut cur = Some(id); let mut steps = 0usize; while let Some(o) = cur { if let Some(p) = self.get_own_property(o, k)? { - return Ok(Some(p)); + return Ok(Some((o, p))); } cur = self.object(o)?.proto; steps += 1; @@ -1553,10 +1568,14 @@ impl Interp { /// [[Get]] starting at `start`, with `receiver` as `this` for a getter. pub(crate) fn get_from(&mut self, start: ObjId, k: &[u16], receiver: &Value) -> JsResult { + let found = self.find_property_on(start, k)?; // A module's export read before the module ran is in its temporal dead zone (ECMA-262 - // 2015 section 9.4.6.8). - self.check_namespace_export(start, k)?; - match self.find_property(start, k)? { + // 2015 section 9.4.6.8), whether the read starts at the namespace object or reaches it + // through a prototype chain. + if let Some((holder, _)) = &found { + self.check_namespace_export(*holder, k)?; + } + match found.map(|(_, p)| p) { None | Some(Prop::Accessor { get: None, .. }) => Ok(Value::Undefined), Some(Prop::Data { value, .. }) => Ok(value), Some(Prop::Accessor { get: Some(g), .. }) => self.call(&Value::Object(g), receiver, &[]), @@ -1863,8 +1882,26 @@ impl Interp { Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), None => {} } - let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { + let mut inherited = None; + let mut cur = self.object(id)?.proto; + let mut steps = 0usize; + while let Some(o) = cur { + // A write that reaches a module namespace object on the prototype chain is refused + // there too: its [[Set]] returns false for every key. + if matches!(self.object(o)?.class, Class::ModuleNamespace(_)) { + return self.reject(throw, &k, "a module namespace object is read-only"); + } + if let Some(p) = self.get_own_property(o, &k)? { + inherited = Some(p); + break; + } + cur = self.object(o)?.proto; + steps += 1; + if steps > 1_000_000 { + return internal("prototype chain too long"); + } + } + match inherited { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), @@ -1930,12 +1967,6 @@ impl Interp { match self.get_own_property(id, k)? { None => Ok(true), Some(p) if p.configurable() => { - // A deleted global variable no longer stops a `let` or `const` of its name - // (ECMA-262 2015 section 8.1.1.4.7), and the names kept are never more than the - // global object's properties. - if id == self.global { - self.global_vars.remove(k); - } let o = self.object_mut(id)?; o.props.remove(k); if let Class::Arguments(map) = &mut o.class @@ -2216,7 +2247,10 @@ impl Interp { let arrow = code.arrow; let self_name = code.self_name.clone(); let f = self.heap.alloc_object(Object::new(Class::Function(Func::Closure { code, env }), Some(proto))); - self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + // An arrow function's `length` is configurable (ECMA-262 2015 section 9.2.4, + // FunctionInitialize); the other forms keep their earlier attributes. + let length_flags = if arrow { CONFIGURABLE } else { 0 }; + self.define(f, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: length_flags })?; // An arrow function has no `prototype` and cannot be constructed (section 14.2.16). if arrow { return Ok(f); @@ -2670,14 +2704,9 @@ impl Interp { // listed or their bytes reserved must not free it. let saved = self.temp_roots.len(); self.temp_roots.push(Value::Object(o)); - // Listing a namespace object's exports reads each one (ECMA-262 2015 section 9.4.6.5). + // Listing a namespace object's exports does not read them (ECMA-262 2015 section + // 9.4.6.11, [[Enumerate]]), so an export still in its temporal dead zone is listed. let keys = self.enumerable_keys(o).and_then(|keys| { - for k in &keys { - self.check_namespace_export(o, k)?; - } - Ok(keys) - }); - let keys = keys.and_then(|keys| { let bytes = keys.iter().map(|k| string_bytes(k.len())).sum::(); self.reserve_heap(bytes)?; self.heap.bytes = self.heap.bytes.saturating_add(bytes); @@ -2780,8 +2809,8 @@ impl Interp { // keeps itself reachable. return Ok(Prepared::Done(self.call_data(&f, &name, &args, &read)?)); } - Func::Eval { f, end, strict_writes, name } => { - return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args)?)); + Func::Eval { f, end, strict_writes, name, site } => { + return Ok(Prepared::Done(self.call_evaluator(&f, &end, &strict_writes, &name, &args, site)?)); } Func::Host { f: host, .. } => { let js_args: Vec = args.iter().map(|v| self.to_js_value(v)).collect(); @@ -3435,7 +3464,8 @@ impl Interp { /// uninitialized. → the environment it runs in and the outer one. Both stay in the temporary /// roots for the caller to remove. pub(crate) fn instantiate_module(&mut self, code: &Rc) -> JsResult<(EnvId, EnvId)> { - self.charge_code(code, declaration_bytes(code).saturating_add(ENV_BYTES))?; + // The code itself was counted when the module was loaded ([`Self::hold_module_code`]). + self.reserve_heap(declaration_bytes(code).saturating_add(ENV_BYTES))?; let scope = self.global_lex; let env = self.heap.alloc_env(Env::Decl { bindings: PropMap::default(), outer: Some(scope) }); self.temp_envs.push(env); @@ -3501,6 +3531,24 @@ impl Interp { self.temp_envs.len() } + /// Counts a loaded module's code against the heap once, when the module is loaded, and keeps + /// it reachable until [`Self::drop_temp_codes`] drops it, so a collection while later modules + /// load counts it too. + pub(crate) fn hold_module_code(&mut self, code: &Rc) -> JsResult<()> { + self.charge_code(code, 0)?; + self.temp_codes.push(code.clone()); + Ok(()) + } + + pub(crate) fn temp_codes_mark(&self) -> usize { + self.temp_codes.len() + } + + /// Ends module linking: drops the modules' code held from `mark` on. + pub(crate) fn drop_temp_codes(&mut self, mark: usize) { + self.temp_codes.truncate(mark); + } + /// Keeps `v` reachable until [`Self::drop_temp_roots`] drops it. pub(crate) fn hold(&mut self, v: Value) { self.temp_roots.push(v); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 8f99275192..09fdc4b715 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -61,7 +61,10 @@ //! [`parse_module`] reads a module (section 15.2): strict mode code with those forms and `import` //! and `export` declarations at its top. [`Realm::start_module`] and [`Realm::run_module`] run a //! module and the modules it imports, which the host gives through a [`ModuleLoader`]: each module -//! once, after the modules it imports, with each import reading the exporting module's binding. +//! once, after the modules it imports, with each import reading the exporting module's binding. In +//! a cycle of imports, a module is marked as visited before the modules it imports are, so it does +//! not wait for a module that is still waiting for its own imports, and reading a binding of that +//! module before it is initialized throws a `ReferenceError`. //! Dynamic `import()` is a syntax error. #![forbid(unsafe_code)] diff --git a/crates/js/src/module.rs b/crates/js/src/module.rs index b706c280f5..e8147668cd 100644 --- a/crates/js/src/module.rs +++ b/crates/js/src/module.rs @@ -17,7 +17,7 @@ //! properties. `export *` passes on every name but `default`; a name two `export *` give from //! different bindings is left out of a namespace and is a `SyntaxError` to import. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use crate::ast::{ExportEntry, ImportName, ModuleInfo}; @@ -84,6 +84,11 @@ struct Record { /// The environment its code runs in and the outer one, once instantiated. envs: Option<(EnvId, EnvId)>, namespace: Option, + /// Each name the module exports itself or re-exports by name, with its entry in + /// `info.exports`. + explicit: HashMap, + /// The request each `export *` of the module names, in order. + stars: Vec, } /// Why a module run could not start. @@ -153,7 +158,19 @@ impl Graph<'_, '_> { Err(CompileError::Syntax(error)) => return Err(LinkFail::Syntax { tag, error }), Err(CompileError::Internal(m)) => return Err(LinkFail::Run(Abrupt::Internal(m))), }; - self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None }); + // The record keeps the code from here on, so the heap counts it from here on. + self.interp.hold_module_code(&code).map_err(LinkFail::Run)?; + let mut explicit = HashMap::new(); + let mut stars = Vec::new(); + for (i, e) in info.exports.iter().enumerate() { + match e { + ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { + explicit.entry(export_name.clone()).or_insert(i); + } + ExportEntry::Star { request, .. } => stars.push(*request), + } + } + self.records.push(Record { key: key_name.clone(), info, code, tag, requested: Vec::new(), envs: None, namespace: None, explicit, stars }); let index = self.records.len() - 1; self.by_key.insert(key_name, index); Ok(index) @@ -175,10 +192,21 @@ impl Graph<'_, '_> { let mut depths = vec![0usize]; let mut i = 0; while i < self.records.len() { - let requests: Vec<(String, u32)> = self.records[i].info.requests.iter().map(|r| (r.specifier.clone(), r.span.start)).collect(); + let requests: Vec<(String, bool, u32)> = self.records[i] + .info + .requests + .iter() + .map(|r| (r.specifier.clone(), char::decode_utf16(r.units.iter().copied()).all(|c| c.is_ok()), r.span.start)) + .collect(); let depth = depths.get(i).copied().unwrap_or(0); - for (specifier, offset) in requests { + for (specifier, text, offset) in requests { self.interp.use_fuel().map_err(LinkFail::Run)?; + // The host maps text to modules, and a specifier with an unpaired surrogate is not + // text, so it is refused here, as a host refuses a specifier it does not read. + if !text { + let message = format!("module specifier '{specifier}' is not valid text: it has an unpaired surrogate"); + return Err(self.fail_at(i, offset, ErrorType::Syntax, &message)); + } let referrer = self.records[i].key.clone(); let loaded = match (self.load)(&referrer, &specifier) { Ok(loaded) => loaded, @@ -247,29 +275,28 @@ impl Graph<'_, '_> { } self.interp.use_fuel().map_err(LinkFail::Run)?; seen.push((m, name.to_string())); - let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); - for e in &exports { - match e { - ExportEntry::Local { export_name, local, .. } if export_name == name => { - return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))); - } - ExportEntry::Indirect { export_name, request, import, .. } if export_name == name => { - let Some(t) = self.target(m, *request) else { return Ok(Ok(None)) }; - return match import { - ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))), - ImportName::Name(n) => self.resolve_export(t, n, seen), - }; - } - _ => {} + let Some(record) = self.records.get(m) else { return Ok(Ok(None)) }; + // The module's own export of the name, looked up in its index, comes before any `export *`. + let explicit = record.explicit.get(name).and_then(|&i| record.info.exports.get(i)); + match explicit { + Some(ExportEntry::Local { local, .. }) => return Ok(Ok(Some(Resolution::Binding { module: m, name: local.clone() }))), + Some(ExportEntry::Indirect { request, import, .. }) => { + let (request, import) = (*request, import.clone()); + let Some(t) = self.target(m, request) else { return Ok(Ok(None)) }; + return match import { + ImportName::Namespace => Ok(Ok(Some(Resolution::Namespace(t)))), + ImportName::Name(n) => self.resolve_export(t, &n, seen), + }; } + _ => {} } if name == "default" { return Ok(Ok(None)); } let mut star = None; - for e in &exports { - let ExportEntry::Star { request, .. } = e else { continue }; - let Some(t) = self.target(m, *request) else { continue }; + let stars = record.stars.clone(); + for request in stars { + let Some(t) = self.target(m, request) else { continue }; match self.resolve_export(t, name, seen)? { Err(Ambiguous) => return Ok(Err(Ambiguous)), Ok(None) => {} @@ -285,23 +312,32 @@ impl Graph<'_, '_> { /// GetExportedNames (section 15.2.1.16.2): the names module `m` exports, those of its /// `export *` modules but `default` included, each once. - fn exported_names(&mut self, m: usize, star: bool, visited: &mut Vec, names: &mut Vec) -> Result<(), LinkFail> { + fn exported_names( + &mut self, + m: usize, + star: bool, + visited: &mut Vec, + names: &mut Vec, + seen: &mut HashSet, + ) -> Result<(), LinkFail> { if visited.contains(&m) { return Ok(()); } visited.push(m); - let exports = self.records.get(m).map(|r| r.info.exports.clone()).unwrap_or_default(); - for e in &exports { + let count = self.records.get(m).map_or(0, |r| r.info.exports.len()); + for i in 0..count { self.interp.use_fuel().map_err(LinkFail::Run)?; + let Some(e) = self.records.get(m).and_then(|r| r.info.exports.get(i)) else { break }; match e { ExportEntry::Local { export_name, .. } | ExportEntry::Indirect { export_name, .. } => { - if !(star && export_name == "default") && !names.contains(export_name) { + if !(star && export_name == "default") && !seen.contains(export_name) { + seen.insert(export_name.clone()); names.push(export_name.clone()); } } ExportEntry::Star { request, .. } => { if let Some(t) = self.target(m, *request) { - self.exported_names(t, true, visited, names)?; + self.exported_names(t, true, visited, names, seen)?; } } } @@ -322,7 +358,7 @@ impl Graph<'_, '_> { return Ok(ns); } let mut names = Vec::new(); - self.exported_names(m, false, &mut Vec::new(), &mut names)?; + self.exported_names(m, false, &mut Vec::new(), &mut names, &mut HashSet::new())?; let mut resolved = Vec::new(); for name in names { if let Ok(Some(r)) = self.resolve_export(m, &name, &mut Vec::new())? { diff --git a/crates/js/src/module_tests.rs b/crates/js/src/module_tests.rs index 26f453b652..55c75139b4 100644 --- a/crates/js/src/module_tests.rs +++ b/crates/js/src/module_tests.rs @@ -105,6 +105,31 @@ fn a_namespace_object_has_the_exports_in_order_and_takes_no_writes() { assert_eq!(out, "alpha,default,mid,zeta|[object Module]|false|true|TypeError|TypeError|TypeError|2|true"); } +#[test] +fn a_write_that_reaches_a_namespace_through_a_prototype_is_refused() { + let m = "export var alpha = 1;"; + let out = run( + "import * as ns from './m.mjs'; + var o = Object.create(ns); + Object.defineProperty(o, 'own', { value: 1, writable: true }); + o.own = 2; + try { o.alpha = 5; } catch (e) { out.push(e.name); } + try { o.fresh = 5; } catch (e) { out.push(e.name); } + try { Object.create(o).alpha = 5; } catch (e) { out.push(e.name); } + out.push(o.own, Object.getOwnPropertyNames(o).join(), ns.alpha, o.alpha);", + &[("./m.mjs", m)], + ); + assert_eq!(out, "TypeError|TypeError|TypeError|2|own|1|1"); + // A script's sloppy write is ignored. + let mut realm = es(); + let out = run_with(&mut realm, "import * as ns from './m.mjs'; out.ns = ns;", &[("./m.mjs", m)], ModuleLimits::default()); + assert_eq!(out, (Ok(JsValue::Undefined), String::new())); + // A namespace has no prototype, so `hasOwnProperty` is called from `Object.prototype`. + let sloppy = "var o = Object.create(out.ns), own = Object.prototype.hasOwnProperty; o.alpha = 5; o.fresh = 5; \ + [own.call(o, 'alpha'), own.call(o, 'fresh'), o.alpha].join()"; + assert_eq!(realm.run(sloppy), Ok(JsValue::String("false,false,1".into()))); +} + #[test] fn a_namespace_takes_only_definitions_that_change_nothing() { let m = "export var a = 1;"; @@ -175,10 +200,14 @@ fn reading_an_import_before_its_module_ran_is_a_reference_error() { fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { let b = "import * as ns from 'main'; var tries = [() => ns.a, () => Object.keys(ns), () => Object.prototype.hasOwnProperty.call(ns, 'a'), () => Object.prototype.propertyIsEnumerable.call(ns, 'a'), - () => Object.getOwnPropertyDescriptor(ns, 'a'), () => { for (var k in ns) {} }, () => Object.isSealed(ns), () => Object.isFrozen(ns), - () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns)]; + () => Object.getOwnPropertyDescriptor(ns, 'a'), () => Object.isSealed(ns), () => Object.isFrozen(ns), + () => Object.seal(ns), () => Object.freeze(ns), () => Object.defineProperties({}, ns), () => JSON.stringify(ns), + () => Object.create(ns).a, () => Object.create(Object.create(ns)).a]; tries.forEach(function (f) { try { f(); out.push('no error'); } catch (e) { out.push(e.name); } }); - out.push('a' in ns, Object.getOwnPropertyNames(ns).join());"; + // Listing the export names reads none of them. + var names = []; + for (var k in ns) names.push(k); + out.push(names.join(), 'a' in ns, 'a' in Object.create(ns), Object.getOwnPropertyNames(ns).join());"; let mut realm = es(); let mut inner = loader(&[("./b.mjs", b)]); let mut load = |referrer: &str, specifier: &str| { @@ -186,8 +215,8 @@ fn a_namespace_export_its_module_has_not_initialized_is_a_reference_error() { }; let r = realm.run_module("main.mjs", "import './b.mjs'; export let a = 1;", ModuleLimits::default(), &mut load); assert_eq!(r, Ok(JsValue::Undefined)); - let errors = "ReferenceError|".repeat(12); - assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}true|a")))); + let errors = "ReferenceError|".repeat(13); + assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String(format!("{errors}a|true|true|a")))); } #[test] @@ -401,19 +430,79 @@ fn a_module_lists_what_it_imports_and_exports() { ); } +#[test] +fn a_specifier_with_an_unpaired_surrogate_parses_and_no_module_has_it() { + let src = "import './\\uD800.mjs'; import './\\uFFFD.mjs'; import './\\uDC00.mjs'; import './\\uD800.mjs';"; + let (_, info) = match parse_module(src, &Options::default()) { + Ok(p) => p, + Err(e) => panic!("{e:?}"), + }; + let units: Vec<&[u16]> = info.requests.iter().map(|r| r.units.as_slice()).collect(); + let dot = [u16::from(b'.'), u16::from(b'/')]; + let ext: Vec = ".mjs".encode_utf16().collect(); + let with = |u: u16| [&dot[..], &[u], &ext[..]].concat(); + assert_eq!(units, [with(0xD800).as_slice(), with(0xFFFD).as_slice(), with(0xDC00).as_slice()]); + assert_eq!(info.requests[0].specifier, "./\u{FFFD}.mjs"); + // The run stops when the module is to be loaded, before any module runs, and the loader is + // not asked for it. + let e = fails("out.push('ran'); import './\\uD800.mjs';", &[], "SyntaxError: module specifier './\u{FFFD}.mjs' is not valid text", ""); + assert_eq!(e.line, 1); +} + +#[test] +fn a_namespace_of_many_exports_lists_each_once_in_order() { + let names: Vec = (0..3000).rev().map(|i| format!("e{i}")).collect(); + let m: String = names.iter().map(|n| format!("export var {n} = '{n}';")).collect(); + let star = "export * from './m.mjs'; export var e5 = 'own';"; + let out = run( + "import * as ns from './star.mjs'; var k = Object.keys(ns); out.push(k.length, k[0], k[k.length - 1], ns.e5, ns.e2999);", + &[("./m.mjs", m.as_str()), ("./star.mjs", star)], + ); + assert_eq!(out, "3000|e0|e999|own|e2999"); +} + #[test] fn modules_survive_a_collection_while_they_link() { let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, Limits { heap_bytes: 64 << 20, ..Limits::default() }); assert!(realm.run("var out = []; var junk = []; for (var i = 0; i < 2000; i++) junk.push({ i: i }); junk = null;").is_ok()); let m = "export var v = 'kept'; export function f() { return v; }"; let mut load = loader(&[("./m.mjs", m)]); - let r = realm.run_module( + // A collection runs at every heap reservation while the modules load and link, before any + // of their code runs. + let before = realm.interp().heap.collections; + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true)); + let started = realm.start_module( "main.mjs", "import * as ns from './m.mjs'; import { f } from './m.mjs'; out.push(ns.f(), f());", ModuleLimits::default(), &mut load, ); - assert_eq!(r, Ok(JsValue::Undefined)); + crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false)); + assert_eq!(started, Ok(())); + assert!(realm.interp().heap.collections > before); + assert!(matches!(realm.advance(1_000_000), Ok(Progress::Done(JsValue::Undefined)))); realm.collect_garbage(); assert_eq!(realm.run("out.join('|')"), Ok(JsValue::String("kept|kept".into()))); } + +#[test] +fn the_heap_counts_each_module_from_when_it_loads() { + // Each module holds about 4 MB of code (its text and its string). The heap holds one of them, + // and not two, so the run stops while the second loads and never asks for the third. + let body = format!("export var v = '{}';", "x".repeat(1_000_000)); + let limits = || Limits { heap_bytes: 7 << 20, ..Limits::default() }; + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits()); + assert!(realm.run("var out = [];").is_ok()); + let one = run_with(&mut realm, "import { v } from './a.mjs'; out.push(v.length);", &[("./a.mjs", body.as_str())], ModuleLimits::default()); + assert_eq!(one, (Ok(JsValue::Undefined), "1000000".to_string())); + let mut realm = Realm::with_options(Options { es2015: true, ..Options::default() }, limits()); + let asked = std::cell::RefCell::new(Vec::new()); + let mut inner = loader(&[("./a.mjs", body.as_str()), ("./b.mjs", body.as_str()), ("./c.mjs", "")]); + let mut load = |referrer: &str, specifier: &str| { + asked.borrow_mut().push(specifier.to_string()); + inner(referrer, specifier) + }; + let r = realm.run_module("main.mjs", "import './a.mjs'; import './b.mjs'; import './c.mjs';", ModuleLimits::default(), &mut load); + assert!(matches!(r, Err(RunError { kind: RunErrorKind::Limit(LimitKind::Heap), .. })), "{r:?}"); + assert_eq!(*asked.borrow(), ["./a.mjs", "./b.mjs"]); +} diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index 28b7cd5f72..573bd06072 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -533,6 +533,11 @@ impl<'s> Parser<'s> { Ok(self.ast.push_stmt(Stmt::Empty, start)) } TokenKind::Keyword(k) => self.keyword_statement(*k, start), + // An expression statement cannot start with `let [` (ECMA-262 2015 section 13.5), so + // the body of an `if` or a loop cannot be a `let` declaration with a pattern either. + _ if self.es2015 && self.tok.ident() == Some("let") && !self.tok.escaped && self.peek().is_some_and(|t| t.is_punct(Punct::LBracket)) => { + Err(self.error_at_token(&self.tok, "a lexical declaration cannot stand here; put it in a block")) + } _ => { let expr = self.parse_expression(false)?; self.semicolon()?; diff --git a/crates/js/src/parser/module.rs b/crates/js/src/parser/module.rs index ec39092afb..ca5317ca4e 100644 --- a/crates/js/src/parser/module.rs +++ b/crates/js/src/parser/module.rs @@ -65,18 +65,18 @@ impl Parser<'_> { } /// A module specifier: a string literal, added to the module's requests once. → its index. + /// Any string value is a specifier here; the host decides which it can load. fn module_specifier(&mut self, info: &mut ModuleInfo) -> Result { let TokenKind::String(units) = &self.tok.kind else { return Err(self.error_at_token(&self.tok, format!("expected a module specifier string but found {}", describe(&self.tok)))); }; - let Ok(specifier) = String::from_utf16(units) else { - return Err(self.error_at_token(&self.tok, "a module specifier must be valid text")); - }; + let units = units.to_vec(); let span = self.bump()?.span; - if let Some(i) = info.requests.iter().position(|r| r.specifier == specifier) { + if let Some(i) = info.requests.iter().position(|r| r.units == units) { return Ok(i); } - info.requests.push(ModuleRequest { specifier, span }); + let specifier = String::from_utf16_lossy(&units); + info.requests.push(ModuleRequest { specifier, units, span }); Ok(info.requests.len() - 1) } diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 1765d6d9d1..0e648d4fcc 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -295,7 +295,7 @@ impl Realm { let interp = &mut self.interp; interp.evaluated = next_tag(interp.evaluated); self.script_tag = interp.evaluated; - let marks = (interp.temp_envs_mark(), interp.temp_roots_mark()); + let marks = (interp.temp_envs_mark(), interp.temp_roots_mark(), interp.temp_codes_mark()); let linked = crate::module::link(interp, key, source, self.script_tag, limits, load); let pushed = match linked { Ok(modules) => interp.push_module_frames(&modules).map_err(LinkFail::Run), @@ -304,6 +304,7 @@ impl Realm { let interp = &mut self.interp; interp.drop_temp_envs(marks.0); interp.drop_temp_roots(marks.1); + interp.drop_temp_codes(marks.2); match pushed { Ok(()) => Ok(()), Err(LinkFail::Syntax { tag, error }) => { diff --git a/crates/js/tests/test262.rs b/crates/js/tests/test262.rs index 3e3472d634..01d9e98665 100644 --- a/crates/js/tests/test262.rs +++ b/crates/js/tests/test262.rs @@ -50,7 +50,8 @@ use std::collections::HashSet; use std::path::{Path, PathBuf}; use vectorcraft_js::{ - JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, tokenize_module, + JsValue, Limits, LoadError, LoadedModule, ModuleLimits, Options, Progress, Punct, Realm, RunErrorKind, Token, TokenKind, parse, tokenize, + tokenize_module, }; /// A test file's metadata, from its `/*--- … ---*/` block. @@ -845,9 +846,12 @@ fn module_path(referrer: &str, specifier: &str) -> Result { /// Runs a module test's `source` (at `rel`, a path from the suite's folder) in a new realm with /// `options`, after `prelude` (the harness) as a script; the modules it imports are read from the -/// suite. `Err` describes a failure. A `negative_type` is the error the run must end with: thrown, -/// or, for a `SyntaxError`, also a module that does not parse. -fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> { +/// suite. `Err` describes a failure. `negative` is the phase (`resolution` or `runtime`) and the +/// error the test expects. A `resolution` test's module must parse, and the run must end with the +/// error while the modules load and link, before any runs; an imported module that does not parse +/// counts for a `SyntaxError`. A `runtime` test's modules must load and link, and the error must be thrown +/// while they run. +fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative: Option<(&str, &str)>, options: &Options) -> Result<(), String> { let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() }); realm.run(prelude).map_err(|e| format!("the harness failed: {}", e.message))?; let mut given = HashSet::new(); @@ -857,10 +861,29 @@ fn run_module_one(dir: &Path, prelude: &str, rel: &str, source: &str, negative_t let source = if given.insert(key.clone()) { Some(read_source(&path).map_err(LoadError::Other)?) } else { None }; Ok(LoadedModule { key, source }) }; - match (realm.run_module(rel, source, ModuleLimits::default(), &mut load), negative_type) { + let resolution = negative.is_some_and(|(phase, _)| phase == "resolution"); + if resolution && let Err(e) = vectorcraft_js::parse_module(source, options) { + return Err(format!("did not parse; a resolution error was expected: {} (line {})", e.message, e.line)); + } + let started = realm.start_module(rel, source, ModuleLimits::default(), &mut load); + let result = match started { + Ok(()) if resolution => return Err("linked; an error while linking was expected".to_string()), + Err(e) if !resolution && negative.is_some() => { + return Err(format!("did not start; an error while running was expected: {:?}: {} (line {})", e.kind, e.message, e.line)); + } + Err(e) => Err(e), + Ok(()) => loop { + match realm.advance(u64::MAX) { + Ok(Progress::Paused) => {} + Ok(Progress::Done(v)) => break Ok(v), + Err(e) => break Err(e), + } + }, + }; + match (result, negative.map(|(_, t)| t)) { (Ok(_), None) => Ok(()), (Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")), - (Err(e), Some("SyntaxError")) if e.kind == RunErrorKind::Syntax => Ok(()), + (Err(e), Some("SyntaxError")) if resolution && e.kind == RunErrorKind::Syntax => Ok(()), (Err(e), Some(t)) if e.kind == RunErrorKind::Thrown => { realm.bind_last_thrown("__thrown"); match realm.run(&format!("typeof __thrown === 'object' && __thrown !== null && __thrown.constructor === {t}")) { @@ -886,6 +909,7 @@ fn run_modules(dir: &Path) { let (mut selected, mut skipped) = (0usize, 0usize); let (mut before, mut after) = ((0usize, 0usize), (0usize, 0usize)); let mut failures = String::new(); + let mut panics = 0usize; for folder in MODULE_FOLDERS { let root = or_fail(inside(dir, &format!("test/language/{folder}"))); assert!(root.is_dir(), "{} is not a test262 checkout", dir.display()); @@ -913,6 +937,7 @@ fn run_modules(dir: &Path) { } selected += 1; let negative_type = meta.negative_type.clone().filter(|_| matches!(phase, Some("runtime" | "resolution"))); + let negative = phase.zip(negative_type.as_deref()); let as_script = if matches!(phase, Some("parse" | "resolution")) { parse(&source, &Options { strict: true, ..options.clone() }).is_err() } else { @@ -930,9 +955,12 @@ fn run_modules(dir: &Path) { } } else { let prelude = format!("{prelude}{includes}"); - match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative_type.as_deref(), &options)) { + match std::panic::catch_unwind(|| run_module_one(dir, &prelude, &rel, &source, negative, &options)) { Ok(r) => r, - Err(_) => Err("PANIC".to_string()), + Err(_) => { + panics += 1; + Err("PANIC".to_string()) + } } }; match outcome { @@ -958,7 +986,7 @@ fn run_modules(dir: &Path) { after.1, report.display() ); - assert!(!failures.contains("PANIC"), "the interpreter panicked; see {}", report.display()); + assert_eq!(panics, 0, "the interpreter panicked; see {}", report.display()); } #[test] diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f281431dc5..46ddcfeb3d 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -119,7 +119,10 @@ pub(crate) fn drain(app: &mut VectorcraftApp) { let Some((name, bytes)) = app.services.script_inbox.as_ref().and_then(|q| q.lock().unwrap_or_else(|e| e.into_inner()).pop()) else { return }; let result = match bytes.as_deref().map(std::str::from_utf8) { None => Err(TOO_LARGE.to_string()), - Some(Ok(source)) => chosen(app, json!({"source": source, "name": name})), + Some(Ok(source)) => { + let module = std::path::Path::new(&name).extension().is_some_and(|e| e.eq_ignore_ascii_case("mjs")); + chosen(app, json!({"source": source, "name": name, "module": module})) + } Some(Err(_)) => Err("the script is not UTF-8 text".to_string()), }; if let Err(e) = result { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index f8d3d4c39e..7106b22f14 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -164,6 +164,18 @@ fn a_web_pick_goes_to_the_warning_and_waits_for_an_open_dialog() { assert_eq!(objects(&app), 2); } +#[test] +fn a_web_pick_of_a_mjs_file_runs_as_a_module() { + let (mut app, inbox, _picks) = app_with_picker(); + app.session.prefs.show_external_script_warning = false; + // `export` is a syntax error outside a module, and `this` is undefined at a module's top. + let module = format!("export var a = 1;\nif (this !== undefined) throw new Error('not a module');\n{DRAW}"); + inbox.lock().unwrap().push(("Picked.MJS".to_string(), Some(module.into_bytes()))); + script_runs::poll(&mut app); + finish(&mut app); + assert_eq!(objects(&app), 2, "{}", app.ui.status); +} + #[test] fn a_web_pick_that_is_not_text_is_reported() { let (mut app, inbox, _picks) = app_with_picker(); diff --git a/docs/mcp.md b/docs/mcp.md index b34a4ebed6..5a882a3371 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2610,7 +2610,7 @@ the included files too. vectorcraft-cli run --cmd script.check --params '{"path": "Tidy Layers.jsx"}' ``` -`script.run {path? | source?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. +`script.run {path? | source?, module?, name?, args?, answers?, maxFuel?}` runs a JavaScript file against the open documents. File › Scripts › Other Script… (Cmd+F12) picks a `.js`, `.mjs` or `.jsx` file and runs it the same way; the help page https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js`, `.mjs` or `.jsx`, in @@ -2630,6 +2630,10 @@ an engine that `#targetengine` keeps reads each run the way that run's script do A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module (https://262.ecma-international.org/6.0/#sec-modules): strict mode code with the forms above, and `import` and `export` declarations at its top level. `import` and `export` are syntax errors in a `.js` or `.jsx` script. +`module` (true or false) chooses this for any `path` or `source`; it defaults to true for a `path` that ends in +`.mjs` and false otherwise. The app passes `module: true` for a `.mjs` file picked on the web, where the script +arrives as `source`. A `source` that runs as a module imports no files: each import ends the run with an error that +names the specifier. - A specifier is a path relative to the file that imports it. It starts with `./` or `../`, separates names with `/` and names a `.mjs` or `.js` file, which is read as a module. A bare name such as `'lib'`, a URL, an absolute @@ -2641,8 +2645,11 @@ A `path` that ends in `.mjs` (in any case) runs as an ECMAScript 2015 module - Every module is read, parsed and linked before any of them runs. A syntax error, a missing or refused file, an import of a name the module does not export, and an import of a name that two `export *` declarations give from different modules end the run with no code run, at the file, line and column of the module they are in. -- Each module runs once in a run, after the modules it imports, in the order it imports them; two paths to one file - (a link, `sub/../x.mjs`, or names that differ only in letter case on Windows) are one module. An import reads +- Each module runs once in a run, after the modules it imports, in the order it imports them. In a cycle of imports + a module does not wait for a module that is still waiting for its own imports, so it can run before that module + has initialized its bindings. Two paths to one file + (a link, `sub/../x.mjs`, or names that differ only in letter case in a Windows folder that ignores case) are one + module, and a module's relative imports are read from the folder the file is in, whichever path reached it first. An import reads the exporting module's binding each time, so it sees later assignments, and reading it before that module has initialized it (in a cycle of imports) throws a `ReferenceError`. Assigning to an import throws a `TypeError`. - `import * as ns` gives a namespace object: not extensible, with no prototype, its export names in code unit order diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 15745fc595..04effe52c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1080,7 +1080,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From b61c09379033e228808454a3742482f1d4529ba5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 16:59:05 -0800 Subject: [PATCH 043/153] JavaScript: $.evalFile in a module script's own code reads beside the script A function defined in a .mjs script that runs while a file `$.evalFile` loaded from a subfolder is the file being run now read its own `$.evalFile` paths from that subfolder. The script's folder is now kept for the run and used for code from the script itself, as it already was for the modules it imports; a script run keeps reading beside the file being run. The test262 counts in docs/target-app-parity.md are those of this branch: 535 of 708 ES2015 runs (173 failing, 22 of them for function `name`, `length` and `caller` rules) and 232 of 263 module tests. --- crates/engine/src/script/include.rs | 10 ++++++++++ crates/engine/src/script/mod.rs | 10 +++++++--- crates/engine/src/tests/script_modules.rs | 13 +++++++++++++ docs/target-app-parity.md | 4 ++-- 4 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index bc91914f0b..fb7d0a2c3a 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -234,6 +234,8 @@ pub(crate) struct Files { module_dirs: HashMap>, /// The key of each module path read, below the script's folder. module_paths: HashMap, + /// The key [`Files::module_entry`] gave the script, in a module run. + entry_key: Option, } /// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in @@ -383,6 +385,7 @@ impl Files { es2015: es2015_script(path), module_dirs: HashMap::new(), module_paths: HashMap::new(), + entry_key: None, } } @@ -397,6 +400,7 @@ impl Files { let shown = self.frames.first().map(|f| f.shown.clone()).unwrap_or_else(|| Arc::from("")); let key = self.chain.first().map(|real| module_key(real)).unwrap_or_default(); self.module_dirs.insert(key.clone(), Vec::new()); + self.entry_key = Some(key.clone()); let map = SourceMap { files: vec![shown], segments: vec![Segment { out_line: 1, file: 0, line: 1, shift: 0 }] }; Ok((key, Expanded { source: text.to_string(), map, name: None, strict: None, engine: None })) } @@ -509,6 +513,12 @@ impl Files { Some(names.iter().fold(root, |p, name| p.join(name))) } + /// The script's folder when the run is a module run ([`Files::module_entry`] read the script), + /// or `None` for a script run. + pub(crate) fn entry_module_dir(&self) -> Option { + self.module_dir(self.entry_key.as_deref()?) + } + /// The file `path` names for `$.evalFile`, relative to the file being run now, or to the folder /// `module_dir` when a module's code calls it, read and with its preprocessor lines read. It /// becomes the file being run until [`Files::end_eval`]. diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 101cdc2bac..cdba1c8a4c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -937,14 +937,18 @@ impl Host { } } - /// The folder of the module whose source has `tag`, when it is a module the script imported - /// (not the script itself, a file `$.evalFile` gave, or code from another run). + /// The folder of the module whose source has `tag`, when it is a module of a module run: the + /// script itself or a module it imported (not a file `$.evalFile` gave, or code from another + /// run). fn module_dir_at(&self, tag: u32) -> Option { let script = self.script_tag.get(); if tag == vectorcraft_js::UNKNOWN_SOURCE || script == vectorcraft_js::UNKNOWN_SOURCE { return None; } - let n = tag.checked_sub(script).filter(|n| *n > 0)?; + let n = tag.checked_sub(script)?; + if n == 0 { + return self.files.borrow().entry_module_dir(); + } let key = self.module_maps.borrow().get(&(n as usize - 1)).cloned()?; self.files.borrow().module_dir(&key) } diff --git a/crates/engine/src/tests/script_modules.rs b/crates/engine/src/tests/script_modules.rs index 0dec7ea7da..45d5a22417 100644 --- a/crates/engine/src/tests/script_modules.rs +++ b/crates/engine/src/tests/script_modules.rs @@ -300,3 +300,16 @@ fn script_module_eval_file_reads_beside_the_module_that_calls_it() { assert_eq!(r["log"], json!([["sub", "top"]])); let _ = std::fs::remove_dir_all(base); } + +#[test] +fn script_module_function_of_the_script_reads_beside_the_script_when_another_file_calls_it() { + let base = folder("evalfile-entry"); + write(&base.join("main/helper.jsx"), "'top'"); + write(&base.join("main/sub/helper.jsx"), "'sub'"); + // The file in `sub` calls the script's function while it is the file being run. + write(&base.join("main/sub/caller.jsx"), "$.global.load()"); + let text = "$.global.load = function () { return $.evalFile('helper.jsx'); };\nvc.log($.evalFile('sub/caller.jsx'));"; + let r = run(&base, text).unwrap(); + assert_eq!(r["log"], json!(["top"])); + let _ = std::fs::remove_dir_all(base); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 04effe52c8..773a38c172 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1079,8 +1079,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`. - `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`). - `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`. - - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 233 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. + - With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes and generators are still syntax errors, and so are `import` and `export` outside a module (next entry). `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 535 of 708 other runs pass with it (373 and 27 without it). Of the 173 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 22 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - `vectorcraft-js` runs ECMAScript 2015 modules (https://262.ecma-international.org/6.0/#sec-modules): `parse_module` reads `import` and `export` declarations, with their early errors, and `Realm::start_module` and `Realm::run_module` load a module and the modules it imports through the host, link every import before any module runs, and run each module once, after the modules it imports; in a cycle of imports a module does not wait for a module that is still waiting for its own imports, so it can run before that module has initialized its bindings. An import reads the exporting module's binding each time, and a read before that binding is initialized throws a `ReferenceError`; `import * as ns` gives a namespace object that is not extensible and takes no writes. `export * as ns from` (ECMAScript 2020) is read too; `import()` is a syntax error. Parsing takes fuel for each code unit, and the host bounds how many modules a run loads and how deep its imports go. `script.run` runs a `.mjs` file, and any script run with `module: true`, as a module: specifiers are `./` and `../` paths to `.mjs` and `.js` files, read only in the script's folder and the folders below it through the script's file scope; a bare name or a URL is a `SyntaxError` that names it, and module files count against the limits of `#include` files. File › Scripts lists `.mjs` files and Other Script… opens them, on the web too. `cargo xtask test262` runs the suite's module tests under `test/language/module-code`, `import` and `export` whose feature tags it reads: 232 of 263 pass as modules (154 as scripts). Tests: `crates/js/src/module_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_modules.rs`. - `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`. - `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`. - `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`. From 262090d75a065873e87a84411ccf2b044c785e80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:06:19 -0800 Subject: [PATCH 044/153] Scripts: path points read and set their selection, and guides can be assigned PathPoint.selected and PathItem.selectedPathPoints threw an error that said they were not available yet, and PathItem.guides could only be read. selected now reads PathPointSelection.ANCHORPOINT for a selected anchor point and NOSELECTION otherwise, and assigning either adds or removes the point with select.anchorsMany, keeping the other selected objects and anchors. Every point of a path selected as a whole counts as selected. Direction handles cannot be selected on their own, so the handle values throw an error. selectedPathPoints lists the selected points in pathPoints order. Assigning guides makes the path a guide or a path again with view.guides.make or view.guides.release, keeping the selection; a value that is not a boolean throws a TypeError, and a clipping path cannot be made a guide. A value the point or path already has runs no command. https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/ --- crates/engine/src/script/dom/paths.rs | 146 ++++++++++++++++-- crates/engine/src/tests/script_dom_paths.rs | 99 ++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 4 +- docs/gaps.md | 4 +- docs/mcp.md | 26 +++- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 7 files changed, 254 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32401db1d0..a3b75cc6ff 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -39,6 +39,11 @@ //! says it is not available yet. `rotateAbout` and `scaleAbout` default to //! `Transformation.CENTER`. A transform that leaves the path where it is (`rotate(360)`, //! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too. +//! - `PathPoint.selected` and `selectedPathPoints` count every point of a path selected as a whole +//! as a selected anchor point, and not the endpoints of selected segments; a path in a selected +//! group is not selected as a whole. Direction handles are not selected on their own, so +//! `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they are not +//! available yet. A clipping path cannot be made a guide. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -585,6 +590,39 @@ fn path_guides(h: &super::Host, a: &[Data]) -> Answer { read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { guide: true, .. }))) } +/// `guides = true` makes the path a guide with `view.guides.make`, and `false` makes it a path again +/// with `view.guides.release`; the selection stays as it was. A clipping path cannot be a guide. +fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { + let on = boolean(arg(a, 1), "guides")?; + let item = this_path(h, a)?; + let (now, clipping) = read_path(h, item, |_, n, _| match &n.kind { + NodeKind::Path { guide, clipping, .. } => (*guide, *clipping), + _ => (false, false), + })?; + if now == on { + return Ok(Data::Undefined); + } + if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + return Err(cannot_edit(item.id)); + } + if !on { + edit_path(h, item, "view.guides.release", json!({}))?; + return Ok(Data::Undefined); + } + if clipping { + return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0))); + } + see_all_points(h); + let kept = h.dom.editing.replace(Some(item)); + let r = on_doc(h, item.doc.uid, true, |h| { + command(h, "select.set", &json!({"ids": [item.id.0]}))?; + command(h, "view.guides.make", &json!({})) + }); + h.dom.editing.set(kept); + r?; + Ok(Data::Undefined) +} + fn path_clipping(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { clipping: true, .. }))) @@ -1323,6 +1361,86 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(path_ref(h, item)) } +/// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every +/// point of a path selected as a whole is, and of a path with direct-selected anchors only those +/// anchors are. The endpoints of selected segments are not. +fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, subs: &[SubPath], i: usize) -> bool { + if !sel.contains(id) || sel.segments.contains_key(&id) { + return false; + } + match sel.partial(id) { + None => true, + Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + } +} + +/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point +/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. +fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { + let (item, i) = this_point(h, a)?; + let on = read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, &pd.subpaths, i))?; + Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into())) +} + +/// The `PathPointSelection` values that select a point's direction handles. +const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPointSelection.RIGHTDIRECTION", "PathPointSelection.LEFTRIGHTPOINT"]; + +/// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and +/// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay +/// selected. A value the point has already runs no command. Direction handles cannot be selected, +/// so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error. +fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { + let on = match arg(a, 1) { + Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true, + Data::String(s) if s == "PathPointSelection.NOSELECTION" => false, + Data::String(s) if HANDLE_SELECTIONS.contains(&s.as_str()) => { + return Err(HostError::Error(format!("PathPoint.selected = {s} is not available yet: only anchor points can be selected"))); + } + _ => return Err(HostError::Type("selected must be a PathPointSelection value".into())), + }; + let (item, i) = this_point(h, a)?; + let (now, at, selectable) = with_doc(h, item.doc, |_, st| { + let subs = st.doc.node(item.id).and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); + let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); + (anchor_selected(&st.selection, item.id, subs, i), locate(subs, i), selectable) + }); + if now == on { + return Ok(Data::Undefined); + } + let Some((s, j)) = at else { return Err(HostError::Error(STALE_POINT.into())) }; + if on && !selectable { + return Err(HostError::Error(format!("Cannot select PathItem {}", item.id.0))); + } + let params = json!({"items": [{"id": item.id.0, "anchors": [[s, j]]}], "mode": if on { "add" } else { "subtract" }}); + on_doc(h, item.doc.uid, false, |h| command(h, "select.anchorsMany", ¶ms))?; + Ok(Data::Undefined) +} + +/// `selectedPathPoints`: the points that are selected anchor points ([`anchor_selected`]), in the +/// order of `pathPoints`. +fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { + let item = this_path(h, a)?; + let picked: Vec = read_path(h, item, |st, _, pd| { + let sel = &st.selection; + if !sel.contains(item.id) || sel.segments.contains_key(&item.id) { + return Vec::new(); + } + let mut out = Vec::new(); + let mut first = 0; + for (s, sp) in pd.subpaths.iter().enumerate() { + let n = sp.anchors.len(); + out.extend((0..n).filter(|j| sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); + first += n; + } + out + })?; + h.charge_call(picked.len() as u64)?; + let [high, low] = id_parts(item.id); + let cuts = float(point_cuts(h, item)); + let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect(); + Ok(Data::Array(points)) +} + /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; @@ -1350,7 +1468,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> { ("evenodd", property(l, path_evenodd, path_set_evenodd)), ("area", get(l, path_area)), ("length", get(l, path_length)), - ("guides", get(l, path_guides)), + ("guides", property(l, path_guides, path_set_guides)), ("clipping", get(l, path_clipping)), ("setEntirePath", point_method(l, path_set_entire)), ("filled", property(l, path_filled, path_set_filled)), @@ -1368,8 +1486,9 @@ pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> { ("translate", method(l, path_translate)), ("rotate", method(l, path_rotate)), ("resize", method(l, path_resize)), + ("selectedPathPoints", get(l, path_selected_points)), ]); - m.extend(["selectedPathPoints", "polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); + m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n))); m } @@ -1411,19 +1530,16 @@ pub(super) fn classes(l: &Link) -> Vec { class( "PathPoint", None, - { - let mut m = named(vec![ - ("typename", typename_of("PathPoint")), - ("parent", point_get(l, pt_parent)), - ("anchor", point_property(l, pt_anchor, pt_set_anchor)), - ("leftDirection", point_property(l, pt_left, pt_set_left)), - ("rightDirection", point_property(l, pt_right, pt_set_right)), - ("pointType", point_property(l, pt_type, pt_set_type)), - ("remove", point_method(l, pt_remove)), - ]); - m.push(later(l, "PathPoint", "selected")); - m - }, + named(vec![ + ("typename", typename_of("PathPoint")), + ("parent", point_get(l, pt_parent)), + ("anchor", point_property(l, pt_anchor, pt_set_anchor)), + ("leftDirection", point_property(l, pt_left, pt_set_left)), + ("rightDirection", point_property(l, pt_right, pt_set_right)), + ("pointType", point_property(l, pt_type, pt_set_type)), + ("selected", property(l, pt_selected, pt_set_selected)), + ("remove", point_method(l, pt_remove)), + ]), None, ), ] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 2dbf3263b9..abe9a1374a 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -880,3 +880,102 @@ fn many_path_edits_are_one_undo_step() { assert!((node(&s, id).appearance.stroke_width() - 1.0).abs() < 1e-9); } } + +fn selected_anchors(s: &Session, id: NodeId) -> Option> { + s.active().unwrap().selection.anchors.get(&id).map(|set| set.iter().copied().collect()) +} + +#[test] +fn path_point_selected_selects_and_deselects_anchor_points() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ + vc.log(pp[1].selected); vc.log(p.selectedPathPoints.length);\ + pp[1].selected = PathPointSelection.ANCHORPOINT; pp[2].selected = PathPointSelection.ANCHORPOINT;\ + vc.log(pp[1].selected); vc.log(pp[0].selected); vc.log(p.selected);\ + var sp = p.selectedPathPoints; vc.log(sp.length); vc.log(sp[1].anchor.join() == pp[2].anchor.join());", + ); + assert_eq!( + out, + vec![ + json!("PathPointSelection.NOSELECTION"), + json!(0), + json!("PathPointSelection.ANCHORPOINT"), + json!("PathPointSelection.NOSELECTION"), + json!(true), + json!(2), + json!(true) + ] + ); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)])); + assert!(s.active().unwrap().selection.contains(b), "the other selected object stays selected"); + assert_eq!(undo_steps(&s), steps, "a selection change is not an undo step"); + let r = run( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + pp[1].selected = PathPointSelection.ANCHORPOINT; pp[0].selected = PathPointSelection.NOSELECTION;", + ) + .unwrap(); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "a value the point has runs no command"); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].selected = PathPointSelection.NOSELECTION;"); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 2)])); +} + +#[test] +fn a_path_selected_as_a_whole_has_every_point_selected() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; vc.log(p.selectedPathPoints.length); vc.log(p.pathPoints[3].selected);\ + p.pathPoints[0].selected = PathPointSelection.NOSELECTION; vc.log(p.selectedPathPoints.length);\ + vc.log(app.activeDocument.pathItems[1].selectedPathPoints.length);", + ); + assert_eq!(out, vec![json!(4), json!("PathPointSelection.ANCHORPOINT"), json!(3), json!(0)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2), (0, 3)])); +} + +#[test] +fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { + let (mut s, a, _) = doc(); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.LEFTDIRECTION;"); + assert!(e.contains("not available yet"), "{e}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = true;"); + assert!(e.contains("PathPointSelection"), "{e}"); + s.execute("object.setProps", &json!({"ids": [a.0], "locked": true})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("Cannot select"), "{e}"); + assert!(s.active().unwrap().selection.is_empty()); +} + +fn is_guide(s: &Session, id: NodeId) -> bool { + matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) +} + +#[test] +fn assigning_guides_makes_and_releases_a_guide() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let steps = undo_steps(&s); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; p.guides = true; vc.log(p.guides);"); + assert_eq!(out, vec![json!(true)]); + assert!(is_guide(&s, a)); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "the selection stays as it was"); + assert_eq!(undo_steps(&s), steps + 1); + let r = run(&mut s, "app.activeDocument.pathItems[0].guides = true;").unwrap(); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps + 1, &json!([])), "a value the path has runs no command"); + log(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(!is_guide(&s, a)); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = 1;"); + assert!(e.contains("guides"), "{e}"); + assert!(!is_guide(&s, a)); + // A path in a group becomes a guide on its own. + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].guides = true;"); + assert!(is_guide(&s, b) && !is_guide(&s, a)); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 24417b2c21..aba7f93c69 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -122,8 +122,8 @@ const INSIDE: &[(&str, &str)] = &[ ( "PathItem.prototype.", "area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \ - filled= guides length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \ - selectedPathPoints= setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \ + filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \ + setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \ strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \ strokeWidth strokeWidth= stroked stroked= translate", ), diff --git a/docs/gaps.md b/docs/gaps.md index d8184b1a9b..ab16cd29ed 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,8 +807,8 @@ 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, type, the selected path - points, gradient stops and the other classes) and the `#engine` script directive (#1183 is open). Scripts have +- **Missing:** the rest of the document object model for scripts (layers, artboards, type, gradient + stops 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, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms. 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, diff --git a/docs/mcp.md b/docs/mcp.md index e3d4e634ed..a9b066a528 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2700,8 +2700,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, - `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, - `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, + `guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, + `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)` (counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through @@ -2713,9 +2713,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, - `leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `parent` and - `remove()`. `new RGBColor()` (0 to 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 - white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + `leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `selected`, + `parent` and `remove()`. Assigning `guides` makes the path a guide with `view.guides.make` (`true`) or a path again + with `view.guides.release` (`false`), with the selection kept; a value that is not a boolean throws a `TypeError`. + `PathPoint.selected` reads `PathPointSelection.ANCHORPOINT` for a selected anchor point and + `PathPointSelection.NOSELECTION` otherwise; assigning `ANCHORPOINT` adds the point to the direct-selected anchors and + `NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept. + `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to + 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -2727,7 +2732,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot a point of its path (`remove()`, `removeAll()`) or replaced its points (`setEntirePath`), or before anything other than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an - object that holds it, such as `translate()`. Color components left out + object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, + and the endpoints of selected segments are not; a path is selected as a whole only when it is itself selected, not + when a group that holds it is. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, + `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and selecting + a point of a path that cannot be selected throws `Cannot select`. A clipping path cannot be made a guide, and + `guides = true` on one throws an error. Color components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest @@ -2748,8 +2758,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing changed. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new - art, the active Fill or Stroke proxy and Recent Colors as they were. `selectedPathPoints`, `PathPoint.selected`, - `transform`, `polarity`, the gradient stops and the document's default paint are not available yet. + art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity`, the gradient stops and + the document's default paint are 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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 28192e13b9..48cb17110f 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, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, type, the selected path points, gradient stops 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, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, type, gradient stops 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 72ed713051..7be0c39261 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, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.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 dd748796249d63527774b005a7dbe184e1f19e44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:56:32 -0800 Subject: [PATCH 045/153] Scripts: guides refuse compound members and locked guides in both directions Assigning PathItem.guides on a path inside a compound path made every path in that compound a guide, because Make Guides acts on the compound that holds a selected member; it now throws an error that says it is not available yet, as duplicate and zOrder do for compound members. While guides are locked, assigning false threw and assigning true succeeded; now either value throws when it would change the path. A path that cannot be selected, for example one outside the isolated group or on a locked artboard, throws Cannot edit before any command runs. Assigning the value a path already has runs no command and throws no error. These are VectorCraft's own rules, and docs/mcp.md lists them with the other rules of its own. Tests cover a compound path member, a clipping path, a locked and a hidden path, the guide lock in both directions, a path in a group of two, and the TypeError name for a value that is not a boolean. --- crates/engine/src/script/dom/paths.rs | 24 +++++++- crates/engine/src/tests/script_dom_paths.rs | 65 +++++++++++++++++++-- docs/mcp.md | 7 ++- 3 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index a3b75cc6ff..bf61be91a5 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -43,7 +43,9 @@ //! as a selected anchor point, and not the endpoints of selected segments; a path in a selected //! group is not selected as a whole. Direction handles are not selected on their own, so //! `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they are not -//! available yet. A clipping path cannot be made a guide. +//! available yet. A clipping path cannot be made a guide. Assigning `guides` on a path inside a +//! compound path throws an error that says it is not available yet, on a path that cannot be +//! edited or selected throws `Cannot edit`, and while guides are locked throws an error. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -590,8 +592,13 @@ fn path_guides(h: &super::Host, a: &[Data]) -> Answer { read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { guide: true, .. }))) } +/// The error of assigning `guides` on a path inside a compound path. +pub const COMPOUND_MEMBER_GUIDES: &str = "Changing guides on a path inside a compound path is not available yet"; + /// `guides = true` makes the path a guide with `view.guides.make`, and `false` makes it a path again -/// with `view.guides.release`; the selection stays as it was. A clipping path cannot be a guide. +/// with `view.guides.release`; the selection stays as it was. A clipping path cannot be a guide, a +/// path inside a compound path throws [`COMPOUND_MEMBER_GUIDES`], and while guides are locked both +/// values throw an error. fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "guides")?; let item = this_path(h, a)?; @@ -602,9 +609,20 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { if now == on { return Ok(Data::Undefined); } - if !with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)) { + let (member, editable, selectable) = with_doc(h, item.doc, |_, st| { + let member = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. })); + let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); + (member, editable(&st.doc, item.id), selectable) + }); + if member { + return Err(HostError::Error(COMPOUND_MEMBER_GUIDES.into())); + } + if !editable || (on && !selectable) { return Err(cannot_edit(item.id)); } + if h.session.borrow().menu.guides_locked { + return Err(HostError::Error(format!("Cannot change guides on PathItem {}: guides are locked", item.id.0))); + } if !on { edit_path(h, item, "view.guides.release", json!({}))?; return Ok(Data::Undefined); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index abe9a1374a..b8fdf6673d 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -938,6 +938,15 @@ fn a_path_selected_as_a_whole_has_every_point_selected() { assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2), (0, 3)])); } +#[test] +fn a_path_in_a_selected_group_is_not_selected_as_a_whole() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let out = log(&mut s, "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);"); + assert_eq!(out, vec![json!([0, 0])]); +} + #[test] fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { let (mut s, a, _) = doc(); @@ -970,12 +979,58 @@ fn assigning_guides_makes_and_releases_a_guide() { log(&mut s, "app.activeDocument.pathItems[0].guides = false;"); assert!(!is_guide(&s, a)); assert_eq!(s.active().unwrap().selection.objects, vec![b]); - let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = 1;"); - assert!(e.contains("guides"), "{e}"); + let out = log(&mut s, "try { app.activeDocument.pathItems[0].guides = 1; } catch (e) { vc.log(e.name); }"); + assert_eq!(out, vec![json!("TypeError")]); assert!(!is_guide(&s, a)); - // A path in a group becomes a guide on its own. - s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + // A path in a group becomes a guide on its own; the other path in the group stays a path. + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); log(&mut s, "app.activeDocument.pathItems[1].guides = true;"); - assert!(is_guide(&s, b) && !is_guide(&s, a)); + assert!(is_guide(&s, a) != is_guide(&s, b), "only the assigned path in the group is a guide"); +} + +#[test] +fn assigning_guides_refuses_compound_members_clipping_paths_and_paths_that_cannot_be_edited() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = art(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("compound path"), "{e}"); + assert_eq!((art(&s), is_guide(&s, a), is_guide(&s, b)), (before, false, false), "no member of the compound path changed"); + + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let before = art(&s); + let e = failure(&mut s, "var ps = app.activeDocument.pathItems; for (var i = 0; i < ps.length; i++) if (ps[i].clipping) ps[i].guides = true;"); + assert!(e.contains("clipping path"), "{e}"); + assert_eq!(art(&s), before); + + for cmd in ["object.lock", "object.hide"] { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute(cmd, &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("Cannot edit"), "{cmd}: {e}"); + assert!(!is_guide(&s, a), "{cmd}"); + } +} + +#[test] +fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(is_guide(&s, a)); + s.set_guides_locked(true); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(e.contains("guides are locked"), "{e}"); + let e = failure(&mut s, "app.activeDocument.pathItems[1].guides = true;"); + assert!(e.contains("guides are locked"), "{e}"); + assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps)); } diff --git a/docs/mcp.md b/docs/mcp.md index a9b066a528..78a863a2b1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2720,7 +2720,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `PathPointSelection.NOSELECTION` otherwise; assigning `ANCHORPOINT` adds the point to the direct-selected anchors and `NOSELECTION` removes it, through `select.anchorsMany`, with the other selected objects and anchors kept. `selectedPathPoints` lists the points that read `ANCHORPOINT`, in the order of `pathPoints`. `new RGBColor()` (0 to - 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` + 255), `new CMYKColor()` (0 to 100), `new GrayColor()` (0 to 100, 0 black and 100 white, as + https://ai-scripting.docsforadobe.dev/jsobjref/GrayColor/ gives it), `new LabColor()` and `new NoColor()` (https://ai-scripting.docsforadobe.dev/jsobjref/NoColor/) make plain color objects; assigning a `NoColor` removes the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. @@ -2737,7 +2738,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot when a group that holds it is. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and selecting a point of a path that cannot be selected throws `Cannot select`. A clipping path cannot be made a guide, and - `guides = true` on one throws an error. Color components left out + `guides = true` on one throws an error; assigning `guides` on a path inside a compound path throws an error that says + it is not available yet, on a path that is hidden, locked or cannot be selected throws `Cannot edit`, and while + guides are locked throws an error for either value. Color components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest From fbc057f8b0ee3f5cbca178e9c114b3c873f6a5ea Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:36:17 -0800 Subject: [PATCH 046/153] Scripts: points of a path in a selected group read as selected PathPoint.selected and PathItem.selectedPathPoints now count a path as selected as a whole when a group or compound path that holds it is selected, as the canvas shows its anchors. Assigning PathPointSelection.NOSELECTION to a point of such a path throws an error that says it is not available yet, and ANCHORPOINT on it runs no command, so the selection is not left holding both the group and one of its paths. Selecting a point of a guide while guides are locked throws an error instead of running a selection that the guide lock undoes. Assigning guides = false on a path that cannot be selected (outside the isolated object) throws Cannot edit, as guides = true does. Reading PathPoint.selected no longer writes the point changes waiting for its path unless they add or remove points, so a loop that reads selected and moves the selected anchors writes the path once. --- crates/engine/src/script/dom/paths.rs | 79 ++++++++++++---- crates/engine/src/tests/script_dom_paths.rs | 100 ++++++++++++++++++-- docs/mcp.md | 16 ++-- 3 files changed, 162 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index bf61be91a5..db0352750b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -41,11 +41,13 @@ //! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too. //! - `PathPoint.selected` and `selectedPathPoints` count every point of a path selected as a whole //! as a selected anchor point, and not the endpoints of selected segments; a path in a selected -//! group is not selected as a whole. Direction handles are not selected on their own, so -//! `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they are not -//! available yet. A clipping path cannot be made a guide. Assigning `guides` on a path inside a -//! compound path throws an error that says it is not available yet, on a path that cannot be -//! edited or selected throws `Cannot edit`, and while guides are locked throws an error. +//! group or compound path is selected as a whole. Direction handles are not selected on their +//! own, so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they +//! are not available yet, and so does `NOSELECTION` on a point of a path in a selected group or +//! compound path. Selecting a point of a guide while guides are locked throws an error. A +//! clipping path cannot be made a guide. Assigning `guides` on a path inside a compound path +//! throws an error that says it is not available yet, on a path that cannot be edited or +//! selected throws `Cannot edit` for both values, and while guides are locked throws an error. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -617,7 +619,7 @@ fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { if member { return Err(HostError::Error(COMPOUND_MEMBER_GUIDES.into())); } - if !editable || (on && !selectable) { + if !editable || !selectable { return Err(cannot_edit(item.id)); } if h.session.borrow().menu.guides_locked { @@ -1379,10 +1381,20 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(path_ref(h, item)) } +/// Whether the path `id` is not selected itself but a group or compound path that holds it is, +/// which selects the path as a whole. +fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool { + !sel.contains(id) && d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) +} + /// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every -/// point of a path selected as a whole is, and of a path with direct-selected anchors only those -/// anchors are. The endpoints of selected segments are not. -fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, subs: &[SubPath], i: usize) -> bool { +/// point of a path selected as a whole is (a path is when a group or compound path that holds it +/// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The +/// endpoints of selected segments are not. +fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool { + if held { + return true; + } if !sel.contains(id) || sel.segments.contains_key(&id) { return false; } @@ -1392,11 +1404,27 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, subs: &[SubPath], i: } } +/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a +/// point index names the same anchor in both. +fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len()) +} + /// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point -/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. +/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in +/// [`super::State`] are written first only when they add or remove points of this path, since +/// the selection names anchors by their place in the document's path. fn pt_selected(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - let on = read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, &pd.subpaths, i))?; + let moved = match &*h.dom.pending.borrow() { + Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?, + _ => false, + }; + if moved { + super::flush(h)?; + } + let on = + read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?; Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into())) } @@ -1406,7 +1434,9 @@ const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPo /// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and /// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay /// selected. A value the point has already runs no command. Direction handles cannot be selected, -/// so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error. +/// so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error, and so does +/// `NOSELECTION` on a path selected through a group or compound path that holds it, and +/// `ANCHORPOINT` on a guide while guides are locked. fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { let on = match arg(a, 1) { Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true, @@ -1417,18 +1447,30 @@ fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { _ => return Err(HostError::Type("selected must be a PathPointSelection value".into())), }; let (item, i) = this_point(h, a)?; - let (now, at, selectable) = with_doc(h, item.doc, |_, st| { - let subs = st.doc.node(item.id).and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); + let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| { + let node = st.doc.node(item.id); + let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]); + let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })); let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id); - (anchor_selected(&st.selection, item.id, subs, i), locate(subs, i), selectable) + let held = held_selected(&st.doc, &st.selection, item.id); + (anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide) }); if now == on { return Ok(Data::Undefined); } let Some((s, j)) = at else { return Err(HostError::Error(STALE_POINT.into())) }; + if held { + return Err(HostError::Error(format!( + "PathPoint.selected = PathPointSelection.NOSELECTION is not available yet on PathItem {}: the group or compound path that holds it is selected", + item.id.0 + ))); + } if on && !selectable { return Err(HostError::Error(format!("Cannot select PathItem {}", item.id.0))); } + if on && guide && h.session.borrow().menu.guides_locked { + return Err(HostError::Error(format!("Cannot select PathItem {}: guides are locked", item.id.0))); + } let params = json!({"items": [{"id": item.id.0, "anchors": [[s, j]]}], "mode": if on { "add" } else { "subtract" }}); on_doc(h, item.doc.uid, false, |h| command(h, "select.anchorsMany", ¶ms))?; Ok(Data::Undefined) @@ -1440,14 +1482,15 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; - if !sel.contains(item.id) || sel.segments.contains_key(&item.id) { + let held = held_selected(&st.doc, sel, item.id); + if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { return Vec::new(); } let mut out = Vec::new(); let mut first = 0; for (s, sp) in pd.subpaths.iter().enumerate() { let n = sp.anchors.len(); - out.extend((0..n).filter(|j| sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); + out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); first += n; } out @@ -1555,7 +1598,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("leftDirection", point_property(l, pt_left, pt_set_left)), ("rightDirection", point_property(l, pt_right, pt_set_right)), ("pointType", point_property(l, pt_type, pt_set_type)), - ("selected", property(l, pt_selected, pt_set_selected)), + ("selected", HostMember::Property { get: super::point_function(l, pt_selected), set: super::function(l, pt_set_selected) }), ("remove", point_method(l, pt_remove)), ]), None, diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b8fdf6673d..43ce225e82 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -939,12 +939,39 @@ fn a_path_selected_as_a_whole_has_every_point_selected() { } #[test] -fn a_path_in_a_selected_group_is_not_selected_as_a_whole() { - let (mut s, a, b) = doc(); - s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); - s.execute("object.group", &json!({})).unwrap(); - let out = log(&mut s, "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);"); - assert_eq!(out, vec![json!([0, 0])]); +fn a_path_in_a_selected_group_or_compound_path_is_selected_as_a_whole() { + for make in ["object.group", "object.compoundPath.make"] { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute(make, &json!({})).unwrap(); + let sel = format!("{:?}", s.active().unwrap().selection); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var ps = app.activeDocument.pathItems; vc.log([ps[0].selectedPathPoints.length, ps[1].selectedPathPoints.length]);\ + vc.log(ps[0].pathPoints[2].selected); ps[0].pathPoints[2].selected = PathPointSelection.ANCHORPOINT;\ + try { ps[0].pathPoints[2].selected = PathPointSelection.NOSELECTION; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out[..2], [json!([4, 4]), json!("PathPointSelection.ANCHORPOINT")], "{make}"); + assert!(out[2].as_str().is_some_and(|m| m.contains("not available yet")), "{make}: {out:?}"); + assert_eq!(format!("{:?}", s.active().unwrap().selection), sel, "{make}: the selection stays as it was"); + assert_eq!(undo_steps(&s), steps, "{make}"); + } +} + +#[test] +fn reading_selected_while_moving_points_writes_the_path_once() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = run( + &mut s, + "var pp = app.activeDocument.pathItems[0].pathPoints;\ + for (var i = 0; i < pp.length; i++) if (pp[i].selected == PathPointSelection.ANCHORPOINT) pp[i].anchor = [pp[i].anchor[0] + 1, pp[i].anchor[1]];", + ) + .unwrap(); + let calls: Vec = + r["slowestCommands"].as_array().unwrap().iter().filter(|c| c["id"] == "path.setAnchors").map(|c| c["calls"].as_u64().unwrap()).collect(); + assert_eq!(calls, vec![1], "{r}"); } #[test] @@ -960,6 +987,60 @@ fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { assert!(s.active().unwrap().selection.is_empty()); } +/// The ways an editable path cannot be selected: on a locked artboard, and outside the isolated +/// object. +const UNSELECTABLE: [&str; 2] = ["locked artboard", "isolation"]; + +/// Makes the paths of [`doc`] other than `b` editable but not selectable, as `case` names. +fn lock_out(s: &mut Session, case: &str, b: NodeId) { + if case == "isolation" { + s.execute("object.isolate", &json!({"id": b.0})).unwrap(); + } else { + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + } +} + +#[test] +fn path_point_selected_refuses_paths_on_locked_artboards_and_outside_isolation() { + for case in UNSELECTABLE { + let (mut s, a, b) = doc(); + lock_out(&mut s, case, b); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("Cannot select"), "{case}: {e}"); + assert!(!s.active().unwrap().selection.contains(a), "{case}"); + } +} + +#[test] +fn selecting_a_point_of_a_guide_throws_while_guides_are_locked() { + let (mut s, a, _) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + s.set_guides_locked(true); + let e = failure(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + assert!(e.contains("guides are locked"), "{e}"); + assert!(!s.active().unwrap().selection.contains(a)); +} + +#[test] +fn assigning_guides_refuses_paths_that_cannot_be_selected() { + for case in UNSELECTABLE { + let (mut s, a, b) = doc(); + lock_out(&mut s, case, b); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(e.contains("Cannot edit"), "{case}: {e}"); + assert!(!is_guide(&s, a), "{case}"); + } + // A guide is on no locked artboard, so only isolation keeps a guide from being released. + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pathItems[0].guides = true;"); + assert!(is_guide(&s, a)); + lock_out(&mut s, "isolation", b); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].guides = false;"); + assert!(e.contains("Cannot edit"), "{e}"); + assert_eq!((is_guide(&s, a), undo_steps(&s)), (true, steps), "the guide stays a guide"); +} + fn is_guide(s: &Session, id: NodeId) -> bool { matches!(node(s, id).kind, NodeKind::Path { guide: true, .. }) } @@ -986,8 +1067,11 @@ fn assigning_guides_makes_and_releases_a_guide() { s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); s.execute("object.group", &json!({})).unwrap(); s.execute("select.none", &json!({})).unwrap(); - log(&mut s, "app.activeDocument.pathItems[1].guides = true;"); - assert!(is_guide(&s, a) != is_guide(&s, b), "only the assigned path in the group is a guide"); + log(&mut s, "var p = app.activeDocument.pathItems[1]; p.name = 'assigned'; p.guides = true;"); + let (assigned, other) = if node(&s, a).name.as_deref() == Some("assigned") { (a, b) } else { (b, a) }; + assert_eq!(node(&s, assigned).name.as_deref(), Some("assigned")); + assert_eq!((is_guide(&s, assigned), is_guide(&s, other)), (true, false), "only the assigned path in the group is a guide"); + assert!(s.active().unwrap().selection.is_empty(), "the selection stays as it was"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 78a863a2b1..103c6f7ee8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2734,13 +2734,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, - and the endpoints of selected segments are not; a path is selected as a whole only when it is itself selected, not - when a group that holds it is. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, - `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and selecting - a point of a path that cannot be selected throws `Cannot select`. A clipping path cannot be made a guide, and - `guides = true` on one throws an error; assigning `guides` on a path inside a compound path throws an error that says - it is not available yet, on a path that is hidden, locked or cannot be selected throws `Cannot edit`, and while - guides are locked throws an error for either value. Color components left out + and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` + to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a + path in a selected group or compound path. Selecting a point of a path that cannot be selected throws `Cannot + select`, and selecting a point of a guide while guides are locked throws an error. A clipping path cannot be made a + guide, and `guides = true` on one throws an error; assigning `guides` on a path inside a compound path throws an + error that says it is not available yet, assigning either value on a path that is hidden, locked or cannot be + selected throws `Cannot edit`, and assigning either value while guides are locked throws an error. Color + components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest From 496ac0c785e928c33b3f39c0cf251ecd06863007 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:14:01 -0800 Subject: [PATCH 047/153] Scripts: state the segment and no-change rules of selected and guides Assigning PathPointSelection.ANCHORPOINT to a point of a path with selected segments replaces that path's segment selection, as select.anchorsMany does for any anchor pick on such a path; the module doc, the setter's doc and docs/mcp.md now say so. docs/mcp.md also says that changing PathPoint.selected adds no undo step, and that assigning guides the value a path already has runs no command, which is why a hidden, locked or compound-member path, or locked guides, throw only for the other value. The touched lines of the PathItem paragraph are rewrapped to its width. New tests cover a point added by the script and selected in the same run, selectedPathPoints after an added point, a path with a selected segment, and assigning guides its current value while guides are locked. --- crates/engine/src/script/dom/paths.rs | 27 +++++++++------- crates/engine/src/tests/script_dom_paths.rs | 34 +++++++++++++++++++++ docs/mcp.md | 33 ++++++++++---------- 3 files changed, 67 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index db0352750b..ddd0853d3a 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -44,10 +44,12 @@ //! group or compound path is selected as a whole. Direction handles are not selected on their //! own, so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they //! are not available yet, and so does `NOSELECTION` on a point of a path in a selected group or -//! compound path. Selecting a point of a guide while guides are locked throws an error. A -//! clipping path cannot be made a guide. Assigning `guides` on a path inside a compound path -//! throws an error that says it is not available yet, on a path that cannot be edited or -//! selected throws `Cannot edit` for both values, and while guides are locked throws an error. +//! compound path. Selecting a point of a path with selected segments replaces that path's +//! segment selection. Selecting a point of a guide while guides are locked throws an error. A +//! clipping path cannot be made a guide. Assigning `guides` a value the path does not have +//! throws an error that says it is not available yet on a path inside a compound path, throws +//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides +//! are locked; assigning the value the path has runs no command. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -598,9 +600,10 @@ fn path_guides(h: &super::Host, a: &[Data]) -> Answer { pub const COMPOUND_MEMBER_GUIDES: &str = "Changing guides on a path inside a compound path is not available yet"; /// `guides = true` makes the path a guide with `view.guides.make`, and `false` makes it a path again -/// with `view.guides.release`; the selection stays as it was. A clipping path cannot be a guide, a -/// path inside a compound path throws [`COMPOUND_MEMBER_GUIDES`], and while guides are locked both -/// values throw an error. +/// with `view.guides.release`; the selection stays as it was. A value the path has already runs no +/// command and throws no error. Otherwise a clipping path cannot be a guide, a path inside a +/// compound path throws [`COMPOUND_MEMBER_GUIDES`], and while guides are locked both values throw +/// an error. fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer { let on = boolean(arg(a, 1), "guides")?; let item = this_path(h, a)?; @@ -1433,10 +1436,12 @@ const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPo /// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and /// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay -/// selected. A value the point has already runs no command. Direction handles cannot be selected, -/// so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error, and so does -/// `NOSELECTION` on a path selected through a group or compound path that holds it, and -/// `ANCHORPOINT` on a guide while guides are locked. +/// selected, except that selecting an anchor of a path with selected segments replaces that path's +/// segment selection, as `select.anchorsMany` does. A value the point has already runs no command. +/// Direction handles cannot be selected, so `LEFTDIRECTION`, `RIGHTDIRECTION` and +/// `LEFTRIGHTPOINT` throw an error, and so does `NOSELECTION` on a path selected through a group or +/// compound path that holds it, and `ANCHORPOINT` on a guide while guides are locked. The setter +/// writes the waiting point changes first, as every member that is not a point function does. fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer { let on = match arg(a, 1) { Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true, diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 43ce225e82..17d9969387 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -974,6 +974,38 @@ fn reading_selected_while_moving_points_writes_the_path_once() { assert_eq!(calls, vec![1], "{r}"); } +#[test] +fn selection_reads_and_writes_see_points_the_script_added() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = p.pathPoints.add(); q.selected = PathPointSelection.ANCHORPOINT;\ + vc.log(q.selected); vc.log(p.selectedPathPoints.length);", + ); + assert_eq!(out, vec![json!("PathPointSelection.ANCHORPOINT"), json!(1)]); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 4)])); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; p.pathPoints.add(); vc.log([p.selectedPathPoints.length, p.pathPoints.length]);"); + assert_eq!(out, vec![json!([6, 6])]); +} + +#[test] +fn selecting_a_point_of_a_path_with_selected_segments_replaces_the_segments() { + let (mut s, a, _) = doc(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "set"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; vc.log(p.selectedPathPoints.length);\ + p.pathPoints[1].selected = PathPointSelection.NOSELECTION;", + ); + assert_eq!(out, vec![json!(0)]); + assert!(s.active().unwrap().selection.segments.contains_key(&a), "a value the point has leaves the segments selected"); + log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].selected = PathPointSelection.ANCHORPOINT;"); + let sel = &s.active().unwrap().selection; + assert!(!sel.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)])); +} + #[test] fn path_point_selected_refuses_handles_bad_values_and_locked_paths() { let (mut s, a, _) = doc(); @@ -1117,4 +1149,6 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() { let e = failure(&mut s, "app.activeDocument.pathItems[1].guides = true;"); assert!(e.contains("guides are locked"), "{e}"); assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps)); + log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;"); + assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command"); } diff --git a/docs/mcp.md b/docs/mcp.md index 103c6f7ee8..319609005f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2701,15 +2701,16 @@ app through the global object `vc`, and writes to the Script Console and runs ot mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, - `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, - `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)` (counterclockwise for a - positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through - `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through - `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms - through `object.move`, `object.rotate` and `object.scale`. Changes to the points of a path (`closed`, - `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the - script uses any other member or command, or the points of another path, and when the script ends; a path aligned - to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. + `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to + 500), `strokeDashes`, `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)` + (counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The + geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the + stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through + `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the + points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one + `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the + script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points + read as the grid snaps them. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, @@ -2737,13 +2738,13 @@ app through the global object `vc`, and writes to the Script Console and runs ot and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a - path in a selected group or compound path. Selecting a point of a path that cannot be selected throws `Cannot - select`, and selecting a point of a guide while guides are locked throws an error. A clipping path cannot be made a - guide, and `guides = true` on one throws an error; assigning `guides` on a path inside a compound path throws an - error that says it is not available yet, assigning either value on a path that is hidden, locked or cannot be - selected throws `Cannot edit`, and assigning either value while guides are locked throws an error. Color - components left out - count as 0, `new + path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's + segment selection. Changing `selected` adds no undo step. Selecting a point of a path that cannot be selected + throws `Cannot select`, and selecting a point of a guide while guides are locked throws an error. A clipping path + cannot be made a guide, and `guides = true` on one throws an error. Assigning `guides` the value a path already + has runs no command. Assigning the other value throws an error that says it is not available yet on a path inside + a compound path, throws `Cannot edit` on a path that is hidden, locked or cannot be selected, and throws an error + while guides are locked. Color components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it From 828df8c7b503c840a5299db719cef108b5c531fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:54:12 -0800 Subject: [PATCH 048/153] Scripts: app.undo and app.redo step through the run's own edits app.undo() and app.redo() run edit.undo and edit.redo in the active document, so they reach only the steps the running script made, and the run still ends as one undo step. With no such step they change nothing, and with no document open they throw "No active document". --- crates/engine/src/script/dom.rs | 27 +++++++++++++++++++++++ crates/engine/src/tests/script_dom.rs | 31 +++++++++++++++++++++++++++ docs/mcp.md | 5 ++++- docs/target-app-parity.md | 2 +- 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cb901014b5..4e776e0809 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -23,6 +23,9 @@ //! the active artboard (`ARTBOARDCOORDINATESYSTEM`), as `app.coordinateSystem` says for the run. //! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`. //! - `app.activeDocument` with no document open throws `No active document`. +//! - `app.undo()` and `app.redo()` act on the active document and reach only the steps the run +//! made; with no such step they change nothing, and with no document open they throw +//! `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. //! - Members the help pages list that are not here yet throw an error that says so. @@ -688,6 +691,28 @@ fn app_set_active(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.undo()` and `app.redo()`: `edit.undo` or `edit.redo` in the active document, which reach +/// only the steps the run made. With no step to undo or redo they change nothing. +fn app_history(h: &Host, id: &str, redo: bool) -> Answer { + let has_step = { + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + if redo { !st.history.redo.is_empty() } else { !st.history.undo.is_empty() } + }; + if has_step { + command(h, id, &json!({}))?; + } + Ok(Data::Undefined) +} + +fn app_undo(h: &Host, _: &[Data]) -> Answer { + app_history(h, "edit.undo", false) +} + +fn app_redo(h: &Host, _: &[Data]) -> Answer { + app_history(h, "edit.redo", true) +} + fn app_selection(h: &Host, _: &[Data]) -> Answer { let uid = h.session.borrow().active().map(|st| st.uid); match uid { @@ -1948,6 +1973,8 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("undo", method(l, app_undo)), + ("redo", method(l, app_redo)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 60e3a71521..798d00395b 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -221,6 +221,37 @@ fn page_item_properties_join_one_undo_step() { } } +/// `app.undo()` and `app.redo()` step through the run's own edits, and the run still ends as one +/// undo step. They change nothing past the run's first edit or its last undone one. +#[test] +fn app_undo_and_redo_step_through_the_runs_edits() { + let (mut s, a, b) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument; var i = d.pageItems[0]; var unnamed = i.name;\ + app.undo(); app.redo();\ + i.name = 'first'; i.opacity = 40;\ + app.undo(); vc.log([i.name, i.opacity]);\ + app.redo(); vc.log(i.opacity);\ + app.redo(); vc.log(i.opacity);\ + app.undo(); app.undo(); app.undo(); vc.log([i.name === unnamed, i.opacity]);\ + vc.log(typeof app.undo());\ + d.pageItems[1].name = 'kept';", + ); + assert_eq!(out, vec![json!(["first", 100]), json!(40), json!(40), json!([true, 100]), json!("undefined")]); + assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run"); + let st = s.active().unwrap(); + let names: Vec<_> = [a, b].iter().map(|id| st.doc.node(*id).unwrap().name.clone()).collect(); + assert!(names.contains(&Some("kept".to_string())) && !names.contains(&Some("first".to_string())), "{names:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let st = s.active().unwrap(); + assert!(st.doc.node(a).is_some_and(|n| n.name.is_none()) && st.doc.node(b).is_some_and(|n| n.name.is_none()), "undoing the run"); + let mut s = Session::new(); + assert!(failure(&mut s, "app.undo();").contains("No active document")); + assert!(failure(&mut s, "app.redo();").contains("No active document")); +} + /// An opacity a graph mark already has still replaces the opacity another mark of its series left on /// the graph, as `object.setProps` does. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..8f8fc434cc 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,7 +2622,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)`, and `app.undo()` and `app.redo()`, which + run `edit.undo` and `edit.redo` in the active document and so reach only the steps the run made. The run still + ends as one undo step. `app.undo()` and `app.redo()` with no such step change nothing, and with no document open + they throw `No active document` (VectorCraft's own rules). `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..7d23108850 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ 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`). `app.undo()` and `app.redo()` undo and redo the edits the run made, and the run still ends as one undo step. Layers, 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 d534dcbf6e07b54d4694406211e28093528adc76 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:51:52 -0800 Subject: [PATCH 049/153] Scripts: charge host object handles and preset settings to the run's limits - An object of a host class counts its handle and its cache entry toward the heap when it is made and after each collection. - Reading an object of a host class as data, the receiver of a member call included, charges its class name and handle to the data limits before they are copied. - The settings of a run's DocumentPreset objects are held to 16 MiB together; a setting assigned again counts only its new value. - getIsFileOpen treats `\` as part of a name outside Windows, except in a path with a drive letter. - Assigning an opacity reuses the stored one only when the value equals what the getter reports. - file.new's artboardLayout messages list `rows`. - The selection de-dup uses a set; the host name inventory lists app.undo and app.redo; the getIsFileOpen test quotes its paths as JSON. - docs/mcp.md: a null presetSettings uses the preset's settings, and the preset settings limit and the getIsFileOpen comparison are described. --- crates/engine/src/cmd/newdoc.rs | 4 +- crates/engine/src/script/dom.rs | 48 ++++++++++++++---- crates/engine/src/tests/script_dom.rs | 39 ++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/heap.rs | 1 + crates/js/src/host.rs | 43 +++++++++------- crates/js/src/host_classes.rs | 21 +++++++- crates/js/src/host_tests.rs | 50 +++++++++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- docs/mcp.md | 13 +++-- 29 files changed, 223 insertions(+), 78 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 073de104cc..8c44a18224 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -370,7 +370,7 @@ impl DocSettings { } return Ok(()); } - let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, spacing?, rightToLeft?}"))?; + let o = l.as_object().ok_or_else(|| bad(cmd, "artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?}"))?; let count = |v: &Value| v.as_f64().filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u32); for (k, v) in o { match k.as_str() { @@ -384,7 +384,7 @@ impl DocSettings { .ok_or_else(|| bad(cmd, format!("artboardLayout.spacing must be 0–{MAX_SPACING} pt")))? } "rightToLeft" => self.right_to_left = v.as_bool().ok_or_else(|| bad(cmd, "artboardLayout.rightToLeft must be true or false"))?, - _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft)"))), + _ => return Err(bad(cmd, format!("unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft)"))), } } if o.contains_key("rows") && self.layout != ArtboardLayout::GridByColumn { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4e776e0809..685f23b53c 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -99,6 +99,8 @@ pub(super) struct State { locked: RefCell>, saving: Cell, presets: RefCell>>, + /// The bytes the settings in [`State::presets`] hold together ([`MAX_PRESET_BYTES`]). + preset_bytes: Cell, } impl State { @@ -730,13 +732,14 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter -/// or a `\`) letters in one case. +/// A path as `getIsFileOpen` compares it. A Windows path (any path on Windows, or one with a drive +/// letter) has `\` and `/` alike and letters in one case; elsewhere a `\` is a character of a name. fn path_key(p: &str) -> String { - let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); - let p = p.replace('\\', "/"); - let p = p.trim_end_matches('/').to_string(); - if windows { p.to_lowercase() } else { p } + if cfg!(windows) || p.as_bytes().get(1) == Some(&b':') { + p.replace('\\', "/").trim_end_matches('/').to_lowercase() + } else { + p.trim_end_matches('/').to_string() + } } /// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is @@ -1059,20 +1062,41 @@ fn new_preset(h: &Host) -> Answer { return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); } let item = |k: &str, v: Data| (k.to_string(), v); - presets.push(vec![ + let fields = vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ]); + ]; + hold_preset_bytes(h, 0, fields.iter().map(|(k, v)| field_bytes(k, v)).sum())?; + presets.push(fields); Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) } /// The most `DocumentPreset` objects one run can make. const MAX_PRESETS: usize = 10_000; +/// The most bytes the settings of the `DocumentPreset` objects of one run hold together. +const MAX_PRESET_BYTES: u64 = 16 << 20; + +/// The bytes a `DocumentPreset` setting holds, as `addDocument` charges it. +fn field_bytes(key: &str, v: &Data) -> u64 { + key.len() as u64 + 2 + data_size(v) +} + +/// Counts `added` bytes of settings in place of `released` toward [`MAX_PRESET_BYTES`], or throws +/// a `RangeError` and counts nothing when that would hold more. +fn hold_preset_bytes(h: &Host, released: u64, added: u64) -> std::result::Result<(), HostError> { + let held = h.dom.preset_bytes.get().saturating_sub(released).saturating_add(added); + if held > MAX_PRESET_BYTES { + return Err(HostError::Range(format!("the DocumentPresets of a script can hold at most {} MiB of settings", MAX_PRESET_BYTES >> 20))); + } + h.dom.preset_bytes.set(held); + Ok(()) +} + /// The settings a `DocumentPreset` has, each a property a script reads and assigns. const PRESET_FIELDS: &[&str] = &[ "artboardLayout", @@ -1125,6 +1149,8 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; let mut presets = h.dom.presets.borrow_mut(); let fields = &mut presets[i]; + let old = fields.iter().find(|(k, _)| k == key).map_or(0, |(k, v)| field_bytes(k, v)); + hold_preset_bytes(&h, old, field_bytes(key, &value))?; match fields.iter_mut().find(|(k, _)| k == key) { Some((_, v)) => *v = value, None => fields.push((key.to_string(), value)), @@ -1265,6 +1291,8 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + // The ids listed so far; `ids` keeps them in the order they were first listed. + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1279,7 +1307,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { // replaces the one the graph keeps for its series or kind. let item = this_item(h, a)?; let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); - let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + let v = now.filter(|now| (now * 1e4).round() / 1e4 == v).unwrap_or(v); set_props(h, a, |_| false, json!({"opacity": v})) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 798d00395b..66279c4131 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -286,6 +286,27 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); + // A value next to the item's opacity that the getter does not report is set as given. + s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].opacity = 99.99995;"); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, 0.9999995); +} + +/// The settings of a run's `DocumentPreset` objects are held to a total, and a setting assigned +/// again counts only its new value. +#[test] +fn document_preset_settings_are_held_to_a_total() { + let (mut s, _, _) = doc(); + let e = failure( + &mut s, + "var t = new Array(64001).join('x'), kept = []; for (var i = 0; i < 300; i++) { var p = new DocumentPreset(); p.title = t; kept.push(p); }", + ); + assert!(e.contains("at most 16 MiB of settings"), "{e}"); + let out = log( + &mut s, + "var t = new Array(64001).join('x'), p = new DocumentPreset(); for (var i = 0; i < 500; i++) p.title = t + i; vc.log(p.title.length);", + ); + assert_eq!(out, vec![json!(64003)]); } #[test] @@ -613,6 +634,11 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { let e = s.execute("file.new", &json!({"artboardLayout": {"layout": layout, "rows": 2}})).unwrap_err().to_string(); assert!(e.contains("rows needs the gridByColumn layout"), "{layout}: {e}"); } + // The messages for a layout of the wrong kind and an unknown key list `rows` with the others. + let e = s.execute("file.new", &json!({"artboardLayout": 3})).unwrap_err().to_string(); + assert!(e.contains("{layout?, columns?, rows?, spacing?, rightToLeft?}"), "{e}"); + let e = s.execute("file.new", &json!({"artboardLayout": {"row": 2}})).unwrap_err().to_string(); + assert!(e.contains("(layout, columns, rows, spacing, rightToLeft)"), "{e}"); } #[test] @@ -1291,10 +1317,19 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy(); + let (whole, other) = (serde_json::to_string(&p).unwrap(), serde_json::to_string(&format!("{p}.other")).unwrap()); + let query = format!("vc.log(app.getIsFileOpen({whole})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); + // Outside Windows a `\` is a character of a name: the folder and the name joined by one name + // another file. + #[cfg(not(windows))] + { + let (dir, name) = (path.parent().unwrap().to_string_lossy(), path.file_name().unwrap().to_string_lossy()); + let joined = serde_json::to_string(&format!("{dir}\\{name}")).unwrap(); + assert_eq!(log(&mut s, &format!("vc.log(app.getIsFileOpen({joined}));")), vec![json!(false)], "{joined}"); + } // Read roots that leave out the document's file: the same path does not count. let elsewhere = std::env::temp_dir().join(format!("vc-dom-roots-{}", std::process::id())); std::fs::create_dir_all(&elsewhere).unwrap(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..57bddac282 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", + redo selection typename undo", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index 418a603e1c..92ea9d703e 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -682,6 +682,7 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u work.extend(state.input.iter().chain(&state.kept).map(|o| o.0)); extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } + Class::Host(h) => extra = crate::host_classes::retained_bytes(h.handle.len()), _ => {} } OBJECT_BYTES + PROP_BYTES * o.props.len() + extra diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f34c9cff8e..0e007ed2ce 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -262,9 +262,7 @@ impl Interp { return Err(self.data_error(r, ErrorType::Range, "is nested too deep")); } let shape = match &self.object(id)?.class { - Class::Host(_) if r.hosted => { - return self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())); - } + Class::Host(_) if r.hosted => return self.read_host_ref(id, r), Class::Host(_) => return Err(self.data_error(r, ErrorType::Type, "is an object of a host class, not plain data")), Class::Array { length, .. } => Shape::Array(*length), Class::Ordinary => { @@ -288,6 +286,16 @@ impl Interp { out } + /// The [`crate::host_ref`] of the object of a host class `id`, its key, class name and handle + /// charged to `r` as the plain data they are before they are copied. + fn read_host_ref(&mut self, id: ObjId, r: &mut Reading) -> JsResult { + let Some((name, len)) = self.host_ref_size(id)? else { return Err(Abrupt::Internal("host object without a class".into())) }; + self.charge_entries(r, len.saturating_add(2))?; + let key = crate::HOST_REF_KEY.len().saturating_mul(3).saturating_add(8); + self.charge_reading(r, key.saturating_add(name.saturating_mul(3)).saturating_add(2))?; + self.host_ref_of(id)?.ok_or_else(|| Abrupt::Internal("host object without a class".into())) + } + fn read_array(&mut self, id: ObjId, length: u32, r: &mut Reading) -> JsResult { self.charge_entries(r, length as usize)?; let mut items = Vec::with_capacity(length as usize); @@ -396,16 +404,8 @@ impl Interp { pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc, this: &Value, args: &[Value], how: &ArgRead) -> JsResult { let data = match how { ArgRead::Site => site_data(self.call_site()), - ArgRead::Hosted => { - let this = match this { - Value::Object(o) => self.host_ref_of(*o)?.unwrap_or(Data::Undefined), - _ => Data::Undefined, - }; - let mut data = vec![this]; - data.extend(self.read_args(name, args, how)?); - data - } - _ => self.read_args(name, args, how)?, + ArgRead::Hosted => self.read_args(name, Some(this), args, how)?, + _ => self.read_args(name, None, args, how)?, }; // Only the script's own code, in a run that can pause, can wait for a result, and a host // class's constructor called with `new` cannot. @@ -452,7 +452,7 @@ impl Interp { name: &Rc, args: &[Value], ) -> JsResult { - let data = self.read_args(name, args, &ArgRead::Data)?; + let data = self.read_args(name, None, args, &ArgRead::Data)?; let source = match f(data) { Ok(Data::String(source)) => source, Ok(d) => return self.write_data(d, 0, false), @@ -494,8 +494,10 @@ impl Interp { r } - /// The arguments of host function `name` as [`Data`], read as `how` says. - fn read_args(&mut self, name: &Rc, args: &[Value], how: &ArgRead) -> JsResult> { + /// The arguments of host function `name` as [`Data`], read as `how` says. With `this`, the + /// first is the object `this` stands for, or `undefined` when it is not an object of a host + /// class, charged to the same limits as the arguments. + fn read_args(&mut self, name: &Rc, this: Option<&Value>, args: &[Value], how: &ArgRead) -> JsResult> { let mut reading = Reading { limits: self.data_limits, bytes: 0, @@ -509,7 +511,14 @@ impl Interp { ArgRead::Each(list) => args.get(..list.len().min(args.len())).unwrap_or(args), _ => args, }; - let mut data = Vec::with_capacity(args.len()); + let mut data = Vec::with_capacity(args.len() + 1); + if let Some(this) = this { + let this = match this { + Value::Object(o) if self.host_ref_size(*o)?.is_some() => self.read_host_ref(*o, &mut reading)?, + _ => Data::Undefined, + }; + data.push(this); + } // A conversion can run the script's own `toString`, which may collect garbage. let mark = self.temp_roots.len(); if !matches!(how, ArgRead::Data | ArgRead::Frozen | ArgRead::Hosted) { diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..c837a9f107 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -86,6 +86,15 @@ type MadeKey = (u32, Box<[u64]>); /// The object made for each family of classes and handle ([`Interp::host_objects`]). pub(crate) type Made = std::collections::HashMap; +/// The estimated bytes of an entry of [`Made`] without the bits of its handle. +const MADE_ENTRY_BYTES: usize = 64; + +/// The estimated bytes an object of a host class with a handle of `len` numbers holds outside its +/// cell: its handle, and its entry in [`Interp::host_objects`] with the bits of the handle. +pub(crate) fn retained_bytes(len: usize) -> usize { + MADE_ENTRY_BYTES.saturating_add(len.saturating_mul(16)) +} + /// Whether `id` is still the object made for `key`, and not a freed cell or another object that /// was given its cell. fn is_made(heap: &crate::heap::Heap, classes: &[Entry], id: ObjId, key: &MadeKey) -> bool { @@ -131,6 +140,14 @@ impl Interp { Ok(Some(host_ref(&name, &h.handle))) } + /// The length of the class name and of the handle of the object of a host class `id`, or `None` + /// when it is not one. + pub(crate) fn host_ref_size(&self, id: ObjId) -> JsResult> { + let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; + let name = self.host_classes.get(h.class as usize).map(|e| e.name.len()).ok_or_else(|| Abrupt::Internal("host class out of range".into()))?; + Ok(Some((name, h.handle.len()))) + } + /// The object of a host class that `d`, which a host function gave, stands for. pub(crate) fn write_host_ref(&mut self, d: &Data) -> JsResult { let Some((name, handle)) = host_ref_parts(d) else { @@ -155,7 +172,9 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES)?; + let extra = retained_bytes(handle.len()); + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(extra))?; + self.heap.bytes = self.heap.bytes.saturating_add(extra); let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..288c56034c 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -661,6 +661,56 @@ fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::String("true,2,true,false".into())); } +/// A realm with the host class `Thing`: `make(n)` gives the `Thing` whose handle is `n` followed by +/// zeros, `len` numbers in all, and `take()` gives `undefined`; and the global `thing`, the `Thing` +/// with the handle `[0]`. +fn with_long_things(r: &mut Realm, len: usize) { + let make: HostFunction = Rc::new(move |a| { + let mut handle = vec![if let Some(Data::Number(n)) = a.get(1) { *n } else { 0.0 }]; + handle.resize(len, 0.0); + Ok(host_ref("Thing", &handle)) + }); + let take: HostFunction = Rc::new(|_| Ok(Data::Undefined)); + let members = vec![("make".to_string(), HostMember::Method(make)), ("take".to_string(), HostMember::Method(take))]; + let class = HostClass { name: "Thing".into(), parent: None, members, index: None, construct: None }; + r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[0.0]))]).unwrap(); +} + +#[test] +fn the_handles_of_host_objects_a_script_keeps_count_toward_the_heap() { + let mut r = realm(100_000_000); + with_long_things(&mut r, 4096); + // 200 objects hold handles of 4,096 numbers each, more than 12 MiB with their keys. + r.set_limits(Limits { fuel: 100_000_000, heap_bytes: 4 << 20, ..Limits::default() }); + let e = r.run("var kept = []; for (var i = 0; i < 200; i++) kept.push(thing.make(i)); kept.length").unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); + // A collection counts the handles of the objects the script still holds. + r.set_limits(Limits { fuel: 100_000_000, heap_bytes: 256 << 20, ..Limits::default() }); + r.run("var kept = []; for (var i = 0; i < 100; i++) kept.push(thing.make(i));").unwrap(); + let interp = r.interp(); + interp.collect_garbage(); + assert!(interp.heap.bytes >= 100 * 4096 * 16, "{}", interp.heap.bytes); +} + +#[test] +fn the_handles_of_host_objects_given_to_the_host_count_toward_the_data_limits() { + let mut r = realm(100_000_000); + with_long_things(&mut r, 1024); + // 100 references to an object with a handle of 1,024 numbers are more than 100,000 entries. + r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 100_000 }); + let probe = "var t = thing.make(1), list = []; for (var i = 0; i < 100; i++) list.push(t); var m = 'none'; \ + try { thing.take(list); } catch (e) { m = e.name + '|' + e.message; } m"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}"); + // The object a member is called on counts too. + r.set_data_limits(DataLimits { depth: 64, bytes: 16 << 20, entries: 1_000 }); + let probe = "var m = 'none'; try { thing.make(2).take(); } catch (e) { m = e.name + '|' + e.message; } m"; + let JsValue::String(out) = r.run(probe).unwrap() else { panic!("not a string") }; + assert!(out.starts_with("RangeError|") && out.contains("too many entries"), "{out}"); + // Short handles stay within the limits. + assert_eq!(r.run("thing.take([thing, thing]) === undefined").unwrap(), JsValue::Bool(true)); +} + #[test] fn a_host_class_constructor_called_with_new_cannot_wait() { let mut r = realm(1_000_000); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..8d04f8210b 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9419,7 +9419,7 @@ breakText Glyphs Glyfy @msg artboard is a 0-based index artboard je index počítaný od 0 @msg artboard must be a 0-based index artboard musí být index počítaný od 0 @msg artboard {i} doesn't print pracovní plocha {i} se netiskne -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout musí být {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout musí být {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns musí být 1 nebo více @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout musí být gridByRow, gridByColumn, row nebo column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft musí být true nebo false @@ -10525,7 +10525,7 @@ breakText Glyphs Glyfy @msg unknown Warp style neznámý styl deformace @msg unknown alignToPath `{a}` neznámé alignToPath `{a}` @msg unknown arrowhead {v} neznámá šipka {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) neznámý klíč artboardLayout `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) neznámý klíč artboardLayout `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` neznámý atribut `{attribute}` @msg unknown attribute `{k}` neznámý atribut `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) neznámá osa `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..5a822aee7a 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1576,7 +1576,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg artboard is a 0-based index artboard er et 0-baseret indeks @msg artboard must be a 0-based index artboard skal være et 0-baseret indeks @msg artboard {i} doesn't print tegneflade {i} udskrives ikke -@msg artboardLayout must be {{layout?, columns?, spacing?, rightToLeft?}} artboardLayout skal være {{layout?, columns?, spacing?, rightToLeft?}} +@msg artboardLayout must be {{layout?, columns?, rows?, spacing?, rightToLeft?}} artboardLayout skal være {{layout?, columns?, rows?, spacing?, rightToLeft?}} @msg artboardLayout.columns must be 1 or more artboardLayout.columns skal være 1 eller mere @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout skal være gridByRow, gridByColumn, row eller column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft skal være true eller false @@ -2746,7 +2746,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg unknown `by` "{name}": expected one of {_1} ukendt `by` "{name}": forventede en af {_1} @msg unknown alignToPath `{a}` ukendt alignToPath `{a}` @msg unknown arrowhead {v} ukendt pilespids {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) ukendt artboardLayout-nøgle `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) ukendt artboardLayout-nøgle `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` ukendt attribut `{attribute}` @msg unknown attribute `{k}` ukendt attribut `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) ukendt akse `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..7e97cb6bbd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9148,7 +9148,7 @@ breakText Glyphs Glyphen @msg artboard is a 0-based index artboard ist ein nullbasierter Index @msg artboard must be a 0-based index artboard muss ein nullbasierter Index sein @msg artboard {i} doesn't print Zeichenfläche {i} wird nicht gedruckt -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout muss {layout?, columns?, spacing?, rightToLeft?} sein +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout muss {layout?, columns?, rows?, spacing?, rightToLeft?} sein @msg artboardLayout.columns must be 1 or more artboardLayout.columns muss 1 oder größer sein @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout muss gridByRow, gridByColumn, row oder column sein @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft muss true oder false sein @@ -10048,7 +10048,7 @@ breakText Glyphs Glyphen @msg unknown Warp style unbekannter Verkrümmungsstil @msg unknown alignToPath `{a}` unbekanntes alignToPath `{a}` @msg unknown arrowhead {v} unbekannte Pfeilspitze {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) unbekannter artboardLayout-Schlüssel `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) unbekannter artboardLayout-Schlüssel `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` unbekanntes Attribut `{attribute}` @msg unknown attribute `{k}` unbekanntes Attribut `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) unbekannte Achse `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..d691dc1109 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -9588,7 +9588,7 @@ breakText Glyphs Glifos @msg artboard is a 0-based index artboard es un índice que empieza en 0 @msg artboard must be a 0-based index artboard debe ser un índice que empieza en 0 @msg artboard {i} doesn't print la mesa de trabajo {i} no se imprime -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout debe ser {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout debe ser {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns debe ser 1 o más @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout debe ser gridByRow, gridByColumn, row o column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft debe ser true o false @@ -10465,7 +10465,7 @@ breakText Glyphs Glifos @msg unknown Warp style estilo de Deformación desconocido @msg unknown alignToPath `{a}` alignToPath desconocido `{a}` @msg unknown arrowhead {v} punta de flecha desconocida {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) clave de artboardLayout desconocida `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) clave de artboardLayout desconocida `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` atributo desconocido `{attribute}` @msg unknown attribute `{k}` atributo desconocido `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) eje desconocido `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..eea91ae765 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9280,7 +9280,7 @@ breakText Glyphs Glyphes @msg artboard is a 0-based index artboard est un indice commençant à 0 @msg artboard must be a 0-based index artboard doit être un indice commençant à 0 @msg artboard {i} doesn't print le plan de travail {i} ne s’imprime pas -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout doit être {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout doit être {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns doit être supérieur ou égal à 1 @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout doit valoir gridByRow, gridByColumn, row ou column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft doit valoir true ou false @@ -10382,7 +10382,7 @@ breakText Glyphs Glyphes @msg unknown Warp style style de déformation inconnu @msg unknown alignToPath `{a}` alignToPath inconnu `{a}` @msg unknown arrowhead {v} pointe de flèche inconnue {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) clé artboardLayout inconnue `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) clé artboardLayout inconnue `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` attribut inconnu `{attribute}` @msg unknown attribute `{k}` attribut inconnu `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) axe inconnu `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..0630433bc9 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7364,7 +7364,7 @@ arrowhead Feather पंख @msg artboard {i} doesn't print आर्टबोर्ड {i} प्रिंट नहीं करता है @msg artboard is a 0-based index artboard 0 से शुरू होने वाला इंडेक्स है @msg artboard must be a 0-based index artboard 0 से शुरू होने वाला इंडेक्स होना चाहिए -@msg artboardLayout must be {{layout?, columns?, spacing?, rightToLeft?}} artboardLayout को {{layout?, columns?, spacing?, rightToLeft?}} होना चाहिए +@msg artboardLayout must be {{layout?, columns?, rows?, spacing?, rightToLeft?}} artboardLayout को {{layout?, columns?, rows?, spacing?, rightToLeft?}} होना चाहिए @msg artboardLayout.columns must be 1 or more artboardLayout.columns को 1 या अधिक होना चाहिए @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout को gridByRow, gridByColumn, row या column होना चाहिए @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft को true या false होना चाहिए @@ -9627,7 +9627,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg unknown align `{other}` अज्ञात संरेखण `{other}` @msg unknown alignToPath `{a}` अज्ञात alignToPath `{a}` @msg unknown arrowhead {v} अज्ञात arrowhead {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) अज्ञात artboardLayout कुंजी `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) अज्ञात artboardLayout कुंजी `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` अज्ञात विशेषता `{attribute}` @msg unknown attribute `{k}` अज्ञात विशेषता `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) अज्ञात अक्ष `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..7cb6022a86 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9290,7 +9290,7 @@ breakText Glyphs Glifák @msg artboard is a 0-based index artboard: 0-tól kezdődő index @msg artboard must be a 0-based index artboard: 0-tól kezdődő index kell @msg artboard {i} doesn't print ez a rajztábla nem kerül nyomtatásra: {i} -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout: {layout?, columns?, spacing?, rightToLeft?} kell +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout: {layout?, columns?, rows?, spacing?, rightToLeft?} kell @msg artboardLayout.columns must be 1 or more artboardLayout.columns: 1 vagy nagyobb érték kell @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout: gridByRow, gridByColumn, row vagy column kell @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft: true vagy false kell @@ -10396,7 +10396,7 @@ breakText Glyphs Glifák @msg unknown Warp style ismeretlen hajlítási stílus @msg unknown alignToPath `{a}` ismeretlen alignToPath: `{a}` @msg unknown arrowhead {v} ismeretlen nyílhegy: {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) ismeretlen artboardLayout kulcs: `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) ismeretlen artboardLayout kulcs: `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` ismeretlen attribútum: `{attribute}` @msg unknown attribute `{k}` ismeretlen attribútum: `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) ismeretlen tengely: `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..b4d0df2a22 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9201,7 +9201,7 @@ breakText Glyphs Glifi @msg artboard is a 0-based index artboard è un indice a partire da 0 @msg artboard must be a 0-based index artboard deve essere un indice a partire da 0 @msg artboard {i} doesn't print la tavola da disegno {i} non viene stampata -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout deve essere {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout deve essere {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns deve essere 1 o maggiore @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout deve essere gridByRow, gridByColumn, row o column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft deve essere true o false @@ -10101,7 +10101,7 @@ breakText Glyphs Glifi @msg unknown Warp style stile Altera sconosciuto @msg unknown alignToPath `{a}` alignToPath sconosciuto `{a}` @msg unknown arrowhead {v} punta di freccia sconosciuta {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) chiave di artboardLayout sconosciuta `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) chiave di artboardLayout sconosciuta `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` attributo sconosciuto `{attribute}` @msg unknown attribute `{k}` attributo sconosciuto `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) asse sconosciuto `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..5d438b24dc 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -8018,7 +8018,7 @@ axis Y Axis Y 軸 @msg artboard is a 0-based index artboard には 0 から始まるインデックスを指定してください @msg artboard must be a 0-based index artboard には 0 から始まるインデックスを指定してください @msg artboard {i} doesn't print アートボード {i} はプリントされません -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout には {layout?, columns?, spacing?, rightToLeft?} を指定してください +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout には {layout?, columns?, rows?, spacing?, rightToLeft?} を指定してください @msg artboardLayout.columns must be 1 or more artboardLayout.columns には 1 以上の値を指定してください @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout には gridByRow、gridByColumn、row、column のいずれかを指定してください @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft には true または false を指定してください @@ -8918,7 +8918,7 @@ axis Y Axis Y 軸 @msg unknown Warp style 不明なワープスタイルです @msg unknown alignToPath `{a}` `{a}` は不明な alignToPath の指定です @msg unknown arrowhead {v} {v} は不明な矢印です -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) `{k}` は不明な artboardLayout のキーです (layout、columns、spacing、rightToLeft のいずれか) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) `{k}` は不明な artboardLayout のキーです (layout、columns、rows、spacing、rightToLeft のいずれか) @msg unknown attribute `{attribute}` `{attribute}` は不明な属性です @msg unknown attribute `{k}` `{k}` は不明な属性です @msg unknown axis `{other}` (vertical|horizontal|free) `{other}` は不明な軸の指定です (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..1cf31d829f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -622,7 +622,7 @@ @msg artboard is a 0-based index artboard არის 0-დან დაწყებული ინდექსი @msg artboard must be a 0-based index artboard უნდა იყოს 0-დან დაწყებული ინდექსი @msg artboard {i} doesn't print სამუშაო დაფა {i} არ იბეჭდება -@msg artboardLayout must be {{layout?, columns?, spacing?, rightToLeft?}} artboardLayout უნდა იყოს {{layout?, columns?, spacing?, rightToLeft?}} +@msg artboardLayout must be {{layout?, columns?, rows?, spacing?, rightToLeft?}} artboardLayout უნდა იყოს {{layout?, columns?, rows?, spacing?, rightToLeft?}} @msg artboardLayout.columns must be 1 or more artboardLayout.columns უნდა იყოს 1 ან მეტი @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout უნდა იყოს gridByRow, gridByColumn, row ან column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft უნდა იყოს true ან false @@ -1769,7 +1769,7 @@ @msg unknown Warp style გაღუნვის უცნობი სტილი @msg unknown alignToPath `{a}` უცნობი alignToPath `{a}` @msg unknown arrowhead {v} უცნობი ისრის წვერი {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) artboardLayout-ის უცნობი გასაღები `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) artboardLayout-ის უცნობი გასაღები `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` უცნობი ატრიბუტი `{attribute}` @msg unknown attribute `{k}` უცნობი ატრიბუტი `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) უცნობი ღერძი `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..80a3ee939e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9059,7 +9059,7 @@ breakText Glyphs 글리프 @msg artboard is a 0-based index artboard는 0부터 시작하는 인덱스입니다 @msg artboard must be a 0-based index artboard는 0부터 시작하는 인덱스여야 합니다 @msg artboard {i} doesn't print 아트보드 {i}은(는) 인쇄되지 않습니다 -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout은 {layout?, columns?, spacing?, rightToLeft?}여야 합니다 +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout은 {layout?, columns?, rows?, spacing?, rightToLeft?}여야 합니다 @msg artboardLayout.columns must be 1 or more artboardLayout.columns는 1 이상이어야 합니다 @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout은 gridByRow, gridByColumn, row 또는 column이어야 합니다 @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft는 true 또는 false여야 합니다 @@ -10172,7 +10172,7 @@ breakText Glyphs 글리프 @msg unknown Warp style 알 수 없는 왜곡 스타일 @msg unknown alignToPath `{a}` 알 수 없는 alignToPath `{a}` @msg unknown arrowhead {v} 알 수 없는 화살촉 {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) 알 수 없는 artboardLayout 키 `{k}`(layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) 알 수 없는 artboardLayout 키 `{k}`(layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` 알 수 없는 속성 `{attribute}` @msg unknown attribute `{k}` 알 수 없는 속성 `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) 알 수 없는 축 `{other}`(vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..9c55f0d7ef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6931,7 +6931,7 @@ imageTrace Outline Contour @msg artboard is a 0-based index artboard is een index die bij 0 begint @msg artboard must be a 0-based index artboard moet een index zijn die bij 0 begint @msg artboard {i} doesn't print tekengebied {i} wordt niet afgedrukt -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout moet {layout?, columns?, spacing?, rightToLeft?} zijn +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout moet {layout?, columns?, rows?, spacing?, rightToLeft?} zijn @msg artboardLayout.columns must be 1 or more artboardLayout.columns moet 1 of meer zijn @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout moet gridByRow, gridByColumn, row of column zijn @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft moet true of false zijn @@ -8045,7 +8045,7 @@ imageTrace Outline Contour @msg unknown Warp style onbekende warpstijl @msg unknown alignToPath `{a}` onbekende alignToPath `{a}` @msg unknown arrowhead {v} onbekende pijlpunt {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) onbekende sleutel `{k}` van artboardLayout (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) onbekende sleutel `{k}` van artboardLayout (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` onbekend kenmerk `{attribute}` @msg unknown attribute `{k}` onbekend kenmerk `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) onbekende as `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..a9cca69cf7 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9409,7 +9409,7 @@ breakText Glyphs Glify @msg artboard is a 0-based index artboard to indeks liczony od 0 @msg artboard must be a 0-based index artboard musi być indeksem liczonym od 0 @msg artboard {i} doesn't print obszar kompozycji {i} nie jest drukowany -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout musi mieć postać {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout musi mieć postać {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns musi wynosić 1 lub więcej @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout musi mieć wartość gridByRow, gridByColumn, row lub column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft musi mieć wartość true lub false @@ -10308,7 +10308,7 @@ breakText Glyphs Glify @msg unknown Warp style nieznany styl wypaczenia @msg unknown alignToPath `{a}` nieznane alignToPath `{a}` @msg unknown arrowhead {v} nieznany grot strzałki {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) nieznany klucz artboardLayout `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) nieznany klucz artboardLayout `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` nieznany atrybut `{attribute}` @msg unknown attribute `{k}` nieznany atrybut `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) nieznana oś `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..598ee16add 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9481,7 +9481,7 @@ swatch Yellow Green Verde-amarelado @msg artboard is a 0-based index artboard é um índice com base 0 @msg artboard must be a 0-based index artboard deve ser um índice com base 0 @msg artboard {i} doesn't print a prancheta {i} não é impressa -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout deve ser {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout deve ser {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns deve ser 1 ou mais @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout deve ser gridByRow, gridByColumn, row ou column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft deve ser true ou false @@ -10586,7 +10586,7 @@ swatch Yellow Green Verde-amarelado @msg unknown Warp style estilo de Deformação desconhecido @msg unknown alignToPath `{a}` alignToPath desconhecido `{a}` @msg unknown arrowhead {v} ponta de seta desconhecida {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) chave de artboardLayout desconhecida `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) chave de artboardLayout desconhecida `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` atributo desconhecido `{attribute}` @msg unknown attribute `{k}` atributo desconhecido `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) eixo desconhecido `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..8b4d52e7c2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9406,7 +9406,7 @@ shape Open Открытый @msg artboard is a 0-based index artboard — индекс, отсчитываемый от 0 @msg artboard must be a 0-based index artboard должно быть индексом, отсчитываемым от 0 @msg artboard {i} doesn't print монтажная область {i} не печатается -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout должно быть {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout должно быть {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns должно быть 1 или больше @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout должно быть gridByRow, gridByColumn, row или column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft должно быть true или false @@ -10503,7 +10503,7 @@ shape Open Открытый @msg unknown Warp style неизвестный стиль деформации @msg unknown alignToPath `{a}` неизвестное значение alignToPath `{a}` @msg unknown arrowhead {v} неизвестная стрелка {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) неизвестный ключ artboardLayout `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) неизвестный ключ artboardLayout `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` неизвестный атрибут `{attribute}` @msg unknown attribute `{k}` неизвестный атрибут `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) неизвестная ось `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..49fe6f130a 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9079,7 +9079,7 @@ digits Hindi Hindi @msg artboard {i} doesn't print rityta {i} skrivs inte ut @msg artboard is a 0-based index artboard är ett 0-baserat index @msg artboard must be a 0-based index artboard måste vara ett 0-baserat index -@msg artboardLayout must be {{layout?, columns?, spacing?, rightToLeft?}} artboardLayout måste vara {{layout?, columns?, spacing?, rightToLeft?}} +@msg artboardLayout must be {{layout?, columns?, rows?, spacing?, rightToLeft?}} artboardLayout måste vara {{layout?, columns?, rows?, spacing?, rightToLeft?}} @msg artboardLayout.columns must be 1 or more artboardLayout.columns måste vara 1 eller mer @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout måste vara gridByRow, gridByColumn, row eller column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft måste vara true eller false @@ -10024,7 +10024,7 @@ digits Hindi Hindi @msg unknown align `{other}` okänd justering `{other}` @msg unknown alignToPath `{a}` okänt alignToPath-värde `{a}` @msg unknown arrowhead {v} okänd pilspets {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) okänd artboardLayout-nyckel `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) okänd artboardLayout-nyckel `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` okänt attribut `{attribute}` @msg unknown attribute `{k}` okänt attribut `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) okänd axel `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..1db24be787 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -8400,7 +8400,7 @@ axis Y Axis Y ekseni @msg artboard is a 0-based index artboard 0 tabanlı bir dizindir @msg artboard must be a 0-based index artboard 0 tabanlı bir dizin olmalıdır @msg artboard {i} doesn't print {i} numaralı çalışma yüzeyi yazdırılmıyor -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout {layout?, columns?, spacing?, rightToLeft?} olmalıdır +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout {layout?, columns?, rows?, spacing?, rightToLeft?} olmalıdır @msg artboardLayout.columns must be 1 or more artboardLayout.columns 1 veya daha büyük olmalıdır @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout gridByRow, gridByColumn, row veya column olmalıdır @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft true veya false olmalıdır @@ -9296,7 +9296,7 @@ axis Y Axis Y ekseni @msg unknown Warp style bilinmeyen Çarpıtma stili @msg unknown alignToPath `{a}` bilinmeyen alignToPath `{a}` @msg unknown arrowhead {v} bilinmeyen ok ucu {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) bilinmeyen artboardLayout anahtarı `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) bilinmeyen artboardLayout anahtarı `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` bilinmeyen öznitelik `{attribute}` @msg unknown attribute `{k}` bilinmeyen öznitelik `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) bilinmeyen eksen `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..f638a75fea 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9062,7 +9062,7 @@ breakText Glyphs Гліфи @msg artboard is a 0-based index artboard — це індекс, що починається з 0 @msg artboard must be a 0-based index artboard має бути індексом, що починається з 0 @msg artboard {i} doesn't print монтажна область {i} не друкується -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout має бути {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout має бути {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns має бути 1 або більше @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout має бути gridByRow, gridByColumn, row або column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft має бути true або false @@ -10161,7 +10161,7 @@ breakText Glyphs Гліфи @msg unknown Warp style невідомий стиль деформації @msg unknown alignToPath `{a}` невідомий alignToPath `{a}` @msg unknown arrowhead {v} невідома стрілка {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) невідомий ключ artboardLayout `{k}` (layout, columns, spacing, rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) невідомий ключ artboardLayout `{k}` (layout, columns, rows, spacing, rightToLeft) @msg unknown attribute `{attribute}` невідомий атрибут `{attribute}` @msg unknown attribute `{k}` невідомий атрибут `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) невідома вісь `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..06d3c77264 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9420,7 +9420,7 @@ breakText Glyphs 字形 @msg artboard is a 0-based index artboard 是从 0 开始的索引 @msg artboard must be a 0-based index artboard 必须是从 0 开始的索引 @msg artboard {i} doesn't print 画板 {i} 不打印 -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout 必须是 {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout 必须是 {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns 必须大于或等于 1 @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout 必须是 gridByRow、gridByColumn、row 或 column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft 必须为 true 或 false @@ -10319,7 +10319,7 @@ breakText Glyphs 字形 @msg unknown Warp style 未知的变形样式 @msg unknown alignToPath `{a}` 未知的 alignToPath `{a}` @msg unknown arrowhead {v} 未知的箭头 {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) 未知的 artboardLayout 键 `{k}` (layout、columns、spacing、rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) 未知的 artboardLayout 键 `{k}` (layout、columns、rows、spacing、rightToLeft) @msg unknown attribute `{attribute}` 未知的属性 `{attribute}` @msg unknown attribute `{k}` 未知的属性 `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) 未知的轴 `{other}` (vertical|horizontal|free) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..2185dbf4f6 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9356,7 +9356,7 @@ breakText Glyphs 字符 @msg artboard is a 0-based index artboard 是從 0 起算的索引 @msg artboard must be a 0-based index artboard 必須是從 0 起算的索引 @msg artboard {i} doesn't print 工作區域 {i} 不會列印 -@msg artboardLayout must be {layout?, columns?, spacing?, rightToLeft?} artboardLayout 必須是 {layout?, columns?, spacing?, rightToLeft?} +@msg artboardLayout must be {layout?, columns?, rows?, spacing?, rightToLeft?} artboardLayout 必須是 {layout?, columns?, rows?, spacing?, rightToLeft?} @msg artboardLayout.columns must be 1 or more artboardLayout.columns 必須大於或等於 1 @msg artboardLayout.layout must be gridByRow, gridByColumn, row or column artboardLayout.layout 必須是 gridByRow、gridByColumn、row 或 column @msg artboardLayout.rightToLeft must be true or false artboardLayout.rightToLeft 必須是 true 或 false @@ -10255,7 +10255,7 @@ breakText Glyphs 字符 @msg unknown Warp style 未知的彎曲樣式 @msg unknown alignToPath `{a}` 未知的 alignToPath `{a}` @msg unknown arrowhead {v} 未知的箭頭 {v} -@msg unknown artboardLayout key `{k}` (layout, columns, spacing, rightToLeft) 未知的 artboardLayout 鍵 `{k}` (layout、columns、spacing、rightToLeft) +@msg unknown artboardLayout key `{k}` (layout, columns, rows, spacing, rightToLeft) 未知的 artboardLayout 鍵 `{k}` (layout、columns、rows、spacing、rightToLeft) @msg unknown attribute `{attribute}` 未知的屬性 `{attribute}` @msg unknown attribute `{k}` 未知的屬性 `{k}` @msg unknown axis `{other}` (vertical|horizontal|free) 未知的軸 `{other}` (vertical|horizontal|free) diff --git a/docs/mcp.md b/docs/mcp.md index 8f8fc434cc..ec64203f77 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2637,8 +2637,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A - `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a - `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + `presetSettings` that is omitted, `undefined` or `null` gives the preset's settings unchanged; any other value + that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. The + `DocumentPreset` objects of one run hold at most 16 MiB of settings together; an assignment past that throws a + `RangeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of @@ -2692,9 +2694,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or - with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, - letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when - the automation read roots allow its file, and that check can look the document's file up on disk. A path with + with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (on Windows and in a + path with a drive letter, letter case is ignored and `\` matches `/`; elsewhere `\` is part of a name) and does + not resolve the path it is given. A document counts only when the automation read roots allow its file, and that + check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members From a278d6a837885531f878d72d1ac0773f052e1f2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 21:51:12 -0800 Subject: [PATCH 050/153] Scripts: a path in a selected group reads as selected with its own picks too When a group or compound path is selected together with one of its paths, and that path also has its own anchor or segment pick, selectedPathPoints and PathPoint.selected now report the path as selected as a whole, as docs/mcp.md says for a path in a selected group. Before, the path's own pick was reported instead. --- crates/engine/src/script/dom/paths.rs | 6 +++--- crates/engine/src/tests/script_dom_paths.rs | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ddd0853d3a..0942ebe880 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1384,10 +1384,10 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { Ok(path_ref(h, item)) } -/// Whether the path `id` is not selected itself but a group or compound path that holds it is, -/// which selects the path as a whole. +/// Whether a group or compound path that holds the path `id` is selected, which selects the path +/// as a whole whatever the path's own selection is. fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool { - !sel.contains(id) && d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) + d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer()))) } /// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 17d9969387..bb73f4175d 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -959,6 +959,20 @@ fn a_path_in_a_selected_group_or_compound_path_is_selected_as_a_whole() { } } +#[test] +fn a_path_in_a_selected_group_reads_as_a_whole_when_its_own_anchors_are_also_picked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + let group = s.active().unwrap().doc.parent_of(a).unwrap(); + s.execute("select.set", &json!({"ids": [group.0, a.0]})).unwrap(); + s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 1]]}], "mode": "subtract"})).unwrap(); + assert!(s.active().unwrap().selection.contains(group), "the group stays selected"); + assert!(s.active().unwrap().selection.partial(a).is_some(), "the path has its own anchor selection"); + let out = log(&mut s, "var p = app.activeDocument.pathItems[0]; vc.log([p.selectedPathPoints.length, p.pathPoints[1].selected]);"); + assert_eq!(out, vec![json!([4, "PathPointSelection.ANCHORPOINT"])]); +} + #[test] fn reading_selected_while_moving_points_writes_the_path_once() { let (mut s, a, _) = doc(); From ab85d735c949791cf49d2b1bc6b5172af8f30cdf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:00:02 -0800 Subject: [PATCH 051/153] New Document: Columns follows a preset's rows in the framework dialog The New Document dialog that main moved to the framework showed a preset's stored column count for a grid by column made with file.new's rows, and kept the rows when the layout or Columns changed. Columns now shows the columns those rows give the current number of artboards, a new layout keeps that count, and a new column count replaces the rows, as the dialog did before the move. --- crates/ui-egui/src/dialogs/new_document.rs | 53 ++++++++++++++++++++-- 1 file changed, 50 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index e60e9e0b3a..eb37e9674d 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -469,6 +469,31 @@ fn advanced(ui: &mut egui::Ui, s: &mut DocSettings) { } } +/// The columns Columns shows: those a grid by column made with `file.new`'s `rows` gives the +/// current number of artboards, otherwise the stored count, at least 1 and at most the artboards. +fn shown_columns(s: &DocSettings) -> u32 { + if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { + return u32::try_from(s.grid_columns()).unwrap_or(MAX_ARTBOARDS); + } + s.columns.max(1).min(s.artboards.max(1)) +} + +/// Sets the artboard layout. A new layout replaces the rows of a preset made with `file.new`'s +/// `rows` with the column count Columns showed for them. +fn set_layout(s: &mut DocSettings, layout: ArtboardLayout) { + if s.rows > 0 { + s.columns = shown_columns(s); + s.rows = 0; + } + s.layout = layout; +} + +/// Sets the column count, which replaces the rows of a preset made with `file.new`'s `rows`. +fn set_columns(s: &mut DocSettings, columns: u32) { + s.rows = 0; + s.columns = columns; +} + /// More Settings' pop-up: the artboard layout, spacing and columns. All three are off with one /// artboard, Columns also for the row and column layouts; columns stay within the artboards. fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { @@ -479,7 +504,7 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { Field::new(layout.clone()).show(ui, |ui, _| { let entries: Vec> = ArtboardLayout::ALL.iter().map(|l| Entry::new(*l, text(tl!(l.label())))).collect(); if let Some(l) = Segmented::new(layout.clone(), Bind::given(s.layout), &entries).enabled(several).show(ui).value().copied() { - s.layout = l; + set_layout(s, l); } }); let rtl = Checkbox::new(Bind::given(s.right_to_left)).label(right_to_left).enabled(several).show(ui); @@ -494,10 +519,10 @@ fn more_settings(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUnits) { }); Field::new(columns.clone()).show(ui, |ui, _| { let n = f64::from(s.artboards.max(1)); - let shown = f64::from(s.columns.max(1)).min(n); + let shown = f64::from(shown_columns(s)); let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid); if let Some(v) = field.show(ui).value().copied().flatten().filter(|v| v.is_finite()) { - s.columns = v.round().clamp(1.0, n) as u32; + set_columns(s, v.round().clamp(1.0, n) as u32); } }); } @@ -1005,4 +1030,26 @@ mod tests { assert!(!dir.join("Print.vectorcraft").exists()); let _ = std::fs::remove_dir_all(&dir); } + + /// A preset made with `file.new`'s `rows`: Columns shows the columns those rows give the + /// current artboards, and a new layout keeps them while a new column count replaces the rows. + #[test] + fn columns_follow_a_presets_rows_until_the_layout_or_columns_change() { + let made = |layout, artboards| DocSettings { layout, artboards, columns: 2, rows: 4, ..DocSettings::default() }; + for (artboards, shown) in [(5, 2), (9, 3), (2, 1)] { + assert_eq!(shown_columns(&made(ArtboardLayout::GridByColumn, artboards)), shown, "{artboards} artboards"); + } + assert_eq!(shown_columns(&made(ArtboardLayout::GridByRow, 9)), 2, "a grid by row shows the stored columns"); + for to in [ArtboardLayout::GridByRow, ArtboardLayout::Row, ArtboardLayout::Column] { + let mut s = made(ArtboardLayout::GridByColumn, 9); + set_layout(&mut s, to); + assert_eq!((s.layout, s.columns, s.rows), (to, 3, 0), "{to:?}"); + } + let mut s = made(ArtboardLayout::GridByRow, 9); + set_layout(&mut s, ArtboardLayout::GridByColumn); + assert_eq!((s.columns, s.rows, shown_columns(&s)), (2, 0, 2), "the columns a grid by row showed stay"); + let mut s = made(ArtboardLayout::GridByColumn, 9); + set_columns(&mut s, 5); + assert_eq!((s.columns, s.rows, shown_columns(&s)), (5, 0, 5)); + } } From 6cf8b4606ac47f48c22a3986e036f92acdae5d98 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:41:14 -0800 Subject: [PATCH 052/153] JavaScript: module code drops each expression statement's value Module code was compiled as eval code, so every expression statement stored its value as the completion value. A module never reads that value, and the stored value stayed reachable until the module finished, so a large temporary result counted against the heap limit for the rest of the module. Module code now pops the value, as function code does. Script and eval code keep their completion values, including through finally blocks. --- crates/js/src/compiler.rs | 14 ++++++++++++-- crates/js/src/module_tests.rs | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index 714211ef85..bb76d8621d 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -90,6 +90,8 @@ struct FnCompiler<'a> { recursion: u32, /// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own. es2015: bool, + /// The code is a module's ([`compile_module`]), which has no completion value. + module: bool, scopes: Vec, templates: Vec