diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..e3ff66fc1c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings). +crates/cad/tests/data/*.dxf -text diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 507caffe10..6b6099e7b6 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -130,7 +130,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", diff --git a/assets/app-icon/vectorcraft-nightly.png b/assets/app-icon/vectorcraft-nightly.png index 4211c1ddb8..09b2747606 100644 Binary files a/assets/app-icon/vectorcraft-nightly.png and b/assets/app-icon/vectorcraft-nightly.png differ diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index ef42eec957..ba5bb3b974 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,82 @@ 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; +/// 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, 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 +/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is +/// 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 }); + if passes(srgb) { + return Some(srgb); + } + 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| 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. + 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 +214,80 @@ 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}"); + } + + /// 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]; + 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 b9fd0b98e6..8a4e6ebe6f 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -851,11 +851,12 @@ 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::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines}; +pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop}; /// Document Info's category titles, the Objects category's count labels, and how its image rows /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; pub use docmenu::guide_indexes; -pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index bb5d8655e9..4a4b998782 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -160,7 +160,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` or while the active tool paints with the proxy's 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 art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}", + "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), @@ -1066,7 +1066,229 @@ 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 row, object, groups and layer, each with its blend mode and opacity over the art below +/// 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 levels the color is drawn through, innermost first, without those that leave it as it is. + 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 +/// 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), + 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 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() } + } +} + +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, + } + } + + /// 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)); + 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 + /// the background. + pub fn ratio(&self, shown: [f32; 3]) -> f64 { + 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; + 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). 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) -> Option { + let cms = vectorcraft_color::cms::active(); + let ratio = |srgb: [f32; 3]| { + let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color)); + backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown)) + }; + if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum { + return None; + } + let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.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 ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &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) { + 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)> { + 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) { @@ -1078,23 +1300,28 @@ 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) = 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| 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); + // 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) => { @@ -1130,60 +1357,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result { // then takes that art back out by the alpha of what it holds drawn alone, and blends the rest: // `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity // applies to what it holds, and the art beside it in the level around it adds to the alpha once. + // The alphas, the art below each level and `alone` do not depend on the color, so each level + // is read once here and [`Backdrop::front`] draws any color through the levels. let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate; - let mut x = (shown(&color), 1.0f32); + 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 && x.1 >= 1.0 && alone >= 1.0 { + if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 { continue; } let above = &steps[k + 1..]; 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), }; - let source = if !blends(step) { - x - } else if alone <= 0.0 { - (x.0, 0.0) - } else { - (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone) - }; - // A level that isolates its blending carries out the alpha of what it holds composited on - // its own. - let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0); - x = composite(step.blend, source, step.opacity, backdrop); - alone = drawn + inner * (1.0 - drawn); - } - let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) }; - 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 }), + // 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 [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 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, !need_color) }; + 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 @@ -1266,7 +1484,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32; /// levels that change what they draw must be the same objects too, since the art below each one is /// read with that object hidden, and the object's opacity must be the same apart from its row's, /// since the row draws over the object's rows below it and the object over the art behind it, and a -/// row that blends or is translucent must lie over the same shown rows. +/// row that blends or is translucent must lie over the same shown rows, and over a lower row that +/// blends, with the same isolation. fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0); let level = |x: &Level, y: &Level| { @@ -1282,10 +1501,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1); // A row that blends or lets art through draws over the rows below it, read at one point. let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0); + // A lower row that blends reads the art behind the object unless the object isolates its + // blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending + // row at no opacity does not show, nor does a fill row without effects under an opaque solid + // Normal fill row without effects, which covers the same shape (a stroke reaches outside it). + let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty(); + let covers = |i: &vectorcraft_doc::AppearanceItem| { + plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. }) + }; + let over_blended = |d: &Drawn| { + over_rows(d) + && d.lower + .iter() + .enumerate() + .any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers))) + }; row(a) == row(b) && (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower) && a.blend == b.blend && (row(a).is_none() || a.isolate == b.isolate) + && (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate) && (given_opacity || (total(a) - total(b)).abs() < 1e-6) && (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6) && la.len() == lb.len() @@ -1297,8 +1532,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 } { @@ -1354,20 +1590,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((stained(s, 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 @@ -1432,19 +1676,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower }) } -/// `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. For a pick (`pick`), a proxy of None +/// or a pattern counts too, as the pick puts a solid color in its place. +fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> { + let (fill, stroke) = s.proxy_paints(); + match if s.fill_active { fill } else { stroke } { + Paint::Solid { .. } => {} + Paint::None | Paint::Pattern { .. } if pick => {} + _ => return None, } + let st = s.active()?; + let sp = st.selection.symbol_part.as_ref()?; + 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 objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and @@ -1489,14 +1735,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(); @@ -1625,8 +1871,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 { @@ -1636,10 +1884,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/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 37f4b132b5..1d6bd59fd1 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD +/// file with many more pixels keeps its corners when the image is tiny: the new image's transform +/// is the old one scaled down to the new pixel size, which is invertible however small it is. +#[test] +fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() { + let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted"); + let plane = vec![255u8; 2000 * 2000]; + let zero = vec![0u8; 2000 * 2000]; + let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero])); + let cut = write_file(&dir, "big.psd", &big); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let png = crate::tests_links::png(4, 4, [0, 0, 255]); + let r = s + .execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]})) + .unwrap(); + let old = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [old.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap(); + assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted"); + let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap(); + let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone(); + assert!(image.is_distorted_image()); + assert_eq!(image.image_corners().unwrap(), corners); +} + +/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort +/// by a DCS file keeps the image's corners: the DCS file's image fills them. +#[test] +fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() { + let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates()); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap(); + let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone(); + assert!(new.is_distorted_image(), "the DCS file's image takes the corners"); + assert_eq!(new.image_corners().unwrap(), corners); +} + /// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective /// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners, /// a clip group of the old file's clipping path loses it when the new file names none, and a later diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index cc210ffa2a..ded0f137b3 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() { } } +/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes +/// its corners, and its slices cover what the corners put their part of the pixels on. +#[test] +fn slices_placed_over_a_distorted_image_follow_its_corners() { + let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[])); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let png = crate::tests_links::png(4, 4, [0, 0, 255]); + s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap(); + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap(); + assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}"); + let d = &s.doc().unwrap().doc; + let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert!(image.is_distorted_image()); + let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") }; + // The top left quarter of the 20 × 20 px canvas. + let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0); + let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap(); + let got = slices(&s)[0].0; + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}"); +} + #[test] fn linked_files_are_placed_without_their_slices() { let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id())); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index de6f945b58..65f268f2b0 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1314,7 +1314,7 @@ fn refill_distorted( /// `path` with its anchors and handles mapped through `map` as a distort maps a path's points /// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front /// of it, and one past it to the far side. `None` when a point maps to no finite page point. -fn warped(path: &PathData, map: &Homography) -> Option { +pub(super) fn warped(path: &PathData, map: &Homography) -> Option { let [[a, b, c], [d, e, f], [g, h, i]] = map.0; let apply = |p: vectorcraft_geom::Point| { let w = g * p.x + h * p.y + i; diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index c277af5c28..58612c744c 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -57,7 +57,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes}; -use vectorcraft_geom::{Affine, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes}; use vectorcraft_pdf::CropTo; use super::fileio::{self, Format, RasterImage}; @@ -88,7 +88,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed order (returned object order without layers), embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result> { /// The transform that puts new art with the natural box `natural` where `old` is: an image's scale /// and rotation relative to its 100% size (its resolution's) and its centre are kept (with -/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by +/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by /// its file's clipping path or not (`new_image`); other objects keep their centre. fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine { let image = replace_measured(d, old, new_image); @@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes))); let full = Affine::scale_non_uniform(sx, sy); let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0); - if im.xf.determinant().abs() > 1e-12 { + if Homography::affine_is_invertible(im.xf) { return im.xf * full.inverse() * Affine::translate(centre - natural.center()); } } @@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image } /// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as -/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an -/// image (`new_image`), except a DCS file's plates; else `old` itself. +/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a +/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself. fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node { match &old.kind { NodeKind::Group { children, clip: true } if new_image => match &children[..] { @@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod } } +/// What Replace does when the image it measures, `old`, is distorted and the art placed is a +/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s +/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and +/// the map from the art's natural box to the page through those corners, which a PSD file's slices +/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't +/// fill ([`Node::set_image_corners`]). +fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> { + let NodeKind::Image(im) = &old.kind else { return None }; + let q = old.image_quad()?; + let (pixels, width, height) = match art { + Art::Image(img, _) => { + let (sx, sy) = pt_per_px(img.ppi); + (Affine::scale_non_uniform(sx, sy), img.width, img.height) + } + Art::Dcs(a) => (a.xf, a.img.width, a.img.height), + _ => return None, + }; + if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) { + return None; + } + let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height)); + let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None }; + let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new))); + probe.set_image_corners(q).ok()?; + let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?; + Some((xf * pixels.inverse(), q, page)) +} + +/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as +/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping +/// path is drawn through them as the pixels are. `None` when the corners can't hold the image. +fn with_corners(mut node: Node, q: [Point; 4]) -> Option { + match &mut node.kind { + NodeKind::Image(_) => node.set_image_corners(q).ok()?, + NodeKind::Group { children, clip: true } => { + let [path, image] = &mut children[..] else { return None }; + let image = Arc::make_mut(image); + let NodeKind::Image(im) = &image.kind else { return None }; + if !Homography::affine_is_invertible(im.xf) { + return None; + } + // The clipping path in the image's pixels, which its transform placed on the page. + let to_pixels = im.xf.inverse(); + image.set_image_corners(q).ok()?; + let map = image.image_map()?; + let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None }; + p.transform(to_pixels); + *p = super::links::warped(p, &map)?; + } + _ => return None, + } + Some(node) +} + /// `rect` fitted with `natural`'s aspect, centred. fn fit(natural: Rect, r: Rect) -> Affine { let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b); @@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { loaded.natural = Rect::from_origin_size(Point::ORIGIN, size); } let natural = loaded.natural; - // Replace keeps the transform of the image it measures (`replace_measured`), which a - // distortion's corners do not follow. Type, and any other object it measures, is placed by the - // bounds of what it replaces, so a distorted image there is not refused. + // Replace keeps the transform of the image it measures (`replace_measured`). When that image + // is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other + // art is refused. Type, and any other object it measures, is placed by the bounds of what it + // replaces, so a distorted image there is not refused. + let mut distorted = None; + let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..)); if let Some(o) = old_node && !is_text { - let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..))); + let image = replace_measured(&st.doc, o, new_image); if image.is_distorted_image() { - return Err(super::xform::distorted_image_error(PLACE, image.id)); + let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?; + distorted = Some((image.id, fit)); } } let m = match (old_node, rect) { - (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))), + (Some(_), _) if let Some((_, (m, ..))) = distorted => m, + (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image), (None, Some(r)) => fit(natural, r), // Its artboard's bottom-left corner on the target's. (None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)), @@ -908,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { if let Art::Dcs(a) = &loaded.art { warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); } - // A PSD file's slices move and scale with its art; one that would leave the canvas is left out. + // A PSD file's slices move and scale with its art, through a distorted image's corners when + // it takes them; one that would leave the canvas is left out. let read_count = read_slices.len(); let slices: Slices = read_slices .into_iter() .filter_map(|(r, o)| { - let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); - let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)); + let placed = match distorted { + Some((_, (_, _, page))) => page.map_rect_bbox(r)?, + None => { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); + corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)) + } + }; super::slices::slice_rect_ok(placed).then_some((placed, o)) }) .collect(); @@ -924,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), } let (id, size, slice_ids) = s.edit("Place", |d, sel| { - let node = transformed(build(d, loaded, link), m); + let mut node = transformed(build(d, loaded, link), m); + if let Some((old_image, (_, q, _))) = distorted { + node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?; + } let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); let (into, index) = match old { Some(old) => { diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index d895c3969f..194df59e51 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (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; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; 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 (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; 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 (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (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 ), @@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result { if s.script_frames && !answers.is_empty() { return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog")); } + let actions = script::actions::parse(p.get("actions")).map_err(param)?; let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; let mut checked_real = None; @@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result { fuel, locale, answers, + actions, }) } @@ -442,6 +444,7 @@ impl Session { fuel, locale, answers: vec![], + actions: vec![], }; let runs = self.script_runs; self.script_start(request).map_err(|e| { diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d9c575eeae..47eccccba9 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -148,8 +148,11 @@ macro_rules! style_cmds { }; } +/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes. +pub const MAX_LOAD_BYTES: usize = 64 << 20; + /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec { let mut v = style_cmds!( @@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { _ => "textStyle.loadAll".to_string(), }; let path = str_param(p, "path"); - let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file(path)?, - (None, Some(text), _) => text.as_bytes().to_vec(), - (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, + let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); + let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(), + (None, Some(text), _) => text.as_bytes().into(), + (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), + (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(), _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; + if bytes.len() > MAX_LOAD_BYTES { + return Err(too_large()); + } let file = str_param(p, "name").or(path).unwrap_or("Styles"); let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?; if src.preview_only { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 2939657c55..fffd80f2c5 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -896,6 +896,27 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } +/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit. +#[test] +fn loading_refuses_a_file_larger_than_64_mb() { + let (mut s, _) = session_with_text("Title"); + let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Big.vectorcraft"); + std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); + let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let text = " ".repeat(MAX_LOAD_BYTES + 1); + let r = s.execute("textStyle.loadAll", &json!({"data": text})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + assert_eq!(s.doc().unwrap().doc, before); +} + /// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or /// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped. #[test] diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 791143f53b..03a7619e61 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -127,6 +127,12 @@ impl HistoryEntry { self.effect.filter(|id| effect_step_label(id) == Some(self.label.as_str())) } + /// 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/engine/src/lib.rs b/crates/engine/src/lib.rs index 46e6c04343..2cdb0f6239 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -373,6 +373,9 @@ pub struct Session { pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, + /// The styles the steps of a batch a script runs removed or renamed and the documents they + /// reverted ([`script::note_style_lists`]). + pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// The desktop app supplies each window by (document uid, runtime window identity) while a diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs new file mode 100644 index 0000000000..2abb290cf7 --- /dev/null +++ b/crates/engine/src/script/actions.rs @@ -0,0 +1,354 @@ +//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's +//! run, as the VBScript reference's `DoScript` method of the Application object describes it +//! (). +//! +//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps +//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app +//! they are the Actions panel's. +//! +//! VectorCraft's own rules, which the reference does not state: +//! - The action and its set are matched by their exact names; a name that matches no action, or +//! more than one, throws before any step runs. +//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins +//! the run's transaction and its one undo step for each changed document, it is counted as a host +//! call, it reads and writes files only where the script may, and a step that fails is put back +//! and throws an error that names the step and the action, while the steps before it stay done. +//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine +//! does not have (a View menu step, or one that plays an action), and a stop throw before any step +//! runs, as does such a command among those an `action.batch` step plays. An action cannot play +//! another action, so it cannot play itself. +//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it +//! changes nothing. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Host, Link, command, current, refused_to_scripts}; + +/// The most actions a run's request may carry. +pub const MAX_ACTIONS: usize = 4096; +/// The most steps one action may have, after a `command.batch` step gives its own steps. +pub const MAX_ACTION_STEPS: usize = 10_000; +/// The most steps the actions of one request may have in all. +pub const MAX_ALL_STEPS: usize = 100_000; +/// The most bytes of the request's actions, as JSON. +pub const MAX_ACTIONS_BYTES: usize = 16 << 20; +/// The longest name of an action or a set, in bytes. +pub const MAX_NAME_BYTES: usize = 1024; +/// The longest command id of a step, in bytes. +const MAX_ID_BYTES: usize = 256; +/// The command id of a stop, which waits for the person in the Actions panel. +pub const STOP_STEP: &str = "action.stop"; + +/// An action a run can play: its set's name, its name and the steps playback runs. +#[derive(Clone, Debug)] +pub struct Playable { + set: String, + name: String, + steps: Vec, +} + +/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a +/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and +/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names. +#[derive(Clone, Debug)] +struct Step { + place: String, + id: String, + params: Value, + bytes: u64, + artboard: Option, +} + +/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the +/// step's place in the action (1 for the first; default its place in the list), within the limits +/// above. A `command.batch` step gives its own steps, each at the batch's place and its own. +pub fn parse(v: Option<&Value>) -> Result, String> { + let Some(v) = v else { return Ok(Vec::new()) }; + let Value::Array(list) = v else { return Err("`actions` must be a list".into()) }; + if list.len() > MAX_ACTIONS { + return Err(format!("`actions` holds more than {MAX_ACTIONS} actions")); + } + if let Some(place) = super::too_deep(v) { + return Err(format!("`actions{place}` is nested more than 64 levels deep")); + } + if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) { + return Err("`actions` is larger than 16 MiB".into()); + } + let mut all = 0usize; + let mut out = Vec::with_capacity(list.len()); + for (i, a) in list.iter().enumerate() { + let at = format!("`actions[{i}]`"); + let Value::Object(a) = a else { return Err(format!("{at} must be an object")) }; + only_keys(a, &["set", "name", "steps"], &at)?; + let set = name_of(a, "set", &at)?; + let name = name_of(a, "name", &at)?; + let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) }; + let mut steps = Vec::new(); + for (j, s) in given.iter().enumerate() { + let at = format!("{at}.steps[{j}]"); + let Value::Object(s) = s else { return Err(format!("{at} must be an object")) }; + only_keys(s, &["command", "params", "step"], &at)?; + let place = match s.get("step") { + None => (j + 1).to_string(), + Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) { + Some(n) => n.to_string(), + None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")), + }, + }; + let (id, params) = command_of(s, &at)?; + match params.get("commands") { + Some(Value::Array(inner)) if id == "command.batch" => { + // The batch's `artboard`, for its steps that act on the active artboard, as + // `command.batch` reads it. + let artboard = params.get("artboard").and_then(Value::as_u64); + for (k, c) in inner.iter().enumerate() { + let at = format!("{at}.params.commands[{k}]"); + let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; + let (id, params) = command_of(c, &at)?; + if id == "command.batch" { + return Err(format!("{at} is a command.batch inside a command.batch")); + } + steps.push(step(format!("{place}.{}", k + 1), id, params, artboard)); + } + } + _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), + _ => steps.push(step(place, id, params, None)), + } + if steps.len() > MAX_ACTION_STEPS { + return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); + } + } + all += steps.len(); + if all > MAX_ALL_STEPS { + return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all")); + } + out.push(Playable { set, name, steps }); + } + Ok(out) +} + +impl Playable { + /// The steps the action runs. + pub fn len(&self) -> usize { + self.steps.len() + } + + /// Whether the action runs no step. + pub fn is_empty(&self) -> bool { + self.steps.is_empty() + } +} + +fn only_keys(o: &Map, keys: &[&str], at: &str) -> Result<(), String> { + match o.keys().find(|k| !keys.contains(&k.as_str())) { + Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))), + None => Ok(()), + } +} + +fn name_of(o: &Map, key: &str, at: &str) -> Result { + match o.get(key) { + Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()), + Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")), + _ => Err(format!("{at}.{key} must be a string")), + } +} + +/// A step's `command` and `params` (default `{}`). +fn command_of(o: &Map, at: &str) -> Result<(String, Value), String> { + let id = match o.get("command") { + Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(), + _ => return Err(format!("{at}.command must be a command id")), + }; + let params = match o.get("params") { + None => json!({}), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(format!("{at}.params must be an object")), + }; + Ok((id, params)) +} + +fn step(place: String, id: String, params: Value, artboard: Option) -> Step { + let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); + Step { place, id, params, bytes, artboard } +} + +/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters +/// as U+FFFD. +fn shown(text: &str) -> String { + const MAX: usize = 80; + let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect(); + if text.chars().nth(MAX).is_some() { + out.push('…'); + } + out +} + +/// The members of `app` this module adds. +pub(super) fn app_members(link: &Link) -> Vec { + let l = link.clone(); + let play = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + do_script(&h, &a) + }); + let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]); + let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)]; + members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name))); + members +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// `app.doScript(action, set, dialogs?)`, its arguments after `this`. +fn do_script(h: &Host, a: &[Data]) -> std::result::Result { + if a.len() > 4 { + return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into())); + } + let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else { + return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into())); + }; + if action.is_empty() || set.is_empty() { + return Err(HostError::Error("doScript needs the action's name and its set's name".into())); + } + if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES { + return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes"))); + } + if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) { + return Err(HostError::Type("doScript's dialogs must be true or false".into())); + } + let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); + let p = match found.as_slice() { + [p] => *p, + [] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), + [] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))), + _ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))), + }; + if p.steps.is_empty() { + return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); + } + // Every step is checked before the first runs, so a step that cannot run leaves the documents as + // they were. + for s in &p.steps { + if let Some((place, id)) = refused_step(s) { + let name = shown(&p.name); + return Err(HostError::Error(if id == STOP_STEP { + format!("step {place} of “{name}” is a stop, which a script cannot wait at") + } else { + format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id)) + })); + } + } + for s in &p.steps { + // A run asked to stop runs no further step; the realm ends it at its next instruction and + // puts the documents back. + if h.session.borrow().script_stop.is_set() { + break; + } + h.charge_call(16 + s.id.len() as u64 + s.bytes)?; + // Saved steps run as they run in the Actions panel: keys their commands no longer read are + // passed over. + let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); + let outer = h.session.borrow_mut().set_replaying(true); + let r = command(h, &s.id, ¶ms); + h.session.borrow_mut().set_replaying(outer); + if let Err(e) = r { + let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id)); + return Err(match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)), + other => other, + }); + } + } + Ok(Data::Undefined) +} + +/// The place and command of the first command step `s` would run that a script may not run: the +/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the +/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the +/// engine does not have are refused. +fn refused_step(s: &Step) -> Option<(String, String)> { + let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none(); + if refused(&s.id) { + return Some((s.place.clone(), s.id.clone())); + } + if s.id != "action.batch" { + return None; + } + let commands = s.params.get("commands").and_then(Value::as_array)?; + commands.iter().enumerate().find_map(|(k, c)| { + let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned())) + }) +} + +/// `params` of step `id`, with the active artboard of the active document added as a +/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for +/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to +/// Selected Art. The active artboard is the index `start` gives for the document (its index as the +/// run started, which the view keeps), past the last artboard the last one, as the view shows it +/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While +/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its +/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh +/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the +/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork +/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the +/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch` +/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past +/// the last artboard the last one, and none in a document without artboards, as `command.batch` +/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit +/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value { + let mut params = params.clone(); + let Some(st) = s.active() else { return params }; + let n = st.doc.artboards.len(); + let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) { + (Some(_), _) if n == 0 => return params, + (Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)), + (None, Some((_, i))) => (*i).min(n.saturating_sub(1)), + (None, None) => super::dom::active_artboard(st), + }; + let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); + let fit_art = id == "artboard.fitToArt"; + let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) { + "artboard" + } else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) { + "index" + } else { + return params; + }; + let Some(p) = params.as_object_mut() else { return params }; + if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) { + return params; + } + let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; + let kept: Vec = match start.picks { + Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => { + list.iter().copied().filter(|i| *i < n).collect() + } + _ => Vec::new(), + }; + if kept.len() >= 2 { + p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept)); + } else if picks.is_empty() { + p.insert(key.into(), json!(active)); + } else if fit_art { + p.insert("indices".into(), json!(picks)); + } + params +} + +/// What [`on_active_artboard`] reads besides the session: the index of each open document's active +/// artboard as the run started, by document uid; the Artboard tool's selection as the run started, +/// with its document's uid; and the `artboard` a step's recorded `command.batch` names. +pub(crate) struct Start<'a> { + pub active: &'a [(u64, usize)], + pub picks: Option<&'a (u64, Vec)>, + pub batch: Option, +} diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index db5786878f..7c50925bf0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -196,19 +196,24 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result HostMember { } /// A member of a class with what `reflect` tells of it. -type Described = (String, HostMember, MemberInfo); +pub(super) type Described = (String, HostMember, MemberInfo); /// A property's or a method's result's type for `reflect`. fn typed(data_type: &str) -> MemberInfo { @@ -301,7 +306,7 @@ fn typed(data_type: &str) -> MemberInfo { } /// A method's result's type and its arguments' names and types, for `reflect`. -fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { +pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); MemberInfo { arguments, ..typed(data_type) } } @@ -309,7 +314,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { /// 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 text range `this` is still there. `hasOwnProperty` is /// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out. -fn later(link: &Link, class: &'static str, name: &'static str) -> Described { +pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -571,7 +576,7 @@ struct Frame { } /// The index of the active artboard of `st`, as the view keeps it. -fn active_artboard(st: &DocState) -> usize { +pub(super) fn active_artboard(st: &DocState) -> usize { let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) } @@ -786,6 +791,11 @@ fn on_doc( Ok(v) } +/// Marks stale the style objects whose styles a command the run ran removed or renamed. +pub(super) fn after_kept_command(h: &Host) { + text::styles::after_command(h); +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -2318,7 +2328,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// The error of `remove()` and `removeAll()` for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; @@ -2672,6 +2682,7 @@ fn classes(link: &Link) -> Vec { ]); application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); application.push(later(l, "Application", "beep")); + application.extend(super::actions::app_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |_: Vec| { @@ -2745,6 +2756,7 @@ fn classes(link: &Link) -> Vec { ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); + document.extend(text::styles::doc_members(l)); document.extend( ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"] .into_iter() diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 8d15f1b19e..998652b81c 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -50,6 +50,7 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod styles; pub(super) mod threads; /// The error of a text range, or of a collection of one, whose frame's text changed other than @@ -201,6 +202,8 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The styles the run's style objects name. + styles: styles::StyleState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1680,14 +1683,13 @@ pub(super) fn classes(l: &Link) -> Vec { range.extend(attr_members(l)); range.push(threads::range_member(l)); range.extend(para_members(l)); + range.extend(styles::range_members(l)); range.extend( [ "lines", "insertionPoints", "textRanges", "kerning", - "characterStyles", - "paragraphStyles", "textSelection", "changeCaseTo", "select", @@ -1786,6 +1788,7 @@ pub(super) fn classes(l: &Link) -> Vec { None, ), ]; + out.extend(styles::classes(l)); out.extend(stories); out } diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs new file mode 100644 index 0000000000..8317e1ae04 --- /dev/null +++ b/crates/engine/src/script/dom/text/styles.rs @@ -0,0 +1,802 @@ +//! Character and paragraph styles in the script object model: `document.characterStyles` and +//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text +//! of a `TextRange` uses, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A document's collection lists its Normal style first, then its other styles in the order the +//! panel lists them. +//! - A style object names its style for the rest of the run, also after the script renames it +//! through `name`. Once the style is removed, or renamed or removed other than through the object +//! model, or its document is closed or reverted with File › Revert, every member throws +//! `Stale style`; a style added later under the same name is another style. +//! - A style name is trimmed, and must then be 1 to 256 characters long with no control +//! characters. +//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the +//! style does not set. Setting one redefines the style: text in the style takes the new value +//! where it had the style's old one and keeps its other changes. +//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words +//! or paragraphs of one, in the style's document. A character style styles exactly that text and +//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches. +//! `clearingOverrides` left out is false; true resets the text to the Normal style first. +//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or +//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in +//! no other style. They do not add or remove styles. +//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its +//! look and is in the Normal style after. +//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`, +//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef}; +use vectorcraft_geom::Point; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref}; + +use super::{ + ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref, + function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text, + text_of, this_range, typename_of, usize_of, whole_span, with_doc, +}; +use crate::DocState; +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs}; +use crate::script::dom::{Described, returns, typed}; + +/// The error of a style object whose style is gone. +pub const STALE_STYLE: &str = "Stale style"; +/// The longest style name, in characters, after trimming. +pub const MAX_STYLE_NAME: usize = 256; +/// The most styles one run's style objects name. +pub const MAX_HELD: usize = 4096; + +/// A style that a run's style objects name: its document and the document's revert count then, its +/// kind and its name now. +struct Slot { + uid: u64, + reverts: u64, + para: bool, + name: String, + live: bool, +} + +/// A document's uid and its character and paragraph style lists when the slots were last checked. +type Seen = (u64, Shared>, Shared>); + +/// The styles a run's style objects name; an object holds its slot's number. +#[derive(Default)] +pub(super) struct StyleState { + slots: RefCell>, + seen: RefCell>, +} + +/// Marks stale each style object whose style the command just run removed or renamed, so a style +/// removed and made again under its name by later commands, or by later steps of the same batch, +/// is another style. A document whose style lists did not change is not checked again. A live +/// slot's style was in its document's list when the command started, so a step that removed or +/// renamed it is in the trail's removed names. +pub(in crate::script) fn after_command(h: &Host) { + let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); + let mut slots = h.dom.text.styles.slots.borrow_mut(); + if !slots.iter().any(|s| s.live) { + return; + } + for slot in slots.iter_mut().filter(|x| x.live) { + if trail.reverted.contains(&slot.uid) + || (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone()))) + { + slot.live = false; + } + } + let s = h.session.borrow(); + let mut seen = h.dom.text.styles.seen.borrow_mut(); + seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); + for st in s.documents() { + let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles)); + if same { + continue; + } + seen.retain(|(uid, ..)| *uid != st.uid); + seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { + slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name); + } + } + for slot in slots.iter_mut().filter(|x| x.live) { + if !s.documents().iter().any(|d| d.uid == slot.uid) { + slot.live = false; + } + } +} + +/// The style objects' state when a savepoint was taken: each slot's name and whether it was +/// live, and the style lists last checked. +pub(in crate::script) struct Mark { + slots: Vec<(String, bool)>, + seen: Vec, +} + +/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored. +pub(in crate::script) fn mark(h: &Host) -> Mark { + let styles = &h.dom.text.styles; + let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect(); + Mark { slots, seen: styles.seen.borrow().clone() } +} + +/// Puts the style objects back as they were at `mark`, after the documents were put back to the +/// savepoint taken with it. A slot added since then stays live only while its document has the +/// style and no older live slot names it. +pub(in crate::script) fn put_back(h: &Host, mark: Mark) { + let styles = &h.dom.text.styles; + let mut slots = styles.slots.borrow_mut(); + let kept = mark.slots.len(); + for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) { + slot.name = name; + slot.live = live; + } + let s = h.session.borrow(); + for i in kept..slots.len() { + let (older, newer) = slots.split_at_mut(i); + let Some(slot) = newer.first_mut() else { break }; + let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name)); + } + *styles.seen.borrow_mut() = mark.seen; +} + +fn normal(para: bool) -> &'static str { + if para { NORMAL_PARA } else { NORMAL_CHAR } +} + +fn cmd(para: bool, verb: &str) -> String { + format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" }) +} + +fn style_class(para: bool) -> &'static str { + if para { "ParagraphStyle" } else { "CharacterStyle" } +} + +fn list_class(para: bool) -> &'static str { + if para { "ParagraphStyles" } else { "CharacterStyles" } +} + +fn defs(st: &DocState, para: bool) -> &Vec { + if para { &st.doc.para_styles } else { &st.doc.char_styles } +} + +/// The document's style names of a kind, the Normal style first. +fn names(st: &DocState, para: bool) -> Vec { + let mut out = vec![normal(para).to_string()]; + out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para))); + out +} + +fn has_style(st: &DocState, para: bool, name: &str) -> bool { + name == normal(para) || defs(st, para).iter().any(|d| d.name == name) +} + +fn stale() -> HostError { + HostError::Error(STALE_STYLE.into()) +} + +fn held_too_many() -> HostError { + HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run")) +} + +/// The style object for the style `name` of the document `uid`: the same slot as every other +/// object naming it in this run. +fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) { + Some(i) => i, + None => { + if slots.len() >= MAX_HELD { + return Err(held_too_many()); + } + slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); + slots.len() - 1 + } + }; + Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)])) +} + +/// A style a style object names. +struct Style { + doc: Doc, + para: bool, + slot: usize, + name: String, +} + +/// The style `d` names, when it is an object of one of `classes` (with the kind each names). +fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result { + let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para))); + let Some((handle, para)) = found else { + return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0)))); + }; + let [run, uid, slot] = handle.as_slice() else { return Err(stale()) }; + let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?; + let slot = usize_of(*slot).ok_or_else(stale)?; + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; + if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) { + s.live = false; + return Err(stale()); + } + Ok(Style { doc, para, slot, name: s.name.clone() }) +} + +fn this_style(h: &Host, a: &[Data]) -> std::result::Result { + style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)]) +} + +/// Marks the slots of the styles `names` of the document `uid` as removed. +fn forget(h: &Host, uid: u64, para: bool, names: &[String]) { + for s in h.dom.text.styles.slots.borrow_mut().iter_mut() { + if s.uid == uid && s.para == para && names.contains(&s.name) { + s.live = false; + } + } +} + +/// A style name a script gave, trimmed. +fn style_name(v: &Data) -> std::result::Result { + let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) }; + if s.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + let t = s.trim(); + if t.is_empty() { + return Err(HostError::Range("a style name must not be empty".into())); + } + if t.chars().count() > MAX_STYLE_NAME { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + if t.chars().any(char::is_control) { + return Err(HostError::Range("a style name must not hold control characters".into())); + } + Ok(t.to_string()) +} + +/// Runs the style command `verb` of the kind on the document of `doc`. +fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result { + on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params)) +} + +// ---- CharacterStyle and ParagraphStyle ---- + +fn style_name_get(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_style(h, a)?.name)) +} + +/// `name = …`: renames the style; the Normal style keeps its name. +fn style_name_set(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let to = style_name(arg(a, 1))?; + if to == style.name { + return Ok(Data::Undefined); + } + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be renamed", style.name))); + } + if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) { + return Err(HostError::Error(format!("a style named {to} already exists"))); + } + run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?; + forget(h, style.doc.uid, style.para, std::slice::from_ref(&to)); + if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) { + s.name = to; + s.live = true; + } + Ok(Data::Undefined) +} + +fn style_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, this_style(h, a)?.doc.uid)) +} + +fn style_typename(h: &Host, a: &[Data]) -> Answer { + Ok(text(style_class(this_style(h, a)?.para))) +} + +fn attributes(h: &Host, a: &[Data], class: &str) -> Answer { + let style = this_style(h, a)?; + Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)])) +} + +fn style_character_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "CharacterStyleAttributes") +} + +fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "ParagraphStyleAttributes") +} + +/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after. +fn style_remove(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be removed", style.name))); + } + run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?; + forget(h, style.doc.uid, style.para, &[style.name]); + Ok(Data::Undefined) +} + +/// The text a style is applied to: a text range, a text frame, or the characters, words or +/// paragraphs of one. +fn target_span(h: &Host, d: &Data) -> std::result::Result { + if handle_of(d, "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, d)?)?.1); + } + const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"]; + if !TEXT.iter().any(|c| handle_of(d, c).is_some()) { + return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into())); + } + span_of(h, d, &TEXT) +} + +/// `applyTo(textItem, clearingOverrides?)`. +fn style_apply_to(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let target = target_span(h, arg(a, 1))?; + let clear = match arg(a, 2) { + Data::Undefined => false, + Data::Bool(b) => *b, + _ => return Err(HostError::Type("clearingOverrides must be true or false".into())), + }; + if target.item.doc.uid != style.doc.uid { + return Err(HostError::Error("the text is in another document than the style".into())); + } + let (index, s, e, _) = resolve(h, target)?; + h.charge_call(16 + (e - s) as u64)?; + let (start, end) = if style.para { + let (_, ba, bb) = para_range(&index, s, e); + (ba, bb) + } else { + // An empty range inside text changes nothing; empty text takes the style on its runs. + if s == e && index.len() > 0 { + return Ok(Data::Undefined); + } + (index.byte(s, false), index.byte(e, true)) + }; + let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end}); + run(h, style.doc, style.para, "apply", &p)?; + Ok(Data::Undefined) +} + +// ---- the attributes of a style ---- + +/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets. +const CHAR_KEYS: [(&str, &str); 11] = [ + ("size", "size"), + ("leading", "leading"), + ("tracking", "tracking"), + ("baselineShift", "baseline_shift"), + ("hScale", "h_scale"), + ("vScale", "v_scale"), + ("rotation", "rotation"), + ("underline", "underline"), + ("strikethrough", "strikethrough"), + ("font", "font_family"), + ("style", "font_style"), +]; + +/// The script's `Justification` members and the alignments a paragraph style stores. +const JUSTIFY: [(&str, &str); 7] = [ + ("LEFT", "Left"), + ("CENTER", "Center"), + ("RIGHT", "Right"), + ("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"), + ("FULLJUSTIFY", "JustifyAll"), +]; + +/// The style an attributes object belongs to and the attributes it sets. +fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map), HostError> { + let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" }; + let style = style_of(h, arg(a, 0), &[(class, para)])?; + let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?; + Ok((style, attrs)) +} + +fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { + let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num); + let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool); + match attr { + Attr::Size => n("size"), + Attr::Leading => n("leading"), + Attr::AutoLeading => match m.get("leading") { + Some(Value::Null) => Data::Bool(true), + Some(v) if v.is_number() => Data::Bool(false), + _ => Data::Undefined, + }, + Attr::Tracking => n("tracking"), + Attr::BaselineShift => n("baseline_shift"), + Attr::HorizontalScale => n("h_scale"), + Attr::VerticalScale => n("v_scale"), + Attr::Rotation => n("rotation"), + Attr::Underline => b("underline"), + Attr::StrikeThrough => b("strikethrough"), + Attr::TextFont => match m.get("font_family").and_then(Value::as_str) { + Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), + None => Data::Undefined, + }, + } +} + +/// The `typename` of a style's `characterAttributes`, which throws once the style is gone. +fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, false)?; + Ok(text("CharacterAttributes")) +} + +/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone. +fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, true)?; + Ok(text("ParagraphAttributes")) +} + +fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { + let (_, m) = attrs_of(h, a, false)?; + Ok(char_value(h, attr, &m)) +} + +/// Redefines the style with `attrs`, unless they are what it has. +fn redefine(h: &Host, style: &Style, old: &Map, attrs: Map) -> Answer { + if attrs == *old { + return Ok(Data::Undefined); + } + run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?; + Ok(Data::Undefined) +} + +fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, false)?; + // `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph + // with the default justification. + let base = CharStyle::default(); + let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size); + let leading = old.get("leading").and_then(Value::as_f64); + let sample = CharStyle { size, leading, ..base }; + let t = TextObject::point(Point::default(), "", sample.clone()); + let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?; + let mut attrs = old.clone(); + for (k, v) in param.as_object().into_iter().flatten() { + let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue }; + let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() }; + attrs.insert((*key).to_string(), v); + } + redefine(h, &style, &old, attrs) +} + +fn para_key(attr: ParaAttr) -> &'static str { + match attr { + ParaAttr::Justification => "justify", + ParaAttr::FirstLineIndent => "first_line_indent", + ParaAttr::LeftIndent => "left_indent", + ParaAttr::RightIndent => "right_indent", + ParaAttr::SpaceBefore => "space_before", + ParaAttr::SpaceAfter => "space_after", + } +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let (_, m) = attrs_of(h, a, true)?; + let v = m.get(para_key(attr)); + Ok(match attr { + ParaAttr::Justification => match v.and_then(Value::as_str) { + Some("Auto") => text("Justification.LEFT"), + Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))), + None => Data::Undefined, + }, + _ => v.and_then(Value::as_f64).map_or(Data::Undefined, num), + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, true)?; + let (_, _, wants) = para_param(attr, name, arg(a, 1))?; + let value = match (&wants, attr) { + (Data::String(s), ParaAttr::Justification) => { + let m = s.strip_prefix("Justification.").unwrap_or(s); + let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j); + json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?) + } + (Data::Number(n), _) => json!(n), + _ => return Err(HostError::Type(format!("{name} must be a finite number"))), + }; + let mut attrs = old.clone(); + attrs.insert(para_key(attr).to_string(), value); + redefine(h, &style, &old, attrs) +} + +/// The body of a member that captures what it reads or sets. +type Body = Rc Answer>; + +/// Members whose getter and setter each charge the call, as [`function`] does. +fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember { + let wrap = |f: Body| -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = super::super::current(&l)?; + h.charge_call(16 + a.iter().map(super::super::data_size).sum::())?; + f(&h, &a) + }) + }; + HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) } +} + +fn char_members(link: &Link) -> Vec { + ATTRS + .iter() + .map(|&(name, attr)| { + let data_type = match attr { + Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", + Attr::TextFont => "TextFont", + _ => "number", + }; + (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type)) + }) + .collect() +} + +fn para_members(link: &Link) -> Vec { + PARA_ATTRS + .iter() + .map(|&(name, attr)| { + let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" }; + (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type)) + }) + .collect() +} + +// ---- CharacterStyles and ParagraphStyles ---- + +/// What a collection of styles lists: a document's styles, or those a text range uses. +enum Of { + Doc(Doc), + Range(Span), +} + +fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> { + let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) { + (Some(_), _) => false, + (_, Some(_)) => true, + _ => return Err(HostError::Type("this is not a CharacterStyles".into())), + }; + let class = list_class(para); + let len = handle_of(d, class).map_or(0, |v| v.len()); + Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para)) +} + +/// The document and the names of the styles a collection lists. +fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec), HostError> { + match of { + Of::Doc(doc) => { + let names = with_doc(h, *doc, |_, st| names(st, para)); + h.charge_call(names.len() as u64)?; + Ok((*doc, names)) + } + Of::Range(r) => { + let (index, s, e, _) = resolve(h, *r)?; + let used = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let used: Vec> = if para { + let (paras, _, _) = para_range(&index, s, e); + paras.map(|i| t.para_at(i).style_name.clone()).collect() + } else { + styles_in(t, index.byte(s, false), index.byte(e, true), false)?.into_iter().map(|(c, _)| c.style_name).collect() + }; + h.charge_call(used.len() as u64)?; + let mut out: Vec = Vec::new(); + for n in used { + let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string()); + if !out.contains(&n) { + out.push(n); + } + } + if out.is_empty() { + out.push(normal(para).to_string()); + } + Ok::<_, HostError>(out) + })?; + Ok((r.item.doc, used)) + } + } +} + +fn list_length(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + Ok(num(float(listed(h, &of, para)?.1.len() as u64))) +} + +fn list_parent(h: &Host, a: &[Data]) -> Answer { + let (of, _) = list_of(h, arg(a, 0))?; + match of { + Of::Doc(doc) => Ok(doc_ref(h, doc.uid)), + Of::Range(r) => { + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) + } + } +} + +fn list_at(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = match &of { + Of::Doc(doc) => with_doc(h, *doc, |_, st| match i { + 0 => Some(normal(para).to_string()), + _ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(), + }) + .map(|n| (*doc, n)), + Of::Range(_) => { + let (doc, names) = listed(h, &of, para)?; + names.get(i).cloned().map(|n| (doc, n)) + } + }; + match found { + Some((doc, name)) => style_ref(h, doc.uid, para, &name), + None => Ok(Data::Undefined), + } +} + +fn list_by_name(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let (doc, names) = listed(h, &of, para)?; + match names.iter().find(|n| *n == name) { + Some(n) => style_ref(h, doc.uid, para, n), + None => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn list_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a), + Data::Number(_) => match list_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a document's collection; a range's collection cannot be changed. +fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> { + match list_of(h, arg(a, 0))? { + (Of::Doc(doc), para) => Ok((doc, para)), + (Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())), + } +} + +/// `add(name)`: a new style that sets no attributes. +fn list_add(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let name = style_name(arg(a, 1))?; + if with_doc(h, doc, |_, st| has_style(st, para, &name)) { + return Err(HostError::Error(format!("a style named {name} already exists"))); + } + // The new style needs a slot of its own: a run that names as many styles as it may adds none. + if h.dom.text.styles.slots.borrow().len() >= MAX_HELD { + return Err(held_too_many()); + } + run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; + // An object of a removed style of this name stays stale. + forget(h, doc.uid, para, std::slice::from_ref(&name)); + style_ref(h, doc.uid, para, &name) +} + +/// `removeAll()`: deletes every style but the Normal style, in one command. +fn list_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let gone: Vec = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect(); + if gone.is_empty() { + return Ok(Data::Undefined); + } + run(h, doc, para, "delete", &json!({"names": gone}))?; + forget(h, doc.uid, para, &gone); + Ok(Data::Undefined) +} + +fn doc_char_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)])) +} + +fn doc_para_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)])) +} + +fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer { + let r = this_range(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, list_class(para))) +} + +fn range_char_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, false) +} + +fn range_para_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, true) +} + +/// `document.characterStyles` and `document.paragraphStyles`. +pub(in crate::script) fn doc_members(l: &Link) -> Vec { + named(vec![ + ("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }), + ("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }), + ]) +} + +/// `TextRange.characterStyles` and `TextRange.paragraphStyles`. +pub(super) fn range_members(l: &Link) -> Vec { + named(vec![ + ("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }), + ("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }), + ]) +} + +/// The style classes. +pub(super) fn classes(l: &Link) -> Vec { + let style = |para: bool| { + let mut members = named(vec![ + ("typename", get(l, style_typename), typed("string")), + ("name", property(l, style_name_get, style_name_set), typed("string")), + ("parent", get(l, style_parent), typed("Document")), + ("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])), + ("remove", method(l, style_remove), returns("undefined", &[])), + ]); + if para { + members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes"))); + members.push(super::super::later(l, "ParagraphStyle", "characterAttributes")); + } else { + members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes"))); + } + class(style_class(para), None, members, None) + }; + let list = |para: bool| { + let name = list_class(para); + let item = style_class(para); + class( + name, + None, + named(vec![ + ("typename", typename_of(name), typed("string")), + ("length", get(l, list_length), typed("number")), + ("parent", get(l, list_parent), typed("*")), + ("index", method(l, list_index), returns(item, &[("itemKey", "*")])), + ("getByName", method(l, list_by_name), returns(item, &[("name", "string")])), + ("add", method(l, list_add), returns(item, &[("name", "string")])), + ("removeAll", method(l, list_remove_all), returns("undefined", &[])), + ]), + Some(function(l, list_at)), + ) + }; + let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]); + chars.extend(char_members(l)); + let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]); + paras.extend(para_members(l)); + vec![ + style(false), + style(true), + list(false), + list(true), + class("CharacterStyleAttributes", None, chars, None), + class("ParagraphStyleAttributes", None, paras, None), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index bc6ae00250..5fd8e0b88b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -48,6 +48,7 @@ //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +pub mod actions; pub mod console; pub mod dialogs; pub mod dollar; @@ -206,6 +207,8 @@ pub(crate) struct Request { pub locale: String, /// The answers to the dialogs of a run with nobody to ask, in order. pub answers: Vec, + /// The actions `app.doScript` can play. + pub actions: Vec, } thread_local! { @@ -806,6 +809,15 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// The actions `app.doScript` can play. + actions: Vec, + /// The index of each open document's active artboard as the run starts, by document uid. The + /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. + active_artboards: Vec<(u64, usize)>, + /// The artboards the Artboard tool had selected in the active document as the run starts (two or + /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the + /// steps `app.doScript` plays read them here. + artboard_picks: Option<(u64, Vec)>, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -1283,6 +1295,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); + s.script_style_trail = StyleTrail::start(s); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1330,6 +1343,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value Ok((v, objects, bytes, save)) } Err(e) => { + s.script_style_trail = StyleTrail::default(); if let Some(save) = save && !save.restore(s) { @@ -1408,9 +1422,76 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( } } dom::after_command(host, before); + // Style objects follow only a command that is kept. + if crossed.is_ok() { + dom::after_kept_command(host); + } else { + session.borrow_mut().script_style_trail = StyleTrail::default(); + } crossed.map(|data| (data, value)) } +/// A document's uid, revert count, and character and paragraph style lists. +pub(crate) type StyleLists = + (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); + +/// What the steps of a command a script runs did to the documents' style lists +/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step +/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the +/// documents a step reverted. +#[derive(Default)] +pub(crate) struct StyleTrail { + lists: Vec, + pub(crate) gone: std::collections::HashSet<(u64, bool, String)>, + pub(crate) reverted: Vec, +} + +impl StyleTrail { + /// A trail that starts from the documents' style lists now. + fn start(s: &Session) -> Self { + let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); + StyleTrail { lists, ..Default::default() } + } +} + +/// After a step of a batch a script runs: notes the styles the step removed or renamed and the +/// documents it reverted, so the style objects see a style the batch removed and made again under +/// its name as another style ([`dom::after_kept_command`]). The trail keeps one copy of each open +/// document's lists, however many steps change them. +pub(crate) fn note_style_lists(s: &mut Session) { + let trail = &mut s.script_style_trail; + trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); + for st in &s.docs { + let (c, p) = (&st.doc.char_styles, &st.doc.para_styles); + let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else { + trail.lists.push((st.uid, st.reverts, c.clone(), p.clone())); + continue; + }; + if last.1 != st.reverts { + if !trail.reverted.contains(&st.uid) { + trail.reverted.push(st.uid); + } + } else { + for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] { + if vectorcraft_doc::Shared::ptr_eq(old, new) { + continue; + } + let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect(); + for d in old.iter().filter(|d| !names.contains(d.name.as_str())) { + trail.gone.insert((st.uid, para, d.name.clone())); + } + } + } + *last = (st.uid, st.reverts, c.clone(), p.clone()); + } +} + +/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]). +#[cfg(test)] +pub(crate) fn retained_style_lists(s: &Session) -> usize { + s.script_style_trail.lists.len() +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { @@ -2063,6 +2144,9 @@ impl Session { if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); } + // The Artboard tool's selection, which the fresh tool state below drops. + let picks = cmd::artboard_tool_picks(self); + let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); @@ -2182,6 +2266,9 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::new(heap_bytes), + actions: request.actions, + active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), + artboard_picks, run_docs: RefCell::new( self.docs .iter() diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 258468641d..9c65271161 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -189,6 +189,7 @@ impl Session { startup_loading: None, startup_failures: vec![], script_high_water: Default::default(), + script_style_trail: Default::default(), script_in_run: false, window_views: vec![], script_copy_first: cfg!(target_arch = "wasm32"), diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 8b8bef8679..eec49be0c7 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -129,6 +129,9 @@ impl Session { self.execute_spec(spec, id, params) }; self.reading = outer; + if self.script_in_run && self.depth > 0 && r.is_ok() { + crate::script::note_style_lists(self); + } r } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2f3c5556e7..f51605c44d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,7 +49,7 @@ mod css; mod curvature_circle; mod cut; mod dashalign; -mod dcs; +pub(super) mod dcs; mod delete_keeps_joined; mod distort; mod docsetup; @@ -175,6 +175,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_actions; mod script_console; mod script_dialogs; mod script_dollar; @@ -185,6 +186,7 @@ mod script_include; mod script_io; mod script_run; mod script_scriptui; +mod script_styles; mod script_tags; mod script_text; mod script_threads; @@ -5169,6 +5171,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/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 9b0147174e..fecd16ed2a 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -776,6 +776,33 @@ 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.57).contains(&got), "{fix:?} draws {drawn:?}: {got}"); +} + +/// A pick for a picked symbol object with a fill of None puts a solid color there, which the +/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained. +#[test] +fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() { + let mut s = picked_symbol_part(); + let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance; + s.active_mut().unwrap().selection.symbol_part = None; + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap(); + s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] }); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure"); + let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap(); + let cms = vectorcraft_color::cms::active(); + let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0))); + let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]); + assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}"); } #[test] @@ -877,3 +904,309 @@ 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.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:?}"); + // 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.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}"); + // 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}"); +} + +/// 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] +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] +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.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}"); +} + +#[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.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}"); + } + } + } +} + +/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one +/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the +/// other, so the white draws over different rows and there is no one answer. A given background +/// stands for the rows below and answers. +#[test] +fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() { + let mut s = session(); + let id = |v: Value| v["id"].as_u64().unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap(); + s.execute("object.lock", &json!({})).unwrap(); + let square = |s: &mut Session, x: i32, isolate: bool| { + let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap()); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + let st = s.active().unwrap(); + let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items; + let top = items.iter().rposition(|i| i.is_fill()).unwrap(); + let lower = items.iter().position(|i| i.is_fill()).unwrap(); + s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap(); + s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + if isolate { + s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap(); + } + n + }; + let a = square(&mut s, 30, false); + let b = square(&mut s, 120, true); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.execute("select.set", &json!({"ids": [b]})).unwrap(); + let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}"); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the selected objects' colors differ"), "{e}"); + s.execute("color.contrast", &json!({"against": "#000000"})).unwrap(); + // A blending row at no opacity does not show, so the isolation no longer changes the answer. + for n in [a, b] { + let st = s.active().unwrap(); + let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap(); + } + s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + s.execute("color.contrast", &json!({})).unwrap(); +} + +/// A Difference square centered on the edge between locked black and white art: the art behind it +/// is not one color where it is read, so no one color stands for it; a given background answers, +/// and over one color the background is read as before. +#[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(); + 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/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index a8e37ff812..34bfe7a7bc 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { } /// Cyan solid on the top row, PANTONE 185 C at 50% on the left column. -fn two_plates() -> Vec { +pub(crate) fn two_plates() -> Vec { single_file( &[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))], "%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", @@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts +/// the file's image between the corners and draws its clipping path through them. +#[test] +fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() { + let dir = temp_dir("replace-distorted-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let png = crate::tests_links::png(4, 4, [255, 0, 0]); + let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap(); + let old = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap(); + let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = NodeId(r["image"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node.is_distorted_image()); + assert_eq!(node.image_corners().unwrap(), corners); + let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") }; + let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect(); + // The left half of the 2 × 2 pixels, where the corners put it. + let map = node.image_map().unwrap(); + let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap()); + assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}"); +} + #[test] fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { let dir = temp_dir("update-gained-clip"); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6391c4f3db..405bb12a37 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() { assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); } +/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step: +/// the new file's pixels fill them, the new image is linked to that file, and its transform is the +/// old image's scaled to the new pixel size. Undo brings the old image back between the same +/// corners. +#[test] +fn place_with_replace_keeps_a_distorted_images_corners() { + let dir = Folder::new("distorted-place-replace"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // Around the artboard's center, where `centre_colour` looks. + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned(); + let before = node(&s, id).unwrap().image_corners().unwrap(); + let old_xf = image(&s, id).xf; + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + let undo = undo_len(&s); + + let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap(); + let new = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(undo_len(&s), undo + 1); + assert!(node(&s, id).is_none(), "the old image is replaced"); + let n = node(&s, new).unwrap(); + assert!(n.is_distorted_image()); + assert_eq!(n.image_corners().unwrap(), before); + let im = image(&s, new); + assert_eq!((im.width, im.height), (60, 20)); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str())); + let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0); + assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, new).is_none()); + assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + /// Unembed into a folder keeps a distorted image's corners, in one undo step. #[test] fn unembed_to_a_folder_keeps_a_distorted_images_corners() { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs new file mode 100644 index 0000000000..1432b8671b --- /dev/null +++ b/crates/engine/src/tests/script_actions.rs @@ -0,0 +1,396 @@ +//! `app.doScript`: a script plays an action of `script.run`'s `actions`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})) +} + +fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec { + let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The error message a `try` around `call` logs, or `"ok"`. +fn caught(s: &mut Session, call: &str, actions: &Value) -> String { + let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}"); + log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string() +} + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn objects(s: &Session) -> usize { + s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn undo_labels(s: &Session) -> Vec { + s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn rect(x: i64) -> Value { + json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}}) +} + +/// One set, `Set`, with the actions given as (name, steps). +fn set(actions: &[(&str, Vec)]) -> Value { + Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect()) +} + +#[test] +fn do_script_plays_every_step_as_one_undo_step_with_the_script() { + let mut s = doc(); + let before = undo_labels(&s); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions); + assert_eq!(out, vec![Value::Null], "doScript returns undefined"); + assert_eq!(objects(&s), 3); + let after = undo_labels(&s); + assert_eq!(after.len(), before.len() + 1, "{after:?}"); + assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL)); + // The steps of a recorded `command.batch` run one by one, each counted as a host call. + let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]); + let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap(); + assert_eq!(objects(&s), 6); + let r0 = run_with(&mut s, "1;", &batch).unwrap(); + assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}"); +} + +#[test] +fn a_later_throw_puts_back_what_the_action_did() { + let mut s = doc(); + let before = (objects(&s), undo_labels(&s)); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string(); + assert!(e.contains("late"), "{e}"); + assert_eq!((objects(&s), undo_labels(&s)), before); +} + +#[test] +fn a_failed_step_is_put_back_and_the_steps_before_it_stay() { + let mut s = doc(); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]); + let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions); + assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}"); + assert_eq!(objects(&s), 1, "the first step stays done and the third never runs"); +} + +#[test] +fn names_are_matched_exactly_and_must_be_one_action() { + let mut s = doc(); + let actions = json!([ + {"set": "Set", "name": "One", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Empty", "steps": []}, + ]); + assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”"); + assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”"); + assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”"); + assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps"); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”"); + assert_eq!(objects(&s), 0); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok"); + assert_eq!(objects(&s), 1); + assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet"); + assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet"); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let mut s = doc(); + let actions = set(&[("One", vec![rect(0)])]); + for (call, want) in [ + ("app.doScript()", "TypeError"), + ("app.doScript(1, 'Set')", "TypeError"), + ("app.doScript('One', {})", "TypeError"), + ("app.doScript('One', 'Set', 'yes')", "TypeError"), + ("app.doScript('One', 'Set', 1)", "TypeError"), + ("app.doScript('One', 'Set', false, 4)", "TypeError"), + ("app.doScript('', 'Set')", "Error"), + ("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"), + ] { + let m = caught(&mut s, call, &actions); + assert!(m.starts_with(&format!("{want}:")), "{call}: {m}"); + } + assert_eq!(objects(&s), 0); +} + +#[test] +fn steps_a_script_may_not_run_stop_the_action_before_any_step() { + let mut s = doc(); + s.prefs.show_external_script_warning = true; + let steps = [ + (json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"), + (json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"), + (json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"), + (json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"), + (json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"), + (json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"), + ]; + for (bad, want) in steps { + let actions = set(&[("Loop", vec![rect(0), bad.clone()])]); + let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions); + assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}"); + assert_eq!(objects(&s), 0, "{bad}: no step ran"); + } + assert!(s.prefs.show_external_script_warning); + // A refused command inside a recorded batch is refused too. + let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]); + let m = caught(&mut s, "app.doScript('B', 'Set')", &batch); + assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}"); + assert_eq!(objects(&s), 0); + // So is one among the commands a Batch step plays on each file, before the steps ahead of it run. + let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}}); + let batch = set(&[("F", vec![rect(0), files])]); + let m = caught(&mut s, "app.doScript('F', 'Set')", &batch); + assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}"); + assert_eq!(objects(&s), 0); +} + +#[test] +fn an_action_step_keeps_the_scripts_file_gate() { + let mut s = doc(); + let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}}); + let actions = set(&[("Export", vec![export])]); + let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions); + assert!(m.contains("Script file access denied"), "{m}"); + assert!(!path.exists()); +} + +#[test] +fn a_long_action_is_held_to_the_host_call_limit() { + let mut s = doc(); + // Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the + // steps of one call cannot pass the limit. + let calls = |s: &mut Session, steps: usize| { + let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]); + run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap() + }; + let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001)); + assert!(many >= one + 2000, "{one} {many}"); +} + +#[test] +fn bad_action_lists_are_refused_before_the_script_runs() { + let mut s = doc(); + let step = || json!({"command": "select.none"}); + let cases = [ + (json!({}), "`actions` must be a list"), + (json!([1]), "`actions[0]` must be an object"), + (json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"), + (json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"), + (json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"), + (json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"), + ( + json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]), + "a command.batch inside a command.batch", + ), + (json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"), + (Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"), + (json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"), + ]; + for (actions, want) in cases { + let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string(); + assert!(e.contains(want), "{want}: {e}"); + } + let many: Vec = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect(); + let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string(); + assert!(e.contains("more than 100000 steps in all"), "{e}"); + assert_eq!(objects(&s), 0, "no run started"); +} + +#[test] +fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() { + let mut s = doc(); + let first = set(&[("One", vec![rect(0)])]); + log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first); + assert_eq!(objects(&s), 0); + // The next run has no actions: the function kept from the first run finds none. + let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }"; + assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]); + let two = set(&[("One", vec![rect(0), rect(30)])]); + assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]); + assert_eq!(objects(&s), 2); +} + +/// Makes artboard `index` of the active document the view's active one, as the app does before each +/// command. +fn make_active(s: &mut Session, index: usize) { + let id = s.active().unwrap().doc.artboards[index].id; + s.doc_mut().unwrap().active_artboard = Some(id); +} + +/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected +/// Art, acts on the active artboard's index as the run started; after the script deletes that +/// artboard, the last one. A step that names its artboard keeps it. +#[test] +fn steps_act_on_the_artboard_active_as_they_run() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 2); + let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}}); + let mut first = align(json!(0)); + first["params"].as_object_mut().unwrap().remove("artboard"); + let actions = set(&[ + ("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]), + ("Align 1", vec![align(json!(0))]), + ("Fit", vec![json!({"command": "artboard.fitToSelection"})]), + ]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions); + let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was"); + assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other"); + log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); +} + +/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, +/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. +#[test] +fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 1); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let mut own = align.clone(); + own["params"]["artboard"] = json!(1); + let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}}); + let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "app.doScript('First', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "the batch's artboard 0"); + log_with(&mut s, "app.doScript('Past', 'Set');", &actions); + assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one"); + log_with(&mut s, "app.doScript('Own', 'Set');", &actions); + assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it"); +} + +/// The active artboard a step gets is the index it had as the run started: after a step deletes an +/// artboard before it, the artboard now at that index, as the view shows it. +#[test] +fn steps_keep_the_active_artboards_index() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let uid = s.active().unwrap().uid; + let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None }; + let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({})); + assert_eq!(add(&s), json!({"artboard": 1})); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one"); +} + +/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its +/// `indices` fits those. +#[test] +fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + let actions = set(&[ + ("Fit", vec![json!({"command": "artboard.fitToArt"})]), + ("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]), + ]); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art"); + log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions); + assert_eq!(boards(&s), art, "the step's own indices"); +} + +/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it +/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps +/// still get the active one. +#[test] +fn paste_and_fit_steps_keep_the_artboard_tools_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + make_active(&mut s, 1); + let start = script::actions::Start { active: &[], picks: None, batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + assert_eq!(add(&s, id), json!({}), "{id}"); + } + assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); + assert_eq!(add(&s, "shape.rectangle"), json!({})); +} + +/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays, +/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to +/// Artwork Bounds step fits them. +#[test] +fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { + // Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2. + let setup = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + s.execute("edit.copy", &json!({})).unwrap(); + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + (s, was, art) + }; + let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + let (mut s, ..) = setup(); + let before = objects(&s); + log_with(&mut s, "app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 2, "one copy on each selected artboard"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // A kept artboard past the last one is left out; with fewer than two left, the active one applies. + let (mut s, ..) = setup(); + s.reset_tool(); + let uid = s.active().unwrap().uid; + let kept = (uid, vec![0, 2]); + let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); +} diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 330b3f4d4d..94886530c1 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1767,6 +1767,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}"); + assert!(s.active().unwrap().doc.node(t).is_some()); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn move_and_duplicate_refuse_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 7d8f06700e..dc9749fb6c 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() { fuel: script::DEFAULT_FUEL, locale: "en_US".into(), answers: Vec::new(), + actions: Vec::new(), }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs new file mode 100644 index 0000000000..df96906aec --- /dev/null +++ b/crates/engine/src/tests/script_styles.rs @@ -0,0 +1,434 @@ +//! Character and paragraph styles in the script object model. + +use serde_json::{Value, json}; +use vectorcraft_doc::{TextObject, TextStyleDef}; + +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::script::TEST_RESULT_BYTES; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn text_of(s: &Session, id: NodeId) -> TextObject { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each run's text, style name, size and underline. +fn runs(s: &Session, id: NodeId) -> Vec<(String, Option, f64, bool)> { + text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect() +} + +fn char_names(s: &Session) -> Vec { + s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect() +} + +const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];"; + +#[test] +fn style_collections_list_the_normal_style_first_and_add_find_and_remove() { + let (mut s, _) = doc_with("Hello"); + let before = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\ + var b = cs.add('Body'); var p = ps.add('Lead');\ + vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\ + vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\ + cs.add('Other'); cs.removeAll(); ps.removeAll();\ + vc.log([cs.length, ps.length, cs[0].name]);" + ), + ); + assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"])); + assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"])); + assert_eq!(out[2], json!([2, "Lead", true])); + assert_eq!(out[3], json!([1, 1, NORMAL_CHAR])); + assert_eq!(undo_steps(&s), before + 1); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs.getByName('Nope');", "Not found"), + ("cs.index(4);", "Not found"), + ("cs.add('Body'); cs.add('Body');", "already exists"), + ("cs[0].remove();", "cannot be removed"), + ("ps[0].name = 'Mine';", "cannot be renamed"), + ("cs.getByName(5);", "string"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::::new())); +} + +/// Names are trimmed; an empty name, one past 256 characters and one with a control character +/// are refused with nothing changed. +#[test] +fn style_names_are_trimmed_and_checked() { + let (mut s, _) = doc_with("Hello"); + let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256))); + assert_eq!(out, [json!("Lead"), json!(256)]); + let undo = undo_steps(&s); + let long = "x".repeat(257); + for (src, says) in [ + ("cs.add(' ');".to_string(), "empty"), + (format!("cs.add('{long}');"), "256 characters"), + ("cs.add('a\\u0007b');".to_string(), "control characters"), + ("ps.add('tab\\there');".to_string(), "control characters"), + ("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"), + ("cs.add(5);".to_string(), "string"), + (format!("cs.getByName('{}');", "y".repeat(5000)), "too long"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + assert_eq!(char_names(&s).len(), 2); + // Path characters are kept as part of the name; a style name never names a file. + let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);")); + assert_eq!(out, [json!("../a/b\\c:*?")]); + assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?")); +} + +/// A style attribute that is not a finite number in range is refused with nothing changed. +#[test] +fn style_attributes_refuse_values_that_are_not_finite_or_in_range() { + let (mut s, _) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');")); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs[1].characterAttributes.size = NaN;", "finite number"), + ("cs[1].characterAttributes.size = Infinity;", "finite number"), + ("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"), + ("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"), + ("cs[1].characterAttributes.tracking = -1e9;", "tracking"), + ("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"), + ("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + let attrs = |s: &Session| { + s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::() + }; + assert_eq!(attrs(&s), 0); +} + +/// A style object follows its style through a rename made with it; after the style is removed, +/// with the object or with a command, every member throws, and a new style of that name does not +/// bring it back. +#[test] +fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { + let (mut s, id) = doc_with("Hello"); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\ + a.name = 'B'; vc.log(cs.length);" + ), + ); + assert_eq!(out, [json!(["B", "B", true]), json!(2)]); + assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B")); + for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] { + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;")); + assert!(e.contains("Stale style"), "{remove}: {e}"); + } + // A style removed and made again by commands is another style. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // So is a style removed and made again by the steps of one batch. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \ + {{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // And a style a batch renames and then names back. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \ + {{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // The attributes object of a removed style throws for its typename too. + let e = + failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); + assert!(e.contains("Stale style"), "{e}"); + // A style renamed by a command is stale too, and its text keeps its look after a removal. + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); + assert!(e.contains("Stale style"), "{e}"); + let e = + failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;")); + assert!(e.contains("Stale style"), "{e}"); + let size = runs(&s, id)[0].2; + log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();")); + assert_eq!(runs(&s, id)[0].1, None); + assert_ne!(runs(&s, id)[0].2, size); + assert_eq!(runs(&s, id)[0].2, 40.0); +} + +/// The steps of one batch a script runs keep one copy of a document's style lists, however many of +/// them change the lists. +#[test] +fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() { + let (mut s, _) = doc_with("Hello"); + let commands: Vec = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect(); + s.script_in_run = true; + let r = s.execute("command.batch", &json!({"commands": commands})); + s.script_in_run = false; + r.unwrap(); + assert_eq!(char_names(&s).len(), 20); + assert_eq!(crate::script::retained_style_lists(&s), 1); +} + +/// A removal or rename whose result cannot cross to the script is put back, and the style's object +/// still names the style after it. +#[test] +fn a_style_change_that_is_put_back_keeps_the_style_object() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap(); + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\ + try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\ + try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\ + vc.log([a.name, a === cs.getByName('B'), cs.length]);" + ), + ); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}"); + assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s)); +} + +/// A character style styles exactly the range; without clearing overrides the range keeps its +/// own underline, and with them it goes back to the Normal style first. +#[test] +fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { + let (mut s, id) = doc_with("Hello world"); + let before = undo_steps(&s); + log( + &mut s, + &format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"), + ); + assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);")); + assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false)); + // A whole frame, and an empty range, which changes nothing. + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);")); + assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); +} + +/// A character style applied to an empty frame styles the text set in it later. +#[test] +fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() { + for target in ["tf", "tf.textRange"] { + let (mut s, id) = doc_with(""); + log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';")); + assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}"); + } +} + +/// A paragraph style styles every paragraph the text touches, and only those. +#[test] +fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { + let (mut s, id) = doc_with("one\ntwo\nthree"); + let out = log( + &mut s, + &format!( + "{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\ + vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\ + a.justification = Justification.CENTER; a.spaceBefore = 6;\ + vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\ + vc.log(tf.paragraphs[1].paragraphAttributes.justification);" + ), + ); + assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]); + let t = text_of(&s, id); + let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect(); + assert_eq!(names, [None, Some("Centered".to_string()), None]); + assert_eq!(t.para_at(1).space_before, 6.0); + assert_eq!(t.para_at(2).space_before, 0.0); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';")); + assert!(e.contains("Justification"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;")); + assert!(e.contains("1296"), "{e}"); +} + +/// A style's character attributes read `undefined` until set; setting one restyles the text in +/// the style but not a value the text changed itself. +#[test] +fn style_attributes_redefine_the_text_in_the_style() { + let (mut s, id) = doc_with("ab cd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), a = x.characterAttributes;\ + vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\ + a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\ + vc.log([a.size, a.autoLeading, a.underline]);" + ), + ); + assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); + assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); + // Turning auto leading off keeps the leading auto leading gave the style's size. + let out = log( + &mut s, + &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"), + ); + assert_eq!(out, [json!([false, 288])]); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); + assert!(e.contains("0.1 to 1296"), "{e}"); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';")); + assert!(e.contains("TextFont"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;")); + assert!(e.contains("not available yet"), "{e}"); +} + +/// A range lists each style its text uses once, in order, with the Normal style for unstyled +/// text, and its lists cannot add or remove styles. +#[test] +fn a_range_lists_the_styles_its_text_uses() { + let (mut s, _) = doc_with("aa bb cc\ndd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\ + ps.add('P').applyTo(tf.paragraphs[1]);\ + function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\ + vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\ + vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\ + vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\ + tf.textRange.characterStyles.parent.typename]);" + ), + ); + assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"])); + assert_eq!(out[1], json!(["X"])); + assert_eq!(out[2], json!([NORMAL_PARA, "P"])); + assert_eq!(out[3], json!([NORMAL_PARA])); + assert_eq!(out[4], json!([true, "X", "TextRange"])); + for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}"); + } +} + +/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another +/// document, and a range whose text changed, with nothing changed. +#[test] +fn apply_to_refuses_bad_arguments_with_nothing_changed() { + let (mut s, id) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X');")); + let runs_before = runs(&s, id); + for (src, says) in [ + ("cs[1].applyTo(5);".to_string(), "TextRange"), + ("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"), + ("cs[1].applyTo(cs);".to_string(), "TextRange"), + (format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"), + ( + "var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(), + "another document", + ), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(runs(&s, id), runs_before); +} + +/// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap(); + let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\ + var cs2 = app.activeDocument.characterStyles;\ + try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\ + vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);" + ), + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}"); + assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style"); + assert_eq!(out[2], json!(false)); +} + +#[test] +fn a_run_names_at_most_4096_styles() { + let (mut s, _) = doc_with("Hello"); + let mut d = (*s.active().unwrap().doc).clone(); + let defs: Vec = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect(); + d.char_styles = defs.into(); + s.doc_mut().unwrap().doc = std::sync::Arc::new(d); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);")); + assert_eq!(out, [json!(false), json!(4101)]); + let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); + assert!(e.contains("4096 styles"), "{e}"); + // `add` with every slot taken adds no style; with one slot left it adds the style. + let out = log( + &mut s, + &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"), + ); + assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);")); + assert_eq!(out, [json!("New"), json!(4102)]); +} + +/// A script loads styles from a file only where it may read files; a file outside that is refused. +#[test] +fn a_script_loads_styles_only_from_a_file_it_may_read() { + let (mut s, _) = doc_with("Hello"); + let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Other.vectorcraft"); + let mut other = Session::new(); + other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap(); + std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap(); + let p = path.to_string_lossy().replace('\\', "/"); + let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});")); + std::fs::remove_dir_all(&dir).ok(); + assert!(e.contains("access denied"), "{e}"); + assert!(char_names(&s).is_empty()); +} diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index ea3142e6cc..d455f6ad2f 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() { ("object.cropImage", json!({})), ("imageTrace.make", json!({})), ("object.mesh.create", json!({})), + // Vector art has no pixels to put between the corners. ( "file.place", - json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}), + json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"")}), ), ] { let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index bc9e2aa0c6..c5d2905963 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -630,6 +630,7 @@ impl Session { freeform_point: self.selected_freeform_point(), raster_sample: self.prefs.eyedropper.sample_size, preview_bounds: self.prefs.use_preview_bounds, + scale_strokes: self.prefs.scale_strokes, glyph_bounds: self.prefs.type_glyph_bounds, preview_memo: Some(&self.preview_memo), unit, diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index b343e534e7..7c4196fd84 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/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 0b20de0e23..d7f60e5b2c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ - getIsFileOpen redraw selection selection= textFonts toString typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ + executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \ + unloadAction unloadAction=", ), ("DocumentPreset.", "prototype"), ( @@ -105,10 +106,10 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= tags textFrames toString \ - typename views width", + "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ + documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \ + symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), ("Views.prototype.", "constructor index length parent toString typename"), @@ -154,8 +155,9 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ( "", - "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ - TextOrientation TextRange TextType Words", + "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ + ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \ + TextFrames TextOrientation TextRange TextType Words", ), ("TextFrames.", "prototype"), ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), @@ -173,11 +175,11 @@ const INSIDE: &[(&str, &str)] = &[ ( "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ - characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \ duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ - leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \ paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ @@ -202,6 +204,30 @@ const INSIDE: &[(&str, &str)] = &[ "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", ), + ("CharacterStyles.", "prototype"), + ("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("CharacterStyle.", "prototype"), + ("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"), + ("CharacterStyleAttributes.", "prototype"), + ( + "CharacterStyleAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphStyles.", "prototype"), + ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("ParagraphStyle.", "prototype"), + ( + "ParagraphStyle.prototype.", + "applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename", + ), + ("ParagraphStyleAttributes.", "prototype"), + ( + "ParagraphStyleAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), ("TextFonts.", "prototype"), ("TextFonts.prototype.", "constructor getByName index length parent typename"), ("TextFont.", "prototype"), diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index a0bf7f1f09..c23f8c6767 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -614,6 +614,9 @@ pub struct Program { pub(crate) lines: crate::LineTable, /// It was read with [`crate::Options::es2015`]. pub(crate) es2015: bool, + /// What `super` and `new.target` may do at its top: nothing in a script, and in eval code + /// what they may do in the code that calls a direct `eval` (ECMA-262 2015 section 18.2.1.1). + pub(crate) supers: crate::parser::SuperRules, } impl Program { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 6e6a6edccc..8bf8783adf 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -591,15 +591,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_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?)) -} - -/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member. -fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult { - match k { - crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name), - crate::symbol::PropKey::Sym(_) => Ok(false), - } + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -618,7 +610,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_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?)) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 101e3e55b5..cda3d45ece 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -453,6 +453,10 @@ pub(crate) struct Code { /// The code is a generator function's: a call makes a generator object ([`Op::GeneratorStart`]), /// and it is not a constructor. pub(crate) generator: bool, + /// What `super` and `new.target` may do in eval code a direct `eval` in this code runs: the + /// rules of the function's body, of the code around an arrow function, or those eval code was + /// read with (ECMA-262 2015 section 18.2.1.1). + pub(crate) supers: crate::parser::SuperRules, } /// What [`Op::SetFunctionNameKey`] puts before a computed name: `get ` and `set ` for accessors. diff --git a/crates/js/src/compiler.rs b/crates/js/src/compiler.rs index ee3151cd2d..1f6d12091d 100644 --- a/crates/js/src/compiler.rs +++ b/crates/js/src/compiler.rs @@ -25,6 +25,7 @@ use crate::ast::{ use crate::bytecode::{BlockScope, Code, CodeKind, Handler, NamePrefix, Op, Source, Template, fallthrough_effect, verify}; use crate::error::{SyntaxError, TOO_DEEP}; use crate::heap::Key; +use crate::parser::SuperRules; use crate::value::Str; use pattern::Mode; @@ -112,6 +113,8 @@ struct FnCompiler<'a> { optional: Vec<(Label, u32)>, /// The code is a generator function's. generator: bool, + /// [`Code::supers`]. + supers: SuperRules, } /// The `var` names and function declarations a body hoists. @@ -162,6 +165,7 @@ impl<'a> FnCompiler<'a> { annex: HashSet::new(), optional: Vec::new(), generator: false, + supers: SuperRules::default(), } } @@ -501,7 +505,7 @@ impl<'a> FnCompiler<'a> { /// Compiles a nested function and returns its index in the function table. fn function(&mut self, fid: FunctionId) -> CResult { - let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?; + let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015, self.supers)?; // An arrow function reads the `this`, `arguments` and `new.target` of the code around it. if code.arrow { self.uses_this |= code.uses_this; @@ -2389,6 +2393,7 @@ impl<'a> FnCompiler<'a> { own_name: meta.own_name, method: meta.method, generator: self.generator, + supers: self.supers, }; code.max_stack = verify(&code).map_err(CompileFail::Internal)?; Ok(Rc::new(code)) @@ -2419,12 +2424,22 @@ fn len_u32(n: usize) -> u32 { } /// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound -/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in. -pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, recursion: u32, bind_name: bool, es2015: bool) -> CResult> { +/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in, and `outer` the +/// [`Code::supers`] of the code around it, which an arrow function keeps. +pub(crate) fn compile_function( + ast: &Ast, + fid: FunctionId, + source: &Rc, + recursion: u32, + bind_name: bool, + es2015: bool, + outer: SuperRules, +) -> CResult> { let Some(f) = ast.function(fid) else { return internal("function out of range") }; let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion); c.es2015 = es2015; c.generator = f.generator; + c.supers = if f.kind == FunctionKind::Arrow { outer } else { SuperRules::function(f.home, f.kind == FunctionKind::DerivedConstructor) }; c.at(f.span.start); c.enter()?; // A destructured parameter has a binding of its own under a name no script can write, which @@ -2515,6 +2530,7 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc, pub(crate) fn compile_program(program: &crate::Program, source: &Rc, kind: CodeKind) -> CResult> { let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0); c.es2015 = program.es2015; + c.supers = program.supers; let hoisted = c.hoist(&program.body, &[])?; let top_scope = c.list_scope(&program.body, false)?; c.stmts(&program.body)?; @@ -2531,5 +2547,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) }; let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) }; let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) }; - compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some) + compile_function(&program.ast, *fid, source, 0, false, program.es2015, program.supers).map(Some) } diff --git a/crates/js/src/es2015_tests.rs b/crates/js/src/es2015_tests.rs index cc8e246d2d..00d0874111 100644 --- a/crates/js/src/es2015_tests.rs +++ b/crates/js/src/es2015_tests.rs @@ -1639,6 +1639,56 @@ fn eval_inside_a_function_reads_its_new_target() { throws("function F() { return (0, eval)('new.target'); } new F()", "SyntaxError"); } +/// A direct `eval` inside a method reads `super` properties of the method's home object, from an +/// arrow function and a nested `eval` too; in a function that is not a method, at the top of a +/// script, through an indirect `eval` and in a `Function` body it is a `SyntaxError`. +#[test] +fn eval_inside_a_method_reads_super_properties() { + truth("class A { get x() { return 'a' + this.n; } } class B extends A { m() { this.n = 1; return eval('super.x'); } } new B().m() === 'a1'"); + truth("class A { f() { return 3; } } class B extends A { m() { return (() => eval('super.f()'))(); } } new B().m() === 3"); + truth("class A { f() { return 3; } } class B extends A { m() { return eval('eval(\"super[\\'f\\']()\")'); } } new B().m() === 3"); + truth("class A { f() { return 3; } } class B extends A { m() { return eval('() => super.f()')(); } } new B().m() === 3"); + truth("class A {} class B extends A { m() { eval('super.y = 5'); return this.y; } } new B().m() === 5"); + truth("class A { static s() { return 4; } } class B extends A { static s() { return eval('super.s()'); } } B.s() === 4"); + truth("class A { constructor() { this.t = eval('super.constructor'); } } new A().t === Object"); + truth("var o = { __proto__: { x: 2 }, m() { 'use strict'; return eval('super.x'); } }; o.m() === 2"); + throws("function F() { return eval('super.x'); } F()", "SyntaxError"); + throws("eval('super.x')", "SyntaxError"); + throws("class A { m() { return (function () { return eval('super.x'); })(); } } new A().m()", "SyntaxError"); + throws("class A { m() { return (0, eval)('super.x'); } } new A().m()", "SyntaxError"); + throws("class A { m() { return Function('return super.x'); } } new A().m()", "SyntaxError"); +} + +/// A direct `eval` inside a derived class's constructor calls the superclass's constructor with +/// `super(…)` and binds `this` once; elsewhere `super(…)` in eval code is a `SyntaxError`. +#[test] +fn eval_inside_a_derived_constructor_calls_super() { + let a = "class A { constructor(v) { this.a = v; this.t = new.target; } } "; + truth(&format!( + "{a}class B extends A {{ constructor() {{ eval('super(1)'); this.b = 2; }} }} var b = new B(); b.a === 1 && b.b === 2 && b.t === B && b instanceof B" + )); + truth(&format!("{a}class B extends A {{ constructor() {{ var r = eval('super(1)'); this.r = r === this; }} }} new B().r")); + truth(&format!("{a}class B extends A {{ constructor() {{ (() => eval('super(1)'))(); }} }} new B().a === 1")); + truth(&format!("{a}class B extends A {{ constructor() {{ 'use strict'; eval('super(1)'); }} }} new B().a === 1")); + throws(&format!("{a}class B extends A {{ constructor() {{ super(1); eval('super(2)'); }} }} new B()"), "ReferenceError"); + throws(&format!("{a}class B extends A {{ constructor() {{ eval('super(1); super(2)'); }} }} new B()"), "ReferenceError"); + throws(&format!("{a}class B extends A {{ constructor() {{ eval('this'); super(1); }} }} new B()"), "ReferenceError"); + throws("class A { constructor() { eval('super()'); } } new A()", "SyntaxError"); + throws(&format!("{a}class B extends A {{ m() {{ eval('super()'); }} }} new B(1).m()"), "SyntaxError"); + throws(&format!("{a}class B extends A {{ constructor() {{ (function () {{ eval('super(1)'); }})(); }} }} new B()"), "SyntaxError"); + throws(&format!("{a}class B extends A {{ constructor() {{ (0, eval)('super(1)'); }} }} new B()"), "SyntaxError"); + throws(&format!("{a}class B extends A {{ constructor() {{ Function('super(1)'); }} }} new B()"), "SyntaxError"); + throws("function F() { eval('super()'); } F()", "SyntaxError"); + throws("eval('super()')", "SyntaxError"); +} + +/// A `Function` body reads its own `new.target`, wherever the `Function` constructor is called. +#[test] +fn a_function_body_reads_its_own_new_target() { + truth("var G = Function('return new.target'); new G() === G && G() === undefined"); + truth("class A { m() { return Function('return new.target')(); } } new A().m() === undefined"); +} + #[test] fn deep_class_chains_stay_within_the_limits() { let src = "var C = class {}; for (var i = 0; i < 2000; i++) { C = class extends C {}; } new C();"; diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index b9411e8e3a..d8b81fdcec 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -40,6 +40,7 @@ use std::rc::Rc; use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::symbol::PropKey; use crate::value::Value; use crate::{Data, HostError, HostFunction}; @@ -245,6 +246,22 @@ impl Interp { Ok(false) } + /// [`Self::is_host_member`] for a property key. A Symbol names no host member. + pub(crate) fn is_host_member_pk(&self, id: ObjId, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.is_host_member(id, name), + PropKey::Sym(_) => Ok(false), + } + } + + /// [`Self::has_property_indexed`] for a property key. A Symbol does not go to the indexer. + pub(crate) fn has_pk_indexed(&mut self, id: ObjId, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.has_property_indexed(id, name), + PropKey::Sym(_) => self.has_pk(id, k), + } + } + /// The [`Data`] for the object of a host class `id`, or `None` when it is not one. pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ffc58e64da..86f9d22983 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -29,6 +29,7 @@ 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, }; +use crate::parser::SuperRules; use crate::string_builtins::flat_charged; use crate::symbol::PropKey; use crate::value::{Str, Value, array_index, index_key, number_to_str, string_to_number, to_int32, to_uint32}; @@ -3545,17 +3546,16 @@ impl Interp { /// [`Interp::compile_source`], with [`crate::bytecode::Source::strict_writes`] set to `writes`. pub(crate) fn compile_source_writes(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind) -> Result, CompileError> { - self.compile_units(units, strict, writes, kind, false) + self.compile_units(units, strict, writes, kind, SuperRules::default()) } - /// [`Interp::compile_source_writes`]; `in_function` reads eval code run inside a function, - /// where `new.target` is allowed. - fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, in_function: bool) -> Result, CompileError> { + /// [`Interp::compile_source_writes`]; `supers` says what `super` and `new.target` may do at + /// the top of the code: what they may do where a direct `eval` is called. + fn compile_units(&mut self, units: &[u16], strict: bool, writes: bool, kind: CodeKind, supers: SuperRules) -> Result, 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 { strict, max_source_units: remaining, ..self.options.clone() }; - let parse = if in_function { crate::parse_utf16_in_function } else { crate::parse_utf16 }; - let program = parse(units, &options).map_err(CompileError::Syntax)?; + let program = crate::parse_utf16_with_supers(units, &options, supers).map_err(CompileError::Syntax)?; let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag, strict_writes: writes }); compile_program(&program, &source, kind).map_err(|e| match e { CompileFail::Syntax(s) => CompileError::Syntax(s), @@ -3582,10 +3582,12 @@ impl Interp { self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; self.observe_code(&units); - // Inside a function the eval code reads the function's `new.target` (section 18.2.1.1). - let new_target = self.caller_new_target()?; + // The eval code may use `super` and `new.target` as the code that calls it may, and reads + // the `new.target` of the function it is in (section 18.2.1.1). + let supers = self.frame()?.code.supers; + let new_target = if supers.new_target { self.caller_new_target()? } else { None }; let writes = self.writes_mode(); - let code = self.compile_units(&units, strict, writes, CodeKind::Eval, new_target.is_some()).map_err(|e| self.compile_error_to_abrupt(e))?; + let code = self.compile_units(&units, strict, writes, CodeKind::Eval, supers).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; let (caller_env, caller_var_env, this, this_in_env) = (frame.env, frame.var_env, frame.this.clone(), frame.this_in_env); @@ -4191,11 +4193,7 @@ impl Interp { } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_prop_key(a)?; - match &k { - PropKey::Str(name) => self.has_property_indexed(*o, name), - PropKey::Sym(_) => self.has_pk(*o, &k), - } - .map(Value::Bool) + self.has_pk_indexed(*o, &k).map(Value::Bool) } } } diff --git a/crates/js/src/interp_tests.rs b/crates/js/src/interp_tests.rs index 2dc3008630..cf47fa9848 100644 --- a/crates/js/src/interp_tests.rs +++ b/crates/js/src/interp_tests.rs @@ -1048,6 +1048,7 @@ fn code(ops: Vec) -> Code { own_name: None, method: false, generator: false, + supers: crate::parser::SuperRules::default(), } } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1f2863ed2d..69ecd261a3 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -222,11 +222,11 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result Result { +/// [`parse_utf16`] for code a direct `eval` runs, which may use `super` and `new.target` as the +/// code that calls it may (ECMA-262 2015 section 18.2.1.1). +pub(crate) fn parse_utf16_with_supers(source: &[u16], options: &Options, rules: parser::SuperRules) -> Result { check_length(source.len(), options)?; - parser::Parser::new(source, options, false)?.with_new_target().parse_program().map(|(program, _)| program) + parser::Parser::new(source, options, false)?.with_supers(rules).parse_program().map(|(program, _)| program) } /// The tokens of `source`, in order, as the parser reads them: preprocessor lines included, and diff --git a/crates/js/src/parser.rs b/crates/js/src/parser.rs index a7852f2d14..bb35c08212 100644 --- a/crates/js/src/parser.rs +++ b/crates/js/src/parser.rs @@ -68,14 +68,23 @@ struct Scope { /// What `super` and `new.target` may do where the parser is (ECMA-262 2015 sections 12.3.5.1, /// 12.3.8.1, 14.1.2, 14.5.1 and 15.1.1): set for each function body and kept by arrow functions. -#[derive(Clone, Copy, Debug, Default)] -struct SuperRules { +/// Eval code run by a direct `eval` has the rules of the code that calls it (section 18.2.1.1). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct SuperRules { /// `super.property` and `super[index]`: in a class's methods, accessors and constructor. - property: bool, + pub(crate) property: bool, /// `super(arguments)`: in a derived class's constructor. - call: bool, + pub(crate) call: bool, /// `new.target`: in any function other than an arrow function at the top of a script. - new_target: bool, + pub(crate) new_target: bool, +} + +impl SuperRules { + /// The rules in the body of a function that is not an arrow function: `home` for one with a + /// home object, `derived` for a derived class's constructor. + pub(crate) fn function(home: bool, derived: bool) -> Self { + Self { property: home, call: derived, new_target: true } + } } /// The parameters of a function as they are read: names or patterns, each one's default value, @@ -176,9 +185,12 @@ impl<'s> Parser<'s> { Ok(parser) } - /// Allows `new.target` at the top of the source: eval code run inside a function. - pub(crate) fn with_new_target(mut self) -> Self { - self.supers.new_target = self.es2015; + /// Reads the top of the source with `rules`: eval code run by a direct `eval` inside a + /// function. Without [`crate::Options::es2015`] the rules stay the default. + pub(crate) fn with_supers(mut self, rules: SuperRules) -> Self { + if self.es2015 { + self.supers = rules; + } self } @@ -190,7 +202,15 @@ impl<'s> Parser<'s> { if let Some(tokens) = &mut self.tokens { tokens.push(self.tok.clone()); } - let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 }; + let program = Program { + ast: self.ast, + body, + strict: self.ctx.strict, + directives: self.directives, + lines: self.lines, + es2015: self.es2015, + supers: self.supers, + }; Ok((program, self.tokens.unwrap_or_default())) } @@ -1149,7 +1169,7 @@ impl<'s> Parser<'s> { generator: bool, ) -> Result { self.enter()?; - let rules = SuperRules { property: home, call: kind == FunctionKind::DerivedConstructor, new_target: true }; + let rules = SuperRules::function(home, kind == FunctionKind::DerivedConstructor); let outer = std::mem::replace(&mut self.supers, rules); // The parameters are read with the function's own `yield` rule, not the enclosing code's. let outer_generator = std::mem::replace(&mut self.ctx.generator, generator); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 7d1e74bc07..7accd98667 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1615,7 +1615,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, opacity?: bool, hexField?: bool, 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 at or below the one asked for; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; 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 active document's RGB space (its assigned profile, else 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, opacity, hexField, 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, opacity?: bool, hexField?: bool, 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 Opacity, 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 at or below the one asked for; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; 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 active document's RGB space (its assigned profile, else 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, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/tools/src/context.rs b/crates/tools/src/context.rs index bbdbd28c7e..1d9431fd47 100644 --- a/crates/tools/src/context.rs +++ b/crates/tools/src/context.rs @@ -253,6 +253,8 @@ pub struct ToolContext<'a> { pub raster_sample: u32, /// General → Use Preview Bounds: the bounding box measures visual bounds (strokes included). pub preview_bounds: bool, + /// General → Scale Strokes & Effects: a scale scales the strokes and effects with the art. + pub scale_strokes: bool, /// Type › Measure Type by Glyph Bounds: the bounding box measures each point type object /// selected as an object (not inside a selected group) by the ink of its glyphs /// ([`vectorcraft_effects::preview::Measure`]). diff --git a/crates/tools/src/corners.rs b/crates/tools/src/corners.rs index 3d02e37aa0..9b0dca8928 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 with Direct Selection and shows the //! Transform panel with the Selection tool. The @@ -40,6 +44,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. @@ -48,16 +54,20 @@ 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, when - /// `editable` ([`Document::editable`]) answers true for `id`. + /// 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. Only when `editable` + /// ([`Document::editable`]) answers true for `id`. fn of(doc: &Document, selection: &Selection, id: NodeId, zoom: f64, any_path: bool, editable: &impl Fn(NodeId) -> bool) -> Option { if selection.segments.contains_key(&id) { return None; @@ -77,33 +87,54 @@ 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 }) + 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. #[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 { @@ -113,17 +144,17 @@ impl CornerWidgets { // Made for the first path, then shared: the art on the locked artboards is measured once. let locks = std::cell::OnceCell::new(); let editable = |id| locks.get_or_init(|| doc.editable())(id); - let paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path, &editable)).collect(); - (!paths.is_empty()).then_some(Self { paths }) + let mut paths: Vec<_> = selection.objects.iter().filter_map(|id| PathWidgets::of(doc, selection, *id, zoom, any_path, &editable)).collect(); + 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 /// 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) @@ -147,12 +178,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 @@ -161,28 +193,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) { @@ -244,16 +285,38 @@ 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 -/// (Direct Selection; the Selection tool shows the Transform panel instead). -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 (Direct Selection; +/// the Selection tool shows the Transform panel instead). 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 @@ -289,6 +352,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, @@ -300,7 +365,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 { @@ -309,26 +388,63 @@ 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 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). 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. + 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() @@ -351,6 +467,7 @@ impl CornerDrag { at_limit: false, at: p, click, + unpicked, kind: None, }) } @@ -369,21 +486,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; } @@ -466,9 +583,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 ff190c6493..1e90ce72c7 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,274 @@ 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 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. +#[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 +590,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 +626,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); @@ -473,7 +773,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() { @@ -483,9 +783,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 d5be458880..c1c4bcbfb2 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -67,7 +67,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}; @@ -835,6 +835,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) { @@ -1135,7 +1142,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![]; } @@ -1387,7 +1396,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)) { @@ -1650,7 +1662,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/tools/src/guides/snap.rs b/crates/tools/src/guides/snap.rs index 20caa7de19..6461d5fd72 100644 --- a/crates/tools/src/guides/snap.rs +++ b/crates/tools/src/guides/snap.rs @@ -116,6 +116,10 @@ pub struct PointSnap { /// The kind of edit the point serves: whether Snap to Pixel rounds it /// ([`ToolContext::snaps_to_pixel`]). op: PixelOp, + /// For a scale with Smart Guides and Use Preview Bounds on: the selection's geometric bounds, + /// whose edges line up with the other art's geometric bounds while the handle drags the visual + /// box ([`Self::snap_scale`]). + edges: Option, } impl PointSnap { @@ -134,6 +138,17 @@ impl PointSnap { Self::for_op(cx, PixelOp::Scaling, targets) } + /// [`Self::scaling`] for the selection's bounding box: with Smart Guides and Use Preview + /// Bounds on, the selection's geometric bounds are the edges that line up. + pub fn scaling_selection(cx: &ToolContext) -> Self { + let mut snap = Self::scaling(cx, || Targets::for_scale(cx)); + if snap.targets.is_some() && cx.smart_guides && cx.preview_bounds { + let geometric = vectorcraft_effects::preview::Measure { preview: false, ..cx.bounds_measure() }; + snap.edges = vectorcraft_effects::preview::oriented_bounds_with(cx.doc, &cx.selection.objects, geometric); + } + snap + } + fn for_op(cx: &ToolContext, op: PixelOp, targets: impl FnOnce() -> Targets) -> Self { let targets = if cx.snaps_to_pixel(op) || cx.snap_to_grid { None @@ -147,7 +162,7 @@ impl PointSnap { } else { None }; - Self { targets, op } + Self { targets, op, edges: None } } /// Snapping for a point placed anywhere, as a drawing tool's ([`DrawSnap`]) is: the art in the @@ -182,7 +197,10 @@ impl PointSnap { /// Snap to Pixel on for scaling, the corner or side the handle moves lines up with whole /// pixels, and with Snap to Grid on it lines up with the nearest gridline, however far that /// is; neither shows guides. Otherwise the handle snaps to the targets [`Self::scaling`] - /// gathered. + /// gathered. With Smart Guides and Use Preview Bounds on, the edges of the selection's + /// geometric bounds line up with the targets, which are the other art's geometric bounds, while + /// the handle stays on the visual box (#6436). The margins between the two boxes keep their + /// size unless Scale Strokes & Effects is on. pub fn snap_scale( &self, cx: &ToolContext, @@ -205,8 +223,10 @@ impl PointSnap { // one step always finds one. return (Targets::grid_lines(moved, step).snap_scale(bx, handle, a, proportional, from_center, step).0, vec![]); } + // The geometric box lines up when it turns with the box the handle drags. + let edges = self.edges.filter(|g| (g.angle - bx.angle).abs() <= 1e-9).map(|g| (g.rect, !cx.scale_strokes)); match &self.targets { - Some((t, tol)) => t.snap_scale(bx, handle, a, proportional, from_center, cx.tol(*tol)), + Some((t, tol)) => t.snap_scale_edges(bx, edges, handle, a, proportional, from_center, cx.tol(*tol)), None => (a, vec![]), } } @@ -448,7 +468,7 @@ impl DrawSnap { /// Guides snapping tolerance (the Knife's straight cut). The targets serve this press only. pub fn press_on_paths(&mut self, cx: &ToolContext, p: Point) -> Point { let targets = Targets::for_drawing(cx.doc, &[], visible(cx), None).styled(cx).anchors_and_paths(); - self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing })); + self.targets = Some((None, PointSnap { targets: Some((targets, cx.snapping_tolerance)), op: PixelOp::Drawing, edges: None })); self.snap(cx, p, None) } @@ -467,7 +487,7 @@ impl DrawSnap { /// again on every move, as [`PointSnap::snap_from`] reads pixels and the grid), nothing in /// reach, or an anchor, center or crossing in reach of `p` or at `corner`. pub fn circle_radius(&mut self, cx: &ToolContext, center: Point, p: Point, corner: Point, r: f64) -> Option { - let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return None }; + let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return None }; if !cx.smart_guides || !cx.snap_tangent || cx.snaps_to_pixel(*op) || cx.snap_to_grid { return None; } @@ -517,7 +537,7 @@ impl DrawSnap { /// gathered ([`Targets::snap_hit`]), whether or not its guides show. False with Smart Guides /// off, with no targets, and while pixels or the grid snap instead. pub(crate) fn lands_on_target(&self, cx: &ToolContext, p: Point, from: Option<&Leave>) -> bool { - let Some((_, PointSnap { targets: Some((t, tol)), op })) = &self.targets else { return false }; + let Some((_, PointSnap { targets: Some((t, tol)), op, .. })) = &self.targets else { return false }; cx.smart_guides && !cx.snaps_to_pixel(*op) && !cx.snap_to_grid && t.snap_hit(p, from, cx.tol(*tol)).2 } diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 5f30ce3a7c..209b73dcb1 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -1583,12 +1583,39 @@ impl Targets { /// the nearest target or ruler guide ("align"), whatever the box's angle. A handle with one way /// to go (a side, or a proportional corner) slides along it until one of them is on a target. pub fn snap_scale(&self, bx: &OrientedBox, handle: Handle, a: Affine, proportional: bool, from_center: bool, tol: f64) -> (Affine, Vec) { + self.snap_scale_edges(bx, None, handle, a, proportional, from_center, tol) + } + + /// [`Self::snap_scale`], with the edges of `edges` landing on the targets in place of the + /// edges of `bx`. `edges` is a box in `bx`'s frame, such as the selection's geometric bounds + /// inside the visual bounds that Use Preview Bounds shows. With its `true`, the margins between + /// the two boxes keep their size as `bx` scales, as `object.setBounds` keeps them; with `false` + /// they scale with it, as `object.transform` scales them. The scale stays one of `bx`. + #[allow(clippy::too_many_arguments)] + pub fn snap_scale_edges( + &self, + bx: &OrientedBox, + edges: Option<(Rect, bool)>, + handle: Handle, + a: Affine, + proportional: bool, + from_center: bool, + tol: f64, + ) -> (Affine, Vec) { type Hit = Option<(f64, Point)>; // Where a snap lands: in line with a target's x and/or y, or on an anchor or centre. type Snap = (Hit, Hit, Option<(Point, Kind)>); let r = bx.rect; let origin = if from_center { r.center() } else { handle.opposite().pos(r) }; let (d0, [sx, _, _, sy, _, _]) = (handle.pos(r) - origin, a.as_coeffs()); + // Margins that keep their size are only measured on a box that does not flip. + let edges = edges.filter(|(g, keep)| g.is_finite() && (!keep || (sx > 0.0 && sy > 0.0))); + let lands = |h: Handle| scale_lands(r, edges, origin, h); + let at = |nx: f64, ny: f64, h: Handle| { + let (v, off) = lands(h); + origin + Vec2::new(nx * v.x, ny * v.y) + off + }; + let landed = |out: Affine| scale_landed(bx, edges, out); let (to_doc, to_local) = (bx.to_doc(), bx.to_doc().inverse()); // A scale that collapses or flips the box is no snap. let valid = |n: f64, s: f64| n.is_finite() && n * s > 0.0; @@ -1610,7 +1637,8 @@ impl Targets { if handle.is_corner() && !proportional { // The corner goes anywhere: onto an anchor or centre, else it takes the target's x, its // y, or both. - let p = to_doc * (a * handle.pos(r)); + let (v, off) = lands(handle); + let p = to_doc * at(sx, sy, handle); let (hx, hy) = (nearest(p, true), nearest(p, false)); let on = self.nearest_point(p, tol).map(|(q, k)| (Some((q.x, q)), Some((q.y, q)), Some((q, k)))); for (tx, ty, at) in on.into_iter().chain([(hx, hy, None), (hx, None, None), (None, hy, None)]) { @@ -1618,7 +1646,7 @@ impl Targets { continue; } let q = to_local * Point::new(tx.map_or(p.x, |h| h.0), ty.map_or(p.y, |h| h.0)); - let (mut cx, mut cy) = ((q.x - origin.x) / d0.x, (q.y - origin.y) / d0.y); + let (mut cx, mut cy) = ((q.x - off.x - origin.x) / v.x, (q.y - off.y - origin.y) / v.y); // Square to the page, the axis without a target stays exactly where it was. if bx.angle == 0.0 { (cx, cy) = (if tx.is_some() { cx } else { sx }, if ty.is_some() { cy } else { sy }); @@ -1654,8 +1682,8 @@ impl Targets { } }; for h in std::iter::once(handle).chain(ends.into_iter().flatten().copied()) { - let v = h.pos(r) - origin; - let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y)); + let (v, off) = lands(h); + let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y) + off); let dir = (to_doc * Point::new(e.0 * v.x, e.1 * v.y)).to_vec2(); let p = base + dir * s0; // An anchor or centre beside its way: it stops at the nearest point of the way. @@ -1683,7 +1711,7 @@ impl Targets { return (out, self.label(q, k.label()).into_iter().collect()); } // The lines run from the target's own point across the resized box, on the page. - let mut nr = (to_doc * out).transform_rect_bbox(r); + let mut nr = landed(out); let mut ov = vec![]; if let Some((x, from)) = hit_x { ov.extend(self.line(Point::new(x, from.y.min(nr.y0)), Point::new(x, from.y.max(nr.y1)))); @@ -1692,7 +1720,7 @@ impl Targets { ov.extend(self.line(Point::new(from.x.min(nr.x0), y), Point::new(from.x.max(nr.x1), y))); } if hit_x.is_some() || hit_y.is_some() { - ov.extend(self.label(to_doc * (out * handle.pos(r)), "align")); + ov.extend(self.label(to_doc * at(nx, ny, handle), "align")); } if !self.boxes.is_empty() && !from_center { let aligned = [hit_x.is_some(), hit_y.is_some()]; @@ -1705,8 +1733,7 @@ impl Targets { let (lo, hi) = span(&nr, is_x); let len = hi - lo; let new_len = if moves_min { hi - (lo + shift) } else { hi + shift - lo }; - if len > 1e-9 && new_len > 1e-9 { - let f = new_len / len; + if let Some(f) = spacing_factor(bx, edges, out, is_x, len, new_len) { let (ax, ay) = handle.axes(); if is_x { nx *= f; @@ -1720,7 +1747,7 @@ impl Targets { } } out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2()); - nr = (to_doc * out).transform_rect_bbox(r); + nr = landed(out); ov.extend(gaps.into_iter().flat_map(|g| self.gap_marks(g, is_x, tol))); } } @@ -1729,3 +1756,42 @@ impl Targets { (out, ov) } } + +/// Where a point `h` of the box `r` scaled about `origin` goes when the box `edges` lines up in +/// its place ([`Targets::snap_scale_edges`]): to `origin + scale·v + off` for the `(v, off)` given. +fn scale_lands(r: Rect, edges: Option<(Rect, bool)>, origin: Point, h: Handle) -> (Vec2, Vec2) { + match edges { + Some((g, true)) => (h.pos(r) - origin, h.pos(g) - h.pos(r)), + Some((g, false)) => (h.pos(g) - origin, Vec2::ZERO), + None => (h.pos(r) - origin, Vec2::ZERO), + } +} + +/// What the scale `out` of `bx` is multiplied by along x (`is_x`) or y for the box whose edges +/// line up to go from length `len` to `new_len` ([`Targets::snap_scale_edges`]). When the margins +/// between `bx` and those edges keep their size, the scale multiplies `bx`'s own length, which +/// changes by as much. None for a length that would collapse. +fn spacing_factor(bx: &OrientedBox, edges: Option<(Rect, bool)>, out: Affine, is_x: bool, len: f64, new_len: f64) -> Option { + let scaled = if matches!(edges, Some((_, true))) { + let (lo, hi) = span(&(bx.to_doc() * out).transform_rect_bbox(bx.rect), is_x); + hi - lo + } else { + len + }; + let grown = scaled + new_len - len; + (len > 1e-9 && new_len > 1e-9 && scaled > 1e-9 && grown > 1e-9).then(|| grown / scaled) +} + +/// The box whose edges line up ([`Targets::snap_scale_edges`]), on the page, after the scale `out` +/// of `bx`. +fn scale_landed(bx: &OrientedBox, edges: Option<(Rect, bool)>, out: Affine) -> Rect { + let r = bx.rect; + match edges { + Some((g, true)) => { + let n = out.transform_rect_bbox(r); + bx.to_doc().transform_rect_bbox(Rect::new(n.x0 + g.x0 - r.x0, n.y0 + g.y0 - r.y0, n.x1 - (r.x1 - g.x1), n.y1 - (r.y1 - g.y1))) + } + Some((g, false)) => (bx.to_doc() * out).transform_rect_bbox(g), + None => (bx.to_doc() * out).transform_rect_bbox(r), + } +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 449dad62d8..c83ffe5c3c 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -652,6 +652,7 @@ pub(crate) mod testutil { freeform_point: None, raster_sample: 1, preview_bounds: false, + scale_strokes: false, glyph_bounds: false, preview_memo: None, unit: Unit::Points, diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 7510358fc4..4e3f2c16f9 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -1985,7 +1985,7 @@ impl SelectionTool { // What the handle moves snaps as a dragged point does: to pixels or the // grid, else with Smart Guides to the other objects, else with Snap to // Point to their anchors; the ruler guides with Snap to Point. - self.targets = Some(PointSnap::scaling(cx, || Targets::for_scale(cx))); + self.targets = Some(PointSnap::scaling_selection(cx)); self.last_backquote = false; self.last_box_pos = None; self.state = State::Scaling { handle, bx, areas }; diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index e74e3d9163..45bc30b47e 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -1291,6 +1291,48 @@ fn a_move_lines_up_geometric_edges_with_use_preview_bounds_on() { } } +/// With Use Preview Bounds on, a scale handle drags the visual box, and Smart Guides line up the +/// selection's geometric edge with the other art's geometric edge, as a move does. +#[test] +fn a_scale_lines_up_geometric_edges_with_use_preview_bounds_on() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Node}; + // An artboard whose edges and center are out of reach, and two rectangles stroked 20 pt. + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let mut add = |r: Rect| { + let id = d.alloc_id(); + let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0); + d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap(); + id + }; + let a = add(Rect::new(100.0, 100.0, 200.0, 200.0)); + add(Rect::new(300.0, 100.0, 400.0, 200.0)); + let s = Selection { objects: vec![a], ..Default::default() }; + let p = paint(); + // The right edge of the box the right-middle handle leaves: the geometric edge with the option + // off, the visual edge 10 pt outside it with the option on. + let right = |preview: bool, from: f64, to: f64| { + let c = ToolContext { preview_bounds: preview, ..cx(&d, &s, &p) }; + let mut t = SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, from, 150.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0)); + match a.last() { + Some(Action::Preview(cmd, v)) if cmd == "object.setBounds" => 90.0 + v["width"].as_f64().unwrap(), + Some(Action::Preview(_, v)) => v["matrix"][0].as_f64().unwrap() * 200.0 + v["matrix"][4].as_f64().unwrap(), + _ => panic!("{a:?}"), + } + }; + let near = |got: f64, want: f64| (got - want).abs() < 1e-9; + // Option off: the edge 1 pt short of the other rectangle's left edge (x = 300) lands on it. + assert!(near(right(false, 200.0, 299.0), 300.0), "{}", right(false, 200.0, 299.0)); + assert!(near(right(false, 200.0, 291.0), 291.0), "{}", right(false, 200.0, 291.0)); + // Option on: the geometric edge 1 pt short lands on it, which leaves the visual edge at 310. + assert!(near(right(true, 210.0, 309.0), 310.0), "{}", right(true, 210.0, 309.0)); + // The visual edge 1 pt past it does not pull the box there: the geometric edge is 9 pt short. + assert!(near(right(true, 210.0, 301.0), 301.0), "{}", right(true, 210.0, 301.0)); +} + /// Smart Guides › Snap to Last Location: a move that comes within Snapping Tolerance of where it /// began goes back there, labeled "last location", a Shift move too; farther out, with the option /// or Smart Guides off, it stays where it is dragged, and an Alt copy snaps as it does with the diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index cb288e5938..0811fdcad9 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -41,7 +41,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag}; -use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square}; +use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, square}; use crate::pie::{self, PieDrag}; use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box}; use crate::sidewidget::{self, SideDrag}; @@ -363,7 +363,7 @@ impl ShapeTool { self.selection = if let Some((handle, bx)) = self.over_handle(cx, ev.pos) { let is_area = |id: &vectorcraft_doc::NodeId| cx.doc.node(*id).is_some_and(is_area_type); let areas = cx.selection.objects.iter().any(is_area); - Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling(cx, || Targets::for_scale(cx))), last: None }) + Some(SelectionDrag::Scale { handle, bx, areas, snap: Box::new(PointSnap::scaling_selection(cx)), last: None }) } else { match hit_center(cx, ev.pos, cx.point_tol()) { Some((_, hold)) => Some(SelectionDrag::Move { start: ev.pos, hold, began: false, snap: Box::new(MoveSnap::new(cx)) }), diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 6b7f213469..8fdf6fb163 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -14,7 +14,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::{BLUE, polygon, rect_corners}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; -use crate::guides::{PointSnap, Targets}; +use crate::guides::PointSnap; use crate::select::{handle_cursor, matrix_json, screen_handle, selection_box}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -273,7 +273,7 @@ impl Tool for FreeTransformTool { self.drag = None; let Some(bx) = selection_box(cx) else { return vec![] }; if let Some(op) = self.classify(cx, &bx, p, ev.mods) { - self.targets = op.handle().is_some().then(|| PointSnap::scaling(cx, || Targets::for_scale(cx))); + self.targets = op.handle().is_some().then(|| PointSnap::scaling_selection(cx)); self.drag = Some(Drag { op, bx, start: p, began: false }); } vec![] @@ -454,6 +454,38 @@ mod tests { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 213.0, 150.0)), vec![Action::Commit]); } + /// With Use Preview Bounds on, a handle drags the visual box, and Smart Guides line up the + /// selection's geometric edge with the other art's geometric edge. + #[test] + fn handle_drag_lines_up_geometric_edges_with_use_preview_bounds_on() { + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Document, Node}; + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let mut add = |r: Rect| { + let id = d.alloc_id(); + let wide = Appearance::basic(Paint::solid(Color::WHITE), Paint::solid(Color::BLACK), 20.0); + d.insert(Some(l), 0, Node::path(id, vectorcraft_geom::shapes::rectangle(r), wide)).unwrap(); + id + }; + let a = add(Rect::new(100.0, 100.0, 200.0, 200.0)); + add(Rect::new(300.0, 100.0, 400.0, 200.0)); + let s = Selection { objects: vec![a], ..Default::default() }; + let p = paint(); + let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }; + // The right edge of the visual box (90 to 210) after a drag of its right-middle handle. + let right = |to: f64| { + let mut t = FreeTransformTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 210.0, 150.0)); + let a = t.pointer(&c, &ev(PointerKind::Drag, to, 150.0)); + let Some(Action::Preview(_, v)) = a.last() else { panic!("{a:?}") }; + v["matrix"][0].as_f64().unwrap() * 210.0 + v["matrix"][4].as_f64().unwrap() + }; + // The geometric edge 1 pt short of x = 300 lands on it; the visual edge 1 pt past does not. + assert!((right(309.0) - 310.0).abs() < 1e-9, "{}", right(309.0)); + assert!((right(301.0) - 301.0).abs() < 1e-9, "{}", right(301.0)); + } + /// In a view turned 90° the handles' cursors turn with the view. #[test] fn handle_cursors_turn_with_the_view() { diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 00b05b350c..3fbe8c3cac 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -1111,6 +1111,41 @@ fn a_soft_gray_band_along_black_traces_as_black_and_white() { assert!((36..=42).contains(&blur_three), "bands 4 px wide blurred by 3 px: {blur_three} of 192 samples traced gray"); } +/// A gray band 3 or 4 pixels wide along a black disc, with edges blurred by 0.6 pixels and a flat +/// square of the same gray elsewhere, keeps at least 4 of every 5 samples gray when the gray is named +/// 6 or 12 levels lighter or darker than the band's color, as it does when the gray is named exactly: +/// the pixels of the square's color count as pixels of the gray. +#[test] +fn a_gray_band_along_black_keeps_its_gray_when_named_some_levels_off_its_flat_areas() { + const INK: [u8; 3] = [4, 4, 3]; + for gray in [230u8, 200, 128] { + for off in [-12i16, -6, 6, 12] { + let Ok(named) = u8::try_from(i16::from(gray) + off) else { continue }; + for wide in [3u8, 4] { + let img = render(120, 60, 0.6, |x, y| { + let band = (40.0..43.0 + f64::from(wide)).contains(&x) && (20.0..36.0).contains(&y); + let square = (80.0..110.0).contains(&x) && (15.0..45.0).contains(&y); + Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 { + INK + } else if band || square { + [gray; 3] + } else { + WHITE + }) + }); + let res = trace(&img, &black_gray_white([named; 3])); + let kept = (0..wide) + .flat_map(|c| (20..36).map(move |y| Point::new(43.5 + f64::from(c), f64::from(y) + 0.5))) + .filter(|&at| top_color(&res, at) == Some([named; 3])) + .count(); + let all = 16 * usize::from(wide); + assert!(5 * kept >= 4 * all, "gray {gray} named {named}, {wide} px band: {kept} of {all} samples traced gray"); + assert_eq!(top_color(&res, Point::new(95.0, 30.0)), Some([named; 3]), "gray {gray} named {named}: the square"); + } + } + } +} + /// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred /// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest. Blurred /// by 2 pixels, a spoke three pixels wide loses 2 or 3 of them, and one two pixels wide traces as diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index 048c8fac71..59b6594c04 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -27,12 +27,12 @@ const NEARBY: usize = 6; const WALK: usize = 5; /// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area. const FLAT: f64 = 1.5 / 255.0; -/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a -/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer. -/// A straight edge whose anti-aliased pixels come within `PURE` of -/// a class gives the same pixels as a line of that class, and keeps the class too. A one-pixel line -/// between two classes that is shorter, falls between pixels or is blurred is read as a blend of -/// those two classes. +/// How many joined pixels within [`PURE`] of one class (or of the colors of its flat areas, for a +/// class named some levels off them, [`area_colors`]) are taken as art of that class, such as a +/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer. A +/// straight edge whose anti-aliased pixels come within `PURE` of a class gives the same pixels as a +/// line of that class, and keeps the class too. A one-pixel line between two classes that is shorter, +/// falls between pixels or is blurred is read as a blend of those two classes. const LINE: usize = 2 * NEARBY + 1; struct Subset { @@ -209,24 +209,33 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] // ([`flat_classes`], [`RowDistances::around`]); the other mix lies as near as the steps that // `across_edge` counts when those are fewer. For the best mix, // the classes held by flat areas between two classes count as well ([`between_classes`]). A - // pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class + // pixel of a class (within `PURE` of it, or of the colors of its flat areas when it is named some + // levels off them, [`area_colors`]) that is joined to at least [`LINE`] such pixels of that class // (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white. let flat = flat_classes(pix, &stands_for, width, height); let between = between_classes(pix, &flat, &mixed, width, height); - let runs = pure_runs(&pure, width, height); + let colors = area_colors(pix, classes, &flat, &between); + let of_class = (!colors.iter().all(FlatColors::is_empty)).then(|| { + pure.iter() + .zip(pix) + .map(|(&q, px)| q.or_else(|| (0..k).find(|&c| colors.get(c).is_some_and(|cs| near_area_color(px, cs))))) + .collect::>() + }); + let of_class = of_class.as_deref().unwrap_or(&pure); + let runs = pure_runs(of_class, width, height); let mut flat_rows = RowDistances::new(|j| [flat.get(j).copied().flatten(), None], width, height, k); let mut between_rows = (!between.is_empty()).then(|| RowDistances::new(|j| between.get(j).copied().unwrap_or([None; 2]), width, height, k)); let mut dist = vec![NEARBY + 1; k]; let mut kept = vec![NEARBY + 1; k]; for (i, key) in tied { - if pure.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) { + if of_class.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) { continue; } let Some(mixes) = mixed.get(&key) else { continue }; let edges: Vec<(&Weights, usize)> = mixes .tied .iter() - .filter_map(|m| across_edge(pix, (&flat, &stands_for), (width, height), i, classes, &mixes.best, m).map(|r| (m, r))) + .filter_map(|m| across_edge(pix, (&flat, &stands_for, &colors), (width, height), i, classes, &mixes.best, m).map(|r| (m, r))) .collect(); if edges.is_empty() { continue; @@ -258,7 +267,10 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] /// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so /// does one that keeps going toward the other. When the first step of one path comes to a pixel /// that stands for its class of `other` (the edge on that side is sharp), the other path stops at -/// a pixel within [`PURE`] of the class left out that it comes to before it gets past that class. +/// a pixel of the class left out that it comes to before it gets past that class: a pixel within +/// [`PURE`] of it, or, for a class named some levels off the colors of its flat areas +/// ([`area_colors`]), within `PURE` of one of those colors, or within `PURE` of the class as named +/// together with the pixel before it. /// For a class left out that lies beyond both classes of `other` on that line, the pixel has a /// neighbor on each side of that class, or a neighbor on each side of the pixel itself, none past /// the class of `other` nearer the class left out, and a chain of neighbors from the pixel to that @@ -279,7 +291,7 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] /// path does not come to such a pixel, and when a class left out lies beyond both classes of `other`. fn across_edge( pix: &[Px], - (flat, stands_for): (&[Option], &[Option]), + (flat, stands_for, colors): (&[Option], &[Option], &AreaColors), (width, height): (usize, usize), i: usize, classes: &[[f64; 4]], @@ -356,11 +368,19 @@ fn across_edge( } false }; - // Whether pixel `j` comes within `PURE` of class `c`. - let within = |j: usize, c: usize| { + // Whether pixel `j` comes within `PURE` of class `c` as named. + let named = |j: usize, c: usize| { let (Some(q), Some(cv)) = (pix.get(j), classes.get(c)) else { return false }; (0..4).map(|k| (f64::from(q[k]) - cv[k]).powi(2)).sum::().sqrt() < PURE }; + // Whether pixel `j`, reached from pixel `prev`, is a pixel of class `c`: within `PURE` of it, or, + // for a class named some levels off the colors of its flat areas ([`area_colors`]), within `PURE` + // of one of those colors, or within `PURE` of the class as named with `prev` too (the class as + // named lies across at least two pixels there, which the pixels of a black-to-white edge do not). + let within = |prev: usize, j: usize, c: usize| match colors.get(c) { + Some(cs) if !cs.is_empty() => pix.get(j).is_some_and(|q| near_area_color(q, cs)) || (named(prev, c) && named(j, c)), + _ => named(j, c), + }; // The neighbor of pixel `j` near the line that lies farthest toward `a` (`toward` -1) or `b` // (`toward` 1), with its place. let next = |j: usize, toward: f64| around(j).filter_map(|n| at(n).map(|tn| (n, tn))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward))); @@ -368,19 +388,22 @@ fn across_edge( // pixel before (the first step is taken whatever `i` itself is). `None` when it does not get more // than `PURE` past `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that // stands for `class` (`stands_for`), or `NEARBY + 1`. With `halt`, the path also ends at a pixel - // within `PURE` of that class that it comes to before it gets past `tc`. + // of that class ([`within`]) that it comes to before it gets past `tc`. let walk = |toward: f64, tc: f64, class: usize, halt: Option| { let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward); let mut past = false; for step in 1..=WALK { + let prev = cur; match next(cur, toward) { Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj), _ => break, } - past = past || (t - tc) * toward * len > PURE; - if !past && halt.is_some_and(|h| within(cur, h)) { + // (A pixel of a flat area's color can lie past `tc` itself, when the class is named some + // levels off that color: the path stops there when it was not past `tc` before.) + if !past && halt.is_some_and(|h| within(prev, cur, h)) { break; } + past = past || (t - tc) * toward * len > PURE; if past && stands_for.get(cur).copied().flatten() == Some(class) { return Some(step); } @@ -484,6 +507,88 @@ fn between_classes(pix: &[Px], flat: &[Option], mixed: &HashMap<[u32; 4], held } +/// For each class with a flat area [`PURE`] or more from it (as when it is named some levels off its +/// color), the distinct colors of its flat areas: the flat areas that +/// stand for it (`flat`) and those whose mix holds it most (`between`, [`between_classes`]). Empty for +/// a class whose flat areas all come within `PURE` of it. +fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option], between: &[[Option; 2]]) -> Vec { + let mut colors: Vec = vec![FlatColors::default(); classes.len()]; + let mut off_named = vec![false; classes.len()]; + let mut kept: HashSet<(usize, [u32; 4])> = HashSet::new(); + for (i, px) in pix.iter().enumerate() { + let Some(c) = flat.get(i).copied().flatten().or_else(|| between.get(i).and_then(|b| b[0])) else { continue }; + let (Some(cv), Some(seen), Some(off)) = (classes.get(c), colors.get_mut(c), off_named.get_mut(c)) else { continue }; + *off = *off || (0..4).map(|j| (f64::from(px[j]) - cv[j]).powi(2)).sum::().sqrt() >= PURE; + if kept.insert((c, px.map(f32::to_bits))) { + seen.push(*px); + } + } + for (seen, off) in colors.iter_mut().zip(off_named) { + if !off { + seen.clear(); + } + } + colors +} + +/// Whether `px` comes within [`PURE`] of one of `colors`. +fn near_area_color(px: &Px, colors: &FlatColors) -> bool { + colors.near(px) +} + +/// The colors of one class's flat areas, kept in cells `2 * PURE` wide on each channel, so a color +/// within [`PURE`] of a pixel lies in the pixel's cell or, on each channel, the next cell on the side +/// the pixel lies nearer: 16 cells in all. +#[derive(Clone, Default)] +struct FlatColors { + cells: HashMap<[i32; 4], Vec>, +} + +impl FlatColors { + fn cell(px: &Px) -> [i32; 4] { + px.map(|v| (f64::from(v) / (2.0 * PURE)).floor() as i32) + } + + fn push(&mut self, px: Px) { + self.cells.entry(Self::cell(&px)).or_default().push(px); + } + + fn is_empty(&self) -> bool { + self.cells.is_empty() + } + + fn clear(&mut self) { + self.cells.clear(); + } + + /// Whether one of the colors lies within [`PURE`] of `px`. + fn near(&self, px: &Px) -> bool { + if self.cells.is_empty() { + return false; + } + let at = Self::cell(px); + // On each channel, -1 or +1: the neighboring cell on the side of the cell's middle the pixel lies. + let side = [0, 1, 2, 3].map(|j| { + let pos = f64::from(px[j]) / (2.0 * PURE) - f64::from(at[j]); + if pos < 0.5 { -1 } else { 1 } + }); + (0..16usize).any(|n| { + let mut key = at; + for (j, k) in key.iter_mut().enumerate() { + if (n >> j) & 1 == 1 { + *k = k.saturating_add(side[j]); + } + } + self.cells.get(&key).is_some_and(|qs| qs.iter().any(|q| distance(px, q) < PURE)) + }) + } +} + +/// How far apart two pixels are (in 0..1 premultiplied RGBA). +fn distance(a: &Px, b: &Px) -> f64 { + (0..4).map(|j| (f64::from(a[j]) - f64::from(b[j])).powi(2)).sum::().sqrt() +} + /// For each of `k` classes, how far along each row the nearest pixel holding that class (`at`, the /// classes pixel `j` holds) lies from each pixel, up to `NEARBY + 1` when none lies within /// [`NEARBY`]. A row is worked out when it is first asked for, so a few pixels cost a few rows. @@ -612,6 +717,9 @@ fn in_flat_area(pix: &[Px], width: usize, height: usize, x: usize, y: usize) -> /// Each class's weight in a pixel's mix. type Weights = Vec<(usize, f32)>; +/// For each class, the colors of its flat areas that lie [`PURE`] or more from it ([`area_colors`]). +type AreaColors = [FlatColors]; + /// A mix tried for a pixel: its squared error with its penalty, the penalty, and its classes with /// their weights (the first `n`). #[derive(Clone, Copy)] @@ -803,6 +911,59 @@ mod tests { } } + #[test] + fn a_column_as_light_as_a_class_keeps_it_beside_a_flat_area_some_levels_off_it() { + // As above, with a flat area of the gray some levels darker than it is named to the right of + // the white: a column of `LINE` rows at the named value is still gray art. + let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + let mut pix = Vec::new(); + for _ in 0..LINE { + pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]); + pix.push([0.9, 0.9, 0.9, 1.0]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + pix.extend([[0.87f32, 0.87, 0.87, 1.0]; 5]); + } + let (pl, _, _) = unmix(&pix, 16, LINE, &classes); + for y in 0..LINE { + assert_eq!(pl[0][y * 16 + 5], 1.0, "gray in row {y}"); + assert!(pl[0][y * 16 + 13] > 0.9, "the flat area in row {y}"); + } + } + + #[test] + fn a_short_strip_as_light_as_a_class_traces_the_same_beside_a_flat_area_some_levels_off_it() { + // Three rows of flat black, a strip 1 to 3 pixels wide at the gray's value and flat white: with + // a flat area of the gray some levels darker than it is named to the right of the white, the + // strip's pixels take the same mixes as without it (a strip 2 or 3 pixels wide stays gray). + let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + for wide in [1usize, 2, 3] { + let rows = |area: bool| { + let mut pix = Vec::new(); + for _ in 0..3 { + pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]); + pix.extend(vec![[0.9f32, 0.9, 0.9, 1.0]; wide]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + if area { + pix.extend([[0.87f32, 0.87, 0.87, 1.0]; 5]); + } + } + pix + }; + let w = 10 + wide; + let (alone, _, _) = unmix(&rows(false), w, 3, &classes); + let (beside, _, _) = unmix(&rows(true), w + 5, 3, &classes); + for y in 0..3 { + for x in 0..w { + let mix = |pl: &[Vec], w: usize| pl.iter().take(3).map(|p| p[y * w + x]).collect::>(); + assert_eq!(mix(&beside, w + 5), mix(&alone, w), "{wide} px strip: the mix at ({x}, {y})"); + } + } + if wide > 1 { + assert_eq!(beside[0][w + 5 + 5], 1.0, "{wide} px strip: gray"); + } + } + } + #[test] fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() { // A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway @@ -906,6 +1067,43 @@ mod tests { } } + #[test] + fn every_flat_area_color_keeps_its_whole_neighborhood() { + // A class named 228, 228, 227 and flat areas of 222 then 223: a pixel of 225 lies within + // `PURE` of 223 but not of 222, so it counts as art of the class only when 223 is kept. + let level = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let classes = vec![[228.0 / 255.0, 228.0 / 255.0, 227.0 / 255.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; + let pix = vec![level(222.0), level(222.0), level(223.0), level(223.0)]; + let flat = vec![Some(0); pix.len()]; + let between = vec![[None; 2]; pix.len()]; + let colors = area_colors(&pix, &classes, &flat, &between); + assert_eq!(colors[0].cells.values().map(Vec::len).sum::(), 2); + assert!(near_area_color(&level(225.0), &colors[0])); + let mut only_222 = FlatColors::default(); + only_222.push(level(222.0)); + assert!(!near_area_color(&level(225.0), &only_222)); + } + + #[test] + fn flat_colors_find_what_a_scan_of_every_color_finds() { + let at = |r: f32, g: f32, b: f32, a: f32| [r / 255.0, g / 255.0, b / 255.0, a / 255.0]; + let stored: Vec = (0..40u8).map(|n| at(f32::from(n) * 6.3, 255.0 - f32::from(n) * 2.9, f32::from(n % 7) * 3.1, 255.0)).collect(); + let mut index = FlatColors::default(); + for &q in &stored { + index.push(q); + } + assert!(stored.iter().all(|q| index.near(q))); + for r in (0..=255u8).step_by(3) { + for g in [0.0f32, 100.0, 140.0, 200.0, 254.0] { + for b in [0.0f32, 2.0, 5.0, 9.0, 18.0] { + let px = at(f32::from(r), g, b, 255.0); + let scan = stored.iter().any(|q| distance(&px, q) < PURE); + assert_eq!(index.near(&px), scan, "{px:?}"); + } + } + } + } + #[test] fn weights_sum_to_one() { let pix = vec![[0.2, 0.1, 0.5, 0.8], [0.9, 0.0, 0.05, 0.95]]; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 53c9664aec..b7ff421414 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -166,6 +166,8 @@ impl VectorcraftApp { } let mut params = params; self.add_active_artboard(id, &mut params); + // A script's `app.doScript` plays the Actions panel's actions. + panels::actions::add_script_actions(self, id, &mut params); // Edit Symbol from the Symbols panel in a document without artboards centers the symbol's // art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit // steps too. @@ -272,8 +274,10 @@ 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. panels::swatches::after_command(self, id, ¶ms, v); + panels::swatches::follow_drag(self); if id == "file.new" { self.status(""); // New Document's Pixel preview mode (Overprint Preview is the engine's). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 9a7734e494..8826becc47 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -299,6 +299,7 @@ fn show_body(app: &mut VectorcraftApp, ui: &mut Ui, space: &CanvasSpace, pass: O crate::dialogs::simplify_slider::show(app, ui, &space.view); } guides::show(app, ui, space, win, kind); + widgets::show_hollow_corners(app, ui, space, kind); // The selection's marks paint here, under the widgets and bars, and are drawn after the tool host has taken this // frame's pointer event, from the document as the event leaves it. let marks = PaintSlot::reserve(ui.painter()); diff --git a/crates/ui-egui/src/canvas/drops/tests.rs b/crates/ui-egui/src/canvas/drops/tests.rs index 9803cb73b6..802568a10a 100644 --- a/crates/ui-egui/src/canvas/drops/tests.rs +++ b/crates/ui-egui/src/canvas/drops/tests.rs @@ -233,7 +233,14 @@ fn a_pattern_swatch_dropped_off_the_art_places_a_copy_of_its_tile_art_there() { app.run("select.none", json!({})).unwrap(); let document = app.session.active().unwrap().uid; let swatch = |name: &str, paint: Paint| { - let rows = SwatchRows { document, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + let rows = SwatchRows { + document, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + held: Default::default(), + }; Payload::Panel(PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }) }; let pattern = swatch("Checks", vectorcraft_doc::pattern::pattern_paint("Checks")); @@ -329,7 +336,14 @@ fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() { app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let rows = SwatchRows { + document: source.uid, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: true, + held: Default::default(), + }; let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; let local_target = add_target(&mut app); diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index a91db6681a..f3f4c66234 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -119,7 +119,7 @@ fn corner_target(doc: &Document, id: NodeId, indices: &[usize]) -> Option Option { @@ -132,10 +132,10 @@ fn shown_corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option Option)>> { @@ -143,7 +143,10 @@ pub(super) fn corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Option)> = vec![]; - for ((id, _), index) in shown.visible_on().zip(shown.corners()) { + for ((id, _, picked), index) in shown.visible_on().zip(shown.corners()) { + if !picked { + continue; + } match per_path.last_mut() { Some((last, indices)) if *last == id => indices.push(index), _ => per_path.push((id, vec![index])), @@ -181,6 +184,78 @@ pub(super) fn corner_hover( Some((data_color(st.doc.layer_color(id)), cut)) } +/// The Live Corners widgets of the corners on show that are not picked: with Direct Selection while some corners +/// are picked, every other corner's widget shows too, so a click or a Shift-click on it picks its corner. Each is +/// listed with its place and its object's layer color. +pub(super) fn hollow_corners(app: &VectorcraftApp, tool: &str, zoom: f64) -> Vec<(Point, DataColor)> { + let (Some(shown), Some(st)) = (shown_corners(app, tool, zoom), app.session.active()) else { return vec![] }; + shown.visible_on().filter(|&(_, _, picked)| !picked).map(|(id, at, _)| (doc_point(at), data_color(st.doc.layer_color(id)))).collect() +} + +/// The widgets of [`hollow_corners`]: each a disc in the handle fill ringed in its layer color, the look of the +/// picked corners' widgets without their dot. Display only: the tool takes the presses. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(canvas_control)] +pub struct HollowCorners { + #[common] + common: Common, + widgets: Vec<(Point, DataColor)>, +} + +impl HollowCorners { + fn new(widgets: Vec<(Point, DataColor)>) -> Self { + HollowCorners { common: Common::new(), widgets }.label("Live Corners not picked") + } +} + +/// The style of the hollow corner widgets. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct HollowCornersStyle { + #[style(metrics)] + metrics: Metrics, + /// A widget's diameter: `size.handle.md`, as the picked corners' widgets. + widget: f32, + /// A widget's inside: `overlay.handle_fill`. + fill: StyleColor, +} + +impl Component for HollowCorners { + const ROLE: Role = Role::GRAPHICS_OBJECT; + const INPUT: Input = Input::Display; + const PARTS: bool = false; + const STOPS: bool = false; + const OVERLAYS: bool = false; + type Style = HollowCornersStyle; + type Output = Response; + + fn style(cx: &StyleCx<'_>, _: HollowCornersStyleKey) -> HollowCornersStyle { + HollowCornersStyle { metrics: Metrics::new(), widget: cx.tokens.size.handle.md, fill: cx.color(cx.tokens.color.overlay.handle_fill) } + } + + fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 { + egui::Vec2::ZERO + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let Some(space) = canvas_space(&cx.env) else { return }; + let draw = ui.draw(); + for &(at, color) in &self.widgets { + let ring = PaintShape::Circle(space.view.to_screen(at), cx.style.widget / 2.0); + draw.fill(&ring, cx.style.fill); + draw.stroke(&ring, StrokeWidth::Medium, StrokeColor::Data(color)); + } + } + + fn access(&self, access: &mut Access, _: &Cx<'_, Self>) { + access.description("Live Corners not picked"); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + fn corner_kind(kind: DocCornerKind) -> CornerKind { match kind { DocCornerKind::Round => CornerKind::Round, @@ -469,6 +544,19 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &craft::u } } +/// Shows the widgets of [`hollow_corners`] over the live document, with View › Show Edges on. The canvas shows +/// them before the selection's anchors and handles, so the anchors and handles draw over them. Nothing here is +/// shown while a revolve is edited. +pub(super) fn show_hollow_corners(app: &VectorcraftApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace, kind: BodyKind) { + if kind != BodyKind::Live || super::revolve_editing(app) || !app.ui.view.edges { + return; + } + let widgets = hollow_corners(app, super::shown_tool(app, ui.ctx()), space.view.zoom); + if !widgets.is_empty() { + HollowCorners::new(widgets).show_at(ui, ui.max_rect()); + } +} + /// The box and its eight handles, drawn in the layer colour and answering nothing. fn show_box(ui: &mut egui::Ui, rect: egui::Rect, b: &ShownBox) { let state = BoxState::new(b.obox.corners().map(doc_point), doc_point(b.obox.center())); diff --git a/crates/ui-egui/src/canvas/widgets/tests.rs b/crates/ui-egui/src/canvas/widgets/tests.rs index 68e70867bd..cb3c70c9d5 100644 --- a/crates/ui-egui/src/canvas/widgets/tests.rs +++ b/crates/ui-egui/src/canvas/widgets/tests.rs @@ -309,6 +309,22 @@ fn a_star_shows_corner_widgets_with_direct_selection() { assert_eq!(corner_count(&app), 0); } +/// #1232: with two of a star's corners picked, Direct Selection still shows all ten widgets: the two picked ones +/// with their dot, the other eight hollow in the layer color. With the star selected whole, every widget is picked. +#[test] +fn direct_selection_shows_the_widgets_of_corners_not_picked_hollow() { + let mut app = new_app(&[]); + let id = make(&mut app, "shape.star", json!({"cx": 200, "cy": 150, "radius1": 80, "radius2": 40})); + app.session.execute("select.anchors", &json!({"id": id, "anchors": [[0, 0], [0, 2]], "mode": "set"})).unwrap(); + app.select_tool("directSelection"); + let zoom = app.view_info().zoom; + let hollow = hollow_corners(&app, app.session.tool_id(), zoom); + assert_eq!((corner_count(&app), hollow.len()), (2, 8)); + assert!(hollow.iter().all(|&(_, color)| color == layer(&app, id))); + app.session.execute("select.set", &json!({"ids": [id]})).unwrap(); + assert_eq!((corner_count(&app), hollow_corners(&app, app.session.tool_id(), zoom).len()), (10, 0)); +} + #[test] fn the_type_widget_shows_which_kind_the_type_is() { let mut app = new_app(&[]); diff --git a/crates/ui-egui/src/dialogs/corners.rs b/crates/ui-egui/src/dialogs/corners.rs index 1f330a64b6..29b5962d3e 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"), `radii` @@ -253,12 +254,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); assert!(is_open(&app), "Corners opened"); diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 6eab0d5404..a3acab8b0b 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -194,11 +194,12 @@ impl Rows<'_> { self.range(key, label, range, 1, UnitKind::Percent) } - /// A length in points, shown in the general unit. + /// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says. fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param { // Stored in points; a pixel is a point, as the rulers count it. let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0); - self.range(key, label, range, 1, UnitKind::Pixels).length(crate::fields::bare_points(lengths, self.bare_points)) + let shown = super::three_d_classic::length_unit(self.unit); + self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points)) } fn flag(&self, key: &str, label: &'static str) -> Param { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 6b73aed5f9..ceb96018f7 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -494,6 +494,41 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); } +/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their +/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit. +#[test] +fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { + use craft::ui::patterns::form_dialogs::DialogFields; + use craft::ui::runtime::env::UnitKind; + use vectorcraft_doc::Unit; + let app = VectorcraftApp::new(Session::new(), crate::Services::default()); + let unit = |general: Unit, effect: &str, page: &str, key: &str| { + let mut data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new()); + data.unit = general; + let mut fields = DialogFields::new(); + fields.set("__page", FieldValue::Text(page.into())); + super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) + }; + let mut checked = 0; + for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] { + for key in ["depth", "bevelWidth", "bevelHeight"] { + assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}"); + checked += 1; + } + let others = [ + (REVOLVE, "rotation", "offset"), + (CLASSIC_EXTRUDE, "object", "depth"), + (CLASSIC_EXTRUDE, "object", "bevelHeight"), + (CLASSIC_REVOLVE, "object", "offset"), + ]; + for (effect, page, key) in others { + assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}"); + checked += 1; + } + } + assert_eq!(checked, 21); +} + #[test] fn reset_all_keeps_map_art_and_its_options() { let mut h = drawn(SQUARE, CLASSIC_EXTRUDE); diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 8c9f26bb1e..f461b3cfe2 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -50,9 +50,13 @@ const MAP_SYMBOL: &str = "mapSymbol"; /// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters. pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]]; -/// The unit of the general-unit length rows. -fn length_unit(unit: Unit) -> UnitKind { - crate::canvas::rulers::unit_kind(unit) +/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when +/// that counts the same number (points, or pixels at 72 per inch), and points otherwise. +pub(super) fn length_unit(unit: Unit) -> UnitKind { + match crate::canvas::rulers::unit_kind(unit) { + UnitKind::Pixels => UnitKind::Pixels, + _ => UnitKind::Points, + } } /// Where the rows show: the 3D and Materials panel marks its fields with `__panel`. diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs index 2db0261f2b..86772bd201 100644 --- a/crates/ui-egui/src/dialogs/tracing_presets.rs +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -164,8 +164,10 @@ impl StackDialog for Manager { // PLAN: the rows components take no `enabled` prop; the scope's `Ui` is disabled for them. ui.scope(|ui| { ui.disable(); - rows::main_rows(ui, &mut params, data, RowsHost::Dialog); - rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None); + rows::settings_group(ui, |ui| { + rows::main_rows(ui, &mut params, data, RowsHost::Dialog); + rows::advanced_rows(ui, &mut params, data, RowsHost::Dialog, None); + }); }); if builtin { Text::new(tl!("Built-in presets don't change: New makes a copy you can edit.")) @@ -472,9 +474,11 @@ fn build(data: Arc) -> impl for<'b> Fn(&'b mut DialogFields) -> ParamD _ => json!({}), }; let shown = ui.scope(|ui| { - let main = rows::main_rows(ui, &mut params, &data, RowsHost::Dialog); - let advanced = rows::advanced_rows(ui, &mut params, &data, RowsHost::Dialog, None); - main.changed || advanced.changed + rows::settings_group(ui, |ui| { + let main = rows::main_rows(ui, &mut params, &data, RowsHost::Dialog); + let advanced = rows::advanced_rows(ui, &mut params, &data, RowsHost::Dialog, None); + main.changed || advanced.changed + }) }); if shown.inner { fields.set("params", FieldValue::Json(params)); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index f85c44afa0..6150887205 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1752,6 +1752,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 73db292645..1e846faf46 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2121,6 +2121,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 c451ec9811..e2c38092d1 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2155,6 +2155,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 d2a89194fa..31030654e3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2193,6 +2193,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 70c167b084..e9da516794 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4860,6 +4860,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 e2ce6c9202..36a98df5f8 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1679,6 +1679,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 51b04c5526..126ed5a57e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1598,6 +1598,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 053e35e721..f26d178b5e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1688,6 +1688,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 05c77549a0..05792769f9 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2152,6 +2152,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 8f843cc11f..85c2e3e977 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1678,6 +1678,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 9bceb93b20..78410c0573 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1742,6 +1742,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 3bc5aaf219..1a8ad42007 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2629,6 +2629,7 @@ arrowhead Feather पंख 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 fedcfcf62b..9673b9779b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2082,6 +2082,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 3c434256fa..52815fe174 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2736,6 +2736,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 13d0656137..d980fb9bc8 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1716,6 +1716,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 97606b7e76..c8419ff162 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4457,6 +4457,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 a8d2240536..f5e48eb141 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4135,6 +4135,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 96e84b418e..9329b98a3e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4447,6 +4447,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 fada1fc205..5571004089 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2721,6 +2721,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 01d3571047..d17e80a23a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2109,6 +2109,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 e3dd5ffeda..5830595a41 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4139,6 +4139,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 a2235998eb..96badacf8d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1701,6 +1701,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 41bda9072e..ca968fc94e 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1635,6 +1635,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 0ee286faa1..c7ab4d49b9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1599,6 +1599,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 e9dd432e72..007055151c 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1710,6 +1710,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 8e9d5cac87..0f4220e58a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1944,6 +1944,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 a7e94e826f..a347bd1d33 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1644,6 +1644,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 3a86a5b728..05f45ecb68 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1680,6 +1680,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/menus/model.rs b/crates/ui-egui/src/menus/model.rs index f00174b4ac..9699991cc6 100644 --- a/crates/ui-egui/src/menus/model.rs +++ b/crates/ui-egui/src/menus/model.rs @@ -44,6 +44,8 @@ pub(crate) struct Menus { /// The states of the catalogued commands and of every menu item's reference. pub(crate) states: Tracked, catalog: Option, + /// The rows `catalog` was made from, kept while what they are made from stays the same. + rows: Option, } impl Menus { @@ -245,26 +247,35 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { .collect(); let Build { mut states, refs, .. } = build; - let defs = catalog_defs(app, &refs, &mut states); + // The catalog is built again only when what its rows are made from changed; edits and selection changes change + // the rows' states alone. + let inputs = CatalogInputs { + snapshot: crate::shortcut_editor::snapshot(), + platform: crate::keymap::platform(), + plays: crate::panels::actions::function_keys(&app.ui.actions), + refs, + overrides: app.shortcut_overrides.clone(), + generation: generation(&listed, &[], &[]), + }; + let rows = match app.menus.rows.take().filter(|rows| rows.accepted && rows.inputs == inputs) { + Some(rows) => rows, + None => { + let (defs, known) = catalog_defs(&inputs); + let catalog = build_catalog(app, &listed, &inputs.plays, defs.clone()); + let accepted = catalog.is_some(); + if catalog.is_some() { + app.menus.catalog = catalog; + } + CatalogRows { inputs, defs, known, accepted } + } + }; + row_states(app, &rows, &mut states); crate::panels::panel_menu_states(app, &mut states); let bar = MenuBar::new(menus); let options = LayoutOptions::new(APP_NAME).label(&translate_label); let laid = layout(&bar, target, &options).bar; - let type_keys = crate::type_editing::app_keys(&defs, &app.shortcut_overrides); - let (defs, linked_keys) = without_linked(defs); - match AppCatalog::new(defs, generation(&listed, &crate::panels::actions::function_keys(&app.ui.actions), &type_keys)) { - Ok(catalog) => { - // While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it, - // and the Type tool's commands run while it types. - let catalog = catalog.typing_rule(TypingRule::AllWait); - let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)); - let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new())); - app.menus.catalog = Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys))); - } - // A refused catalog is a bug in the rows; the last good one keeps the commands working. - Err(e) => eprintln!("menu catalog refused: {e:?}"), - } + app.menus.rows = Some(rows); app.menus.bar = bar; if *app.menus.laid != laid { app.menus.laid.edit(|l| *l = laid); @@ -272,28 +283,63 @@ fn rebuild(app: &mut VectorcraftApp, target: Target) { app.menus.states.edit(|s| *s = states); } +/// What the catalog's rows are made from: the editor's entries, the platform, the actions' function keys, the menu +/// references with their labels, the user's shortcuts, and the language, plug-ins, scripts, fonts and listed names. +struct CatalogInputs { + snapshot: std::sync::Arc, + platform: craft::keymap::Platform, + plays: Vec<(String, craft::keymap::Chord)>, + refs: Vec<(CommandRef, String, bool)>, + overrides: std::sync::Arc, + generation: u64, +} + +impl PartialEq for CatalogInputs { + fn eq(&self, other: &Self) -> bool { + std::sync::Arc::ptr_eq(&self.snapshot, &other.snapshot) + && std::sync::Arc::ptr_eq(&self.overrides, &other.overrides) + && (self.platform, self.generation) == (other.platform, other.generation) + && self.plays == other.plays + && self.refs == other.refs + } +} + +/// The catalog's rows as the last rebuild made them from `inputs`, the keys of those rows, and whether the catalog +/// took them (a refused set is made again on the next rebuild). +struct CatalogRows { + inputs: CatalogInputs, + defs: Vec, + known: HashSet, + accepted: bool, +} + +#[cfg(test)] +thread_local! { + /// How many times this thread made the catalog's rows. + pub(crate) static CATALOG_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// The catalog's rows: the keymap's, with icons, then a row for every menu reference the keymap -/// does not name (by its key or its bare id), and the state of every row not set by the tree. +/// does not name (by its key or its bare id), with the keys of every row. // PLAN: the Shift+Space row for MomentaryCommands::RotateView (S-CV8) is the canvas area's: that // command is not in the app scope, which `AppCatalog` accepts. // PLAN: ActionsPanelCommands' defs (area plan X6) are menus-w18's; their signature is not visible here. -fn catalog_defs(app: &VectorcraftApp, refs: &[(CommandRef, String, bool)], states: &mut CommandStates) -> Vec { - let snapshot = crate::shortcut_editor::snapshot(); +fn catalog_defs(inputs: &CatalogInputs) -> (Vec, HashSet) { + #[cfg(test)] + CATALOG_BUILDS.set(CATALOG_BUILDS.get() + 1); // An action's function key comes first: it takes priority over the command shortcuts. - let plays = crate::panels::actions::function_keys(&app.ui.actions).into_iter().map(|(name, chord)| { + let plays = inputs.plays.iter().map(|(name, chord)| { let play = CommandRef::with_params(crate::panels::actions::PLAY_ACTION, json!({ "action": name })); - CommandDef::new(play, name, Scope::app()).with_default(Binding::new(chord)) + CommandDef::new(play, name.clone(), Scope::app()).with_default(Binding::new(*chord)) }); let mut defs: Vec = plays - .chain(crate::keymap::catalog_defs(crate::keymap::platform(), &snapshot).into_iter().map(|d| { - match crate::panels::command_icon(&d.command.id) { - Some(icon) => d.with_icon(icon), - None => d, - } + .chain(crate::keymap::catalog_defs(inputs.platform, &inputs.snapshot).into_iter().map(|d| match crate::panels::command_icon(&d.command.id) { + Some(icon) => d.with_icon(icon), + None => d, })) .collect(); let mut known: HashSet = defs.iter().map(|d| d.command.key()).collect(); - for (command, label, checkable) in refs { + for (command, label, checkable) in &inputs.refs { if known.contains(&command.key()) || known.contains(&command.id) { continue; } @@ -301,20 +347,46 @@ fn catalog_defs(app: &VectorcraftApp, refs: &[(CommandRef, String, bool)], state let def = CommandDef::new(command.clone(), label.clone(), Scope::app()); defs.push(if *checkable { def.toggle() } else { def }); } - for d in &defs { + (defs, known) +} + +/// The catalog made from `defs`, or `None` when it refuses them. +fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft::keymap::Chord)], defs: Vec) -> Option { + let type_keys = crate::type_editing::app_keys(&defs, &app.shortcut_overrides); + let (defs, linked_keys) = without_linked(defs); + match AppCatalog::new(defs, generation(listed, plays, &type_keys)) { + Ok(catalog) => { + // While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it, + // and the Type tool's commands run while it types. + let catalog = catalog.typing_rule(TypingRule::AllWait); + let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)); + let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new())); + Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys))) + } + // A refused catalog is a bug in the rows; the last good one keeps the commands working. + Err(e) => { + eprintln!("menu catalog refused: {e:?}"); + None + } + } +} + +/// The state of every catalog row the tree did not set, and of the engine commands the palette lists that no row +/// names. +fn row_states(app: &VectorcraftApp, rows: &CatalogRows, states: &mut CommandStates) { + for d in &rows.defs { if states.get(&d.command).is_none() { states.set(d.command.clone(), row_state(app, &d.command, &d.label)); } } // The engine commands the palette lists and no row names (Asset Export's Remove and Rename) are dimmed there and say // why, as the rows are. - for c in crate::palette::listed_engine_commands().filter(|c| !known.contains(c.id)) { + for c in crate::palette::listed_engine_commands().filter(|c| !rows.known.contains(c.id)) { let command = CommandRef::new(c.id); if states.get(&command).is_none() { states.set(command.clone(), row_state(app, &command, c.label)); } } - defs } /// `defs` without the commands a linked framework set defines (Undo, Redo, Cut, Copy, Paste and Tab's panels toggles): @@ -506,3 +578,44 @@ impl Build<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn app_with_document() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let ctx = crate::testing::ui_context(); + refresh(&mut app, &ctx); + (app, ctx) + } + + /// Edits and selection changes give the rows new states and leave the catalog's rows as they were made. + #[test] + fn edits_and_selection_changes_keep_the_catalog_rows() { + let (mut app, ctx) = app_with_document(); + // The plug-ins, fonts and scripts are the process's, which tests on other threads change, and a row the menus + // leave out while it is off comes back with the art: a rebuild that made the rows while those moved is not counted. + let shared = |app: &VectorcraftApp| { + app.menus.rows.as_ref().map(|r| (std::sync::Arc::as_ptr(&r.inputs.snapshot).addr(), r.inputs.generation, r.inputs.refs.clone())) + }; + let mut remade = 0; + let mut step = |app: &mut VectorcraftApp, id: &str, params: Value| { + app.run(id, params).unwrap(); + let (builds, before) = (CATALOG_BUILDS.get(), shared(app)); + refresh(app, &ctx); + if CATALOG_BUILDS.get() > builds && shared(app) == before { + remade += 1; + } + }; + for k in 0..5 { + step(&mut app, "shape.rectangle", json!({"x": k * 20, "y": 0, "width": 10, "height": 10})); + step(&mut app, "select.none", json!({})); + } + step(&mut app, "select.all", json!({})); + assert_eq!(remade, 0, "11 rebuilds after edits and selection changes made the catalog's rows again"); + assert!(app.menus.states.get(&CommandRef::new("edit.undo")).is_some_and(CommandState::is_enabled), "the states follow the edits"); + assert!(app.menus.states.get(&CommandRef::new("object.group")).is_some_and(CommandState::is_enabled)); + } +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 6b0aac8b1f..ada6e2d516 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1616,7 +1616,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, opacity?: bool, hexField?: bool, 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 at or below the one asked for; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; 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 active document's RGB space (its assigned profile, else 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, opacity, hexField, 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, opacity?: bool, hexField?: bool, 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 Opacity, 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 at or below the one asked for; 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; 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 active document's RGB space (its assigned profile, else 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, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panel_drag.rs b/crates/ui-egui/src/panel_drag.rs index 587da09f84..56cdff25ac 100644 --- a/crates/ui-egui/src/panel_drag.rs +++ b/crates/ui-egui/src/panel_drag.rs @@ -52,6 +52,9 @@ pub struct SwatchRows { pub groups: bool, /// Whether the grabbed swatch's paint can travel as an unlinked process color. pub unlinked_process_color: bool, + /// The rows as the document held them when the drag started, which New Swatch and Delete + /// Swatch check before acting on them. + pub(crate) held: std::sync::Arc, } impl PanelDrag { diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index ced30aad17..42528b3faf 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -1136,7 +1136,14 @@ mod tests { app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true }; + let rows = SwatchRows { + document: source.uid, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: true, + held: Default::default(), + }; let drag = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None }; app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap(); drop_paint(&mut app, Well::Primary, &drag); @@ -1164,8 +1171,14 @@ mod tests { app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap(); let source = app.session.active().unwrap(); let paint = source.doc.swatch(name).unwrap().paint.clone(); - let rows = - SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: false }; + let rows = SwatchRows { + document: source.uid, + grabbed: name.into(), + names: vec![name.into()], + groups: false, + unlinked_process_color: false, + held: Default::default(), + }; let drag = PanelDrag::Paint { paint, params: json!({"swatch": name}), rows: Some(rows), library: None }; if different_drawing { app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); @@ -1227,6 +1240,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_color_wheel_copy; #[cfg(test)] mod tests_color_wheel_document_colors; diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index c44c6dc8ba..8694052a3a 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -58,7 +58,7 @@ pub use playback::{ deserialize_playback, play, play_action, play_at, playback_drawn, playback_held, playback_options, playback_shown, tick_playback, waiting_at_stop, }; -pub(crate) use playback::{KnownCommands, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands}; +pub(crate) use playback::{KnownCommands, add_script_actions, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands}; pub use recording::{START_RECORDING, STOP_RECORDING, record, stop}; pub(crate) use recording::{after_journaled_edit, after_recorded_command, before_recorded_command}; diff --git a/crates/ui-egui/src/panels/actions/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index 50cab383e2..bff0bd1d4d 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec { .collect() } +/// For command `id` `script.run`, or the script of `script.startup.run`'s `then`: gives its +/// `params` the panel's actions as `actions`, which the script's `app.doScript` plays, unless the +/// caller gave them: every action of every set, in panel order, with its steps as playback runs +/// them ([`playback_steps`]) and each step's place in the action. An action that `actions` cannot +/// hold (a step that is not a command, a name that is too long, or one past the limits of +/// [`vectorcraft_engine::script::actions`]) is left out. +pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { + use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, Playable, parse}; + let target = match id { + "script.run" => Some(params), + "script.startup.run" => params.get_mut("then"), + _ => None, + }; + let Some(p) = target.and_then(Value::as_object_mut) else { return }; + if p.contains_key("actions") { + return; + } + let list = &app.ui.actions; + let (mut held, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); + for set in list.sets() { + for a in model::members(list, set).into_iter().filter_map(|i| list.action(i)) { + if held.len() >= MAX_ACTIONS { + break; + } + // The commands of a recorded `command.batch` step go back into one batch step, so that an + // error names a failing command by the batch's place and its own (`3.2`). + let mut played: Vec = Vec::new(); + for s in playback_steps(a) { + let params = match s.command.get("params") { + None | Some(Value::Null) => json!({}), + Some(p) => p.clone(), + }; + let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params}); + let place = s.row + 1; + if a.steps.get(s.row).is_none_or(|step| step.command != "command.batch") { + let mut one = one; + one["step"] = json!(place); + played.push(one); + continue; + } + match played.last_mut() { + Some(last) if last["command"] == "command.batch" && last["step"] == place => { + if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") { + inner.push(one); + } + } + _ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})), + } + } + let one = Value::Array(vec![json!({"set": set, "name": a.name, "steps": played})]); + let Ok(parsed) = parse(Some(&one)) else { continue }; + let count = parsed.first().map_or(0, Playable::len); + let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len()); + if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES { + continue; + } + steps += count; + bytes += size; + if let Value::Array(mut one) = one { + held.append(&mut one); + } + } + } + p.insert("actions".into(), Value::Array(held)); +} + /// The steps of `action` whose command `known` does not hold, in order, as (step index, the index /// of the command in a `command.batch` step, command id). A `command.batch` step's own commands are /// checked one by one, as playback runs them ([`included_commands`]); a command of one with no diff --git a/crates/ui-egui/src/panels/actions/tests_playback.rs b/crates/ui-egui/src/panels/actions/tests_playback.rs index b6db1c5941..f566eb22fc 100644 --- a/crates/ui-egui/src/panels/actions/tests_playback.rs +++ b/crates/ui-egui/src/panels/actions/tests_playback.rs @@ -637,6 +637,79 @@ fn an_error_counts_excluded_steps() { assert_eq!(x(&app), 0.0, "the failing batch changes nothing"); } +/// A script's `app.doScript` plays the panel's actions with their included steps; an action whose +/// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept. +#[test] +fn a_script_plays_the_panels_actions() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let rect = |x: i64| ("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10})); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let batch = json!({"commands": [{"command": "select.none"}, bad]}); + let actions = vec![ + action("Draw", &[rect(0), rect(20), rect(40)]), + action("Odd", &[rect(0), ("select.none", json!(5))]), + action("Batched", &[("select.none", json!({})), ("command.batch", batch)]), + ]; + push_set(&mut app, "Mine", actions); + let draw = model::members(&app.ui.actions, "Mine")[0]; + app.ui.actions.set_step(draw, 1, false).unwrap(); + let objects = + |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::()); + let undo = app.session.active().map_or(0, |d| d.history.undo.len()); + app.session.script_frames = false; + let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"])); + assert_eq!(objects(&app), 2, "the excluded step does not run"); + assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1); + // A failing command of a recorded batch is named by the batch's place and its own. + let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + let m = r["log"][0].as_str().unwrap_or_default(); + assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}"); + let r = + app.run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})).unwrap(); + assert_eq!(r["log"], json!(["there is no action set “Mine”"])); + assert_eq!(objects(&app), 2); +} + +/// The script that `script.startup.run` runs after the startup scripts (its `then`) plays the +/// panel's actions too, as File › Scripts runs a script with Run Startup Scripts on. +#[test] +fn the_script_after_the_startup_scripts_plays_the_panels_actions() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + push_set(&mut app, "Mine", vec![action("Draw", &[("shape.rectangle", json!({"x": 0, "y": 10, "width": 10, "height": 10}))])]); + app.session.script_frames = false; + let then = json!({"source": "try { app.doScript('Draw', 'Mine'); vc.log('ok'); } catch (e) { vc.log(e.message); }", "name": "t.js"}); + let r = app.run("script.startup.run", json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!(r["then"]["log"], json!(["ok"]), "{r}"); +} + +/// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's +/// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. +#[test] +fn a_script_plays_the_actions_on_the_active_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let batch = json!({"commands": [align]}); + push_set(&mut app, "Mine", vec![action("Align", &[("command.batch", batch)]), action("Fit", &[("artboard.fitToSelection", json!({}))])]); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&app); + app.view_mut().unwrap().artboard = 1; + app.session.script_frames = false; + let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');"; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one"); + assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1"); +} + /// A step of a recorded `command.batch` that fails is named by the batch's place in the action /// and its own command. #[test] diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 3d95d2c28d..ad1c544b5a 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -22,7 +22,7 @@ use std::sync::{Arc, OnceLock}; use craft::behavior::overlay::{Align, Side}; use craft::behavior::{ColumnKey, ColumnWidth, CopyKeys, DisplayOrder, EditEvent, IconId, ItemSource, Selection}; -use craft::theme::Srgba; +use craft::theme::{ControlSize, Srgba}; use craft::ui::buttons::{Button, ButtonOutput}; use craft::ui::choice::{Swatch, SwatchOutput}; use craft::ui::contract::overlay::{Anchor, Place}; @@ -876,7 +876,8 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> { } /// The well of a fill (`fill`) or stroke row, named for it: `paint` as its face, its colour (a solid paint's) as its -/// value. +/// value. The well is a small control, so it stands inside its control-high row and the wells of neighboring rows do +/// not touch. fn paint_swatch(fill: bool, paint: &Paint) -> Swatch { let color = paint.color().map_or(Srgba::BLACK, |c| { let [r, g, b] = c.to_rgb(); @@ -885,6 +886,7 @@ fn paint_swatch(fill: bool, paint: &Paint) -> Swatch { let row = if fill { tl!("Fill") } else { tl!("Stroke") }; Swatch::new(crate::i18n::fmt(tl!("{row} swatch"), &[("row", row)]), color) .face(paint_preview::rect_face(paint)) + .size(ControlSize::Sm) .tooltip(tl!("Click to choose a swatch, Shift-click to mix a colour")) } diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index f630dff16e..3e706b06c1 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -38,6 +38,9 @@ //! () 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`. //! //! Panel menu › Show Color Vision Preview adds a row under the wheel or the box with the color as //! simulated for protanopia, deuteranopia and tritanopia, through the simulations View › Proof @@ -66,6 +69,7 @@ //! Hex with Alpha, CSS rgb(), CSS hsl(), CSS oklch() or CMYK Values. Its items are gray without a //! solid color, and CSS oklch() also while the active document's RGB space is not sRGB. +use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Arc; @@ -78,7 +82,7 @@ use craft::color_ui::AreaMode; use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorArea, ColorStrip, ColorWheel, WheelInner}; use craft::keymap::CommandRef; use craft::theme::{ColorModel, HsbModel, ModelValues, RgbModel, Srgba}; -use craft::ui::choice::{Swatch, SwatchSpacing, SwatchTable}; +use craft::ui::choice::{SwatchSpacing, SwatchTable}; use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _, Sizing}; use craft::ui::display::{Shade, Text}; use craft::ui::layout::CellAlign; @@ -87,7 +91,7 @@ use craft::ui::menu::PanelRow; use craft::ui::runtime::commands::{CommandState, CommandStates}; use craft::ui::runtime::env::Label; use craft::ui::text::TextField; -use egui::Ui; +use egui::{Color32, Rect, Stroke, Ui}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget}; @@ -96,10 +100,11 @@ 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, contrast_pick_backdrop}; // PLAN: assumed `crate::edits::{apply_edits, EditPath}` (wg.A16, widgets-w13) and `crate::panels::Live` (co.A2, hub-w2). use super::color::{Target, apply, gamut, target_now, wheel_target}; -use super::{Live, alt_held}; +use super::{Live, alt_held, color_json}; use crate::VectorcraftApp; use crate::edits::{EditPath, apply_edits}; @@ -432,28 +437,24 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S if let Some(on) = crate::menus::opt_bool(p, "hexField")? { set.hex_field = on; } - match p.get("contrast") { + if let Some(on) = crate::menus::opt_bool(p, "contrast")? { + set.contrast = on; + } + let key = "contrastFor"; + match p.get(key) { None | Some(Value::Null) => {} Some(v) => { - let key = "contrast"; - set.contrast = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; + set.contrast_for = v.as_str().and_then(Category::parse).ok_or_else(|| { + let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect(); + format!("`{key}` must be one of {}", ids.join(", ")) + })? } } - match p.get("contrastFor") { - None | Some(Value::Null) => {} - Some(v) => { - let key = "contrastFor"; - let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect(); - set.contrast_for = v.as_str().and_then(Category::parse).ok_or_else(|| format!("`{key}` must be one of {}", ids.join(", ")))?; - } - } - match p.get("contrastBackground") { + let key = "contrastBackground"; + match p.get(key) { None => {} Some(Value::Null) => set.contrast_background = None, - Some(v) => { - let key = "contrastBackground"; - set.contrast_background = Some(background_value(v).ok_or_else(|| format!("`{key}` must be a color or {}", "null"))?); - } + Some(v) => set.contrast_background = Some(background_value(v).ok_or_else(|| format!("`{key}` must be a color or {}", "null"))?), } if let Some(on) = crate::menus::opt_bool(p, "vision")? { set.vision = on; @@ -499,8 +500,8 @@ pub(super) fn category_name(c: Category) -> &'static str { } /// Every row of the panel menu with its state for `set`, `srgb` telling whether the active -/// document's RGB space is sRGB and `current` the color the panel edits, which Contrast Background -/// › Current Color pins. +/// document's RGB space is sRGB and `current` the color the panel edits, which Contrast +/// Background › Current Color pins. fn items(set: &Settings, srgb: bool, current: Option) -> Vec { let item = |id: String, label: &str, checked: bool, enabled: bool, params: Value| Item { id, @@ -543,10 +544,20 @@ fn items(set: &Settings, srgb: bool, current: Option) -> Vec { for c in Category::ALL { out.push(item(category_row_id(c), category_name(c), set.contrast_for == c, true, json!({ "contrastFor": c.id() }))); } - let pinned = set.contrast_background.is_some(); - out.push(item("contrastBackground.below".into(), tl!("Behind Selection"), !pinned, true, json!({ "contrastBackground": null }))); - let params = current.map_or(Value::Null, |c| json!({ "contrastBackground": crate::panels::color_json(&c) })); - out.push(item("contrastBackground.current".into(), tl!("Current Color"), pinned, current.is_some(), params)); + out.push(item( + "contrastBackground.below".into(), + tl!("Behind Selection"), + set.contrast_background.is_none(), + true, + json!({ "contrastBackground": null }), + )); + out.push(item( + "contrastBackground.current".into(), + tl!("Current Color"), + set.contrast_background.is_some(), + current.is_some(), + json!({ "contrastBackground": current.as_ref().map(color_json) }), + )); out.push(item("vision".into(), tl!("Show Color Vision Preview"), set.vision, true, json!({ "vision": !set.vision }))); out.push(item( "documentColors".into(), @@ -592,7 +603,7 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { )); rows.push(PanelRow::Submenu( Label::from(tl!("Contrast Background").to_string()), - ["contrastBackground.below", "contrastBackground.current"].into_iter().map(|row| command(row.into())).collect(), + vec![command("contrastBackground.below".into()), command("contrastBackground.current".into())], )); rows.extend(["vision", "documentColors"].map(|row| command(row.into()))); rows.push(PanelRow::Separator); @@ -603,16 +614,11 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec { rows } -/// The menu rows of `app`'s settings, with the color the panel edits for Current Color. -fn app_items(app: &VectorcraftApp) -> Vec { - items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), super::color::target_now(app).color()) -} - /// The labels, checks and enabled states of [`menu_rows`]. The items of Copy Color As are gray /// without a solid color, and CSS oklch() also while the active document's RGB space is not sRGB. pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) { let srgb = cms::active().rgb_is_srgb(); - for item in app_items(app) { + for item in items(&app.ui.color_wheel, srgb, target_now(app).color()) { let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked); if let Some(hint) = item.hint { state = state.hint(hint); @@ -640,7 +646,7 @@ pub(crate) fn copy_color_as(app: &mut VectorcraftApp, notation: &str) -> Result< let tgt = target_now(app); let Some(color) = tgt.color() else { return Ok(Value::Null) }; let (o, live) = shown_opacity(app, &tgt); - let mut p = json!({ "color": super::color_json(&color), "notation": notation }); + 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); } @@ -666,10 +672,11 @@ pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option let (notation, _) = copy_notations().into_iter().find(|(n, _)| *n == notation)?; return Some(copy_color_as(app, notation)); } - if row == "contrastBackground.current" && super::color::target_now(app).color().is_none() { + let current = target_now(app).color(); + if row == "contrastBackground.current" && current.is_none() { return Some(Err("Current Color needs a solid color in the active proxy".to_string())); } - let params = app_items(app).into_iter().find(|item| item.id == row)?.params; + let params = items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), current).into_iter().find(|item| item.id == row)?.params; Some(command(app, ¶ms)) } @@ -739,10 +746,14 @@ pub struct WheelUi { rows_live: Option, /// Whether a drag of the Show Opacity row previews on an open interaction, until it is released. opacity_live: bool, - /// The color behind the selection, as `#rrggbb`, with the [`BehindKey`] it was read for. + /// The color behind the selection as `#rrggbb`, with the [`BehindKey`] it was read for. pub(super) behind: Option<(BehindKey, Option)>, /// The contrast row's `color.contrast` answer, with the [`RatioKey`] it was asked for. pub(super) ratio: Option<(RatioKey, Option)>, + /// What the contrast row's answer was measured against, with the [`RatioKey`] it was asked for. + backdrop: Option<(RatioKey, Option)>, + /// The contrast lines of the square or the field, with the [`LinesKey`] they were found for. + pub(super) lines: Option<(LinesKey, Lines)>, } /// The colors the row shows and whether they are the selection's, read with `color.used` once per @@ -876,6 +887,27 @@ fn picked_hsb(v: &ModelValues, shown: [f32; 3]) -> [f32; 3] { if hsb[1] <= 0.0 || hsb[2] <= 0.0 { [shown[0], hsb[1], hsb[2]] } else { hsb } } +/// The HSB the field of channel `ch`'s box picks at field point (`x`, `y`) (0 to 1 each, across from +/// the left and down from the top) around HSB `shown`, as the widget's field maps a point to its two +/// components. The wheel's square is the field of [`Channel::Hue`]. +pub(super) fn field_pick(ch: Channel, x: f32, y: f32, shown: [f32; 3]) -> [f32; 3] { + let mode = area_mode(ch); + let channels = mode.model().channels(); + let mut v = box_values(ch, shown); + for (c, t) in mode.area().into_iter().zip([x, 1.0 - y]) { + if let (Some(range), Some(value)) = (channels.get(c), v.values.get_mut(c)) { + *value = range.min + (range.max - range.min) * t.clamp(0.0, 1.0); + } + } + picked_hsb(&v, shown) +} + +/// The component the field of channel `ch`'s box holds fixed around HSB `shown`: the strip's value. +pub(super) fn field_fixed(ch: Channel, shown: [f32; 3]) -> f32 { + let mode = area_mode(ch); + box_values(ch, shown).values.get(mode.strip()).copied().unwrap_or(0.0) +} + /// The widgets' color of display sRGB `rgb`. fn srgb([r, g, b]: [f32; 3]) -> Srgba { Srgba::rgb(r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0)) @@ -955,6 +987,256 @@ pub(super) struct RatioKey { pub(super) mesh_points: Vec<(NodeId, Vec)>, /// Whether the Live Paint Bucket paints, which gives the proxies its paints without a revision. pub(super) bucket: bool, + /// The Contrast For category, which the closest passing colors are for. + pub(super) category: Category, +} + +/// 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, 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; + +/// 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)>; + +/// 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 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. 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; + // `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![]; + // 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) }; + 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(); + // 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]); + } + } + } + } + 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`. 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, panel: &mut WheelUi, backdrop: &Backdrop, cx: &Pick) -> Lines { + let set = &app.ui.color_wheel; + let (category, view) = (set.contrast_for, set.view); + // The wheel's square is the field of the hue box. + let ch = if view == View::Box { set.channel } else { Channel::Hue }; + let was = replaced(app, cx.tgt, false); + let hsb = cx.shown; + let field = format!("{view:?} {ch:?} {} {:?} {}", field_fixed(ch, hsb), was.map(|c| c.model()), cx.cmyk_doc); + let dragging = app.session.in_interaction(); + let key = |coarse: bool| -> LinesKey { (backdrop.clone(), category, field.clone(), under(), coarse) }; + if let Some((k, lines)) = &panel.lines + && (*k == key(false) || (dragging && *k == key(true))) + { + return lines.clone(); + } + let ratio_at = |x: f32, y: f32| backdrop.ratio(backdrop.shown(cx.cms, &stored(cx.cms, field_pick(ch, x, y, hsb), was.as_ref(), cx.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 }; + let lines = contrast_lines(&ratio_at, &minimums, samples, !dragging); + panel.lines = Some((key(dragging), 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 @@ -993,9 +1275,19 @@ fn background(app: &mut VectorcraftApp, panel: &mut WheelUi) -> Option { Color::from_hex(&hex?) } -/// The `color.contrast` answer against `pinned`, else against the color behind the selection -/// (`against: "below"`), kept per [`RatioKey`]. -fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option) -> Option { +/// The contrast row's measurement: `color.contrast`'s answer for the chosen category, and what the +/// lines measure picks against. +struct Measured { + answer: Option, + backdrop: Option, +} + +/// The `color.contrast` answer for the chosen category against the pinned background, else +/// against the color behind the selection (`against: "below"`), with what it measured the color +/// against, kept per [`RatioKey`]. +fn measure(app: &VectorcraftApp, panel: &mut WheelUi) -> Measured { + let category = app.ui.color_wheel.contrast_for; + let pinned = app.ui.color_wheel.contrast_background; let st = app.session.active(); let key = RatioKey { background: pinned.map_or_else(|| "below".to_string(), |bg| format!("{bg:?}")), @@ -1011,33 +1303,43 @@ fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option r.clone(), + match (&panel.ratio, &panel.backdrop) { + (Some((k, answer)), Some((kb, backdrop))) if *k == key && *kb == key => Measured { answer: answer.clone(), backdrop: backdrop.clone() }, _ => { - let against = pinned.as_ref().map_or_else(|| json!("below"), crate::panels::color_json); - let r = app.session.execute("color.contrast", &json!({ "against": against })).ok(); - panel.ratio = Some((key, r.clone())); - r + let against = pinned.as_ref().map_or_else(|| json!("below"), color_json); + 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()), + }; + panel.ratio = Some((key.clone(), answer.clone())); + panel.backdrop = Some((key, backdrop.clone())); + Measured { answer, backdrop } } } } -/// 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. Only when there is no -/// answer is the background read on its own ([`background`]), so the chip still shows it. The chip -/// is a color well named Background whose value is the background's hex value, as the color vision -/// chips are; a click on it does nothing. -fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms) { +/// 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, when `color.contrast` finds one for that level; 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 first chip shows the background the answer +/// measured against, pinned or not, else the one a pick would be measured against (a pinned 100 % +/// K shows as black with a rich black Appearance of Black). Only when there is neither is the +/// background read on its own ([`background`]), so the chip still shows it. The chip is named +/// Background, with the background's hex value as its value, as the color vision chips are. +/// Returns the fix color when its chip is clicked or activated. +fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms, m: &Measured) -> Option { let category = app.ui.color_wheel.contrast_for; let pinned = app.ui.color_wheel.contrast_background; - let answer = ratio_answer(app, panel, pinned); - // The background the ratio was measured against. - let measured = answer.as_ref().filter(|_| pinned.is_none()).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); - let chip = match pinned.or(measured) { + let answer = m.answer.as_ref(); + 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, panel), }; @@ -1049,22 +1351,55 @@ fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: tip.push(' '); tip.push_str(tl!("The background is read at the center of the selection.")); } - let ratio = answer.as_ref().and_then(|r| r["ratio"].as_f64()); - Row::new().show(ui, |ui, _| { - let well = Mixed::Same(chip.map(|c| srgb(cms.display_rgb(&c)))); - let _ = Swatch::optional(tl!("Background").to_string(), well).tooltip(tip.clone()).show(ui); - let Some(ratio) = ratio else { - Text::new("—").tooltip(tip.clone()).show(ui); - return; + let entries = [(Label::from(tl!("Background").to_string()), chip.map_or(Srgba::new(0.0, 0.0, 0.0, 0.0), |c| srgb(cms.display_rgb(&c))))]; + ui.horizontal(|ui| { + // The chip holds no selection: a click reports one the row ignores. + let _ = SwatchTable::new(tl!("Contrast Background").to_string(), &entries) + .per_row(1) + .tips(true) + .selection(Bind::given(Selection::default())) + .show_all(ui); + let Some(ratio) = answer.and_then(|r| r["ratio"].as_f64()) else { + Text::new("—").tooltip(tip).show(ui); + return None; }; Text::new(wcag::ratio_text(ratio)).tooltip(tip.clone()).show(ui); let (aa, aaa) = category.passes(ratio); let result = |pass: bool| if pass { tl!("Pass") } else { tl!("Fail") }; Text::new(format!("AA {}", result(aa))).tooltip(tip.clone()).show(ui); if let Some(aaa) = aaa { - Text::new(format!("AAA {}", result(aaa))).tooltip(tip.clone()).show(ui); + Text::new(format!("AAA {}", result(aaa))).tooltip(tip).show(ui); } - }); + fix_chip(ui, cms, answer, aa, aaa) + }) + .inner +} + +/// 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`. Nothing is +/// shown when there is none. Returns the color when the chip is clicked or activated. +fn fix_chip(ui: &mut Ui, cms: &Cms, 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 (color, name) = level.and_then(|(key, name)| { + let v = answer?.get("fix")?.get(key)?; + serde_json::from_value::(v.clone()).ok().map(|c| (c, name)) + })?; + let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]); + let entries = [(Label::from(label), srgb(cms.display_rgb(&color)))]; + let out = SwatchTable::new(tl!("Closest Passing Color").to_string(), &entries) + .per_row(1) + .tips(true) + .activate(ActivateOn::Click) + // The chip applies by click and holds no selection of its own. + .selection(Bind::given(Selection::default())) + .show_all(ui); + out.open.map(|_| color) } /// What the HSB picked last belongs to: the document, the selected objects or text characters, @@ -1692,8 +2027,8 @@ fn apply_text(app: &mut VectorcraftApp, ui: &Ui, text: &str, opacity_set: bool, /// The wheel: the hue ring around the saturation and brightness square, with Show Harmony's markers /// on the ring. A click on a marker applies its color; a press held on one keeps the ring from -/// picking. -fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Picked { +/// picking. Returns the picks and the square's rect. +fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> (Picked, Option) { let marked = cx.color.is_some(); let others: Vec<[f32; 3]> = if set.harmony && marked { set.harmony_rule.apply_hsb(cx.shown).into_iter().skip(1).collect() } else { Vec::new() }; let markers: Vec = others.iter().map(|&hsb| srgb(hsb_to_rgb(hsb))).collect(); @@ -1706,14 +2041,18 @@ fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> P wheel = wheel.gamut(gamut(app)); } let out = wheel.show(ui); - match out.picked.and_then(|i| others.get(i)) { + // The square is the wheel's child named `square`. + let square = ui.ctx().read_response(out.edit.response.id.with("square")).map(|r| r.rect); + let picked = match out.picked.and_then(|i| others.get(i)) { Some(&hsb) => Picked { marker: Some(hsb), edits: Vec::new() }, None => Picked { marker: None, edits: vec![out.edit] }, - } + }; + (picked, square) } -/// The box: the field of channel `set.channel` and its strip. -fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Picked { +/// The box: the field of channel `set.channel` and its strip. Returns the picks and the field's +/// rect. +fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> (Picked, Option) { let ch = set.channel; let mode = area_mode(ch); let values = cx.color.map(|_| box_values(ch, cx.shown)); @@ -1722,8 +2061,9 @@ fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Pic area = area.gamut(gamut(app)); } let field = area.show(ui); + let rect = field.response.rect; let strip = ColorStrip::new(ch.name().to_string(), mode, bind(values)).show(ui); - Picked { marker: None, edits: vec![field, strip] } + (Picked { marker: None, edits: vec![field, strip] }, Some(rect)) } pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { @@ -1762,13 +2102,16 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) { fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings, now: f64) { let (cms, behind, cmyk_doc, hsb) = (cx.cms, cx.behind, cx.cmyk_doc, cx.shown); let mut picked = Picked::default(); + let measured = set.contrast.then(|| measure(app, panel)); + // The rect of the box's field or the wheel's square, which the contrast lines are drawn over. + let mut field = None; Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| { super::proxy(app, ui); match set.view { View::Box => { - Row::new().fill_width().show(ui, |ui, _| picked = show_box(app, ui, cx, set)); + Row::new().fill_width().show(ui, |ui, _| (picked, field) = show_box(app, ui, cx, set)); } - View::Wheel => picked = show_wheel(app, ui, cx, set), + View::Wheel => (picked, field) = show_wheel(app, ui, cx, set), } }); // The hex field shows the text of the frame's start, so a text committed when a press on the @@ -1858,8 +2201,15 @@ fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pi app.sync_views(); panel.rows_live = None; } - if set.contrast { - contrast_row(app, panel, ui, cx.cms); + if let Some(m) = &measured { + // With Alt held a pick goes to the other proxy, which the lines do not measure. + if let (Some(backdrop), Some(rect)) = (m.backdrop.as_ref().filter(|_| !cx.behind), field) { + let lines = lines_for(app, panel, backdrop, cx); + draw_contrast_lines(ui, rect, &lines); + } + if let Some(c) = contrast_row(app, panel, ui, cx.cms, m) { + apply(app, cx.tgt, c, Live::Released, false); + } } if set.vision { vision_row(ui, cx.cms, cx.color.as_ref()); diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 77afb2c39b..08dcd9f42e 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -1032,13 +1032,16 @@ fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list: split_row(app, ui); let data = RowsData::of(app); - let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() }; - let advanced = Section::new(tl!("Advanced")) - .open(Bind::bound(&mut app.ui.image_trace_advanced)) - .show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler))) - .inner - .unwrap_or_default(); + let (main, advanced) = rows::settings_group(ui, |ui| { + let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel); + let advanced = Section::new(tl!("Advanced")) + .open(Bind::bound(&mut app.ui.image_trace_advanced)) + .show(ui, |ui, _| rows::advanced_rows(ui, &mut st.params, &data, RowsHost::Panel, Some(sampler))) + .inner + .unwrap_or_default(); + (main, advanced) + }); // A setting is settled when its pick, check or drag ends. Switching to Custom while a slider // still drags would remove the preset's Enhanced row from under it. for RowsOutput { committed, .. } in [main, advanced] { diff --git a/crates/ui-egui/src/panels/image_trace/rows.rs b/crates/ui-egui/src/panels/image_trace/rows.rs index 73f3034177..98551787eb 100644 --- a/crates/ui-egui/src/panels/image_trace/rows.rs +++ b/crates/ui-egui/src/panels/image_trace/rows.rs @@ -11,7 +11,7 @@ use craft::theme::Srgba; use craft::ui::buttons::ToggleButton; use craft::ui::choice::{Checkbox, Segmented}; use craft::ui::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowContainer as _}; -use craft::ui::form::{Field, SliderField, SliderFieldLayout}; +use craft::ui::form::{Field, FieldGroup, SliderField, SliderFieldLayout}; use craft::ui::layout_components::Row; use craft::ui::pickers::Select; // PLAN: assumed `IconId` is re-exported from `craft::ui::primitives`. @@ -132,6 +132,12 @@ fn select_row(ui: &mut Ui, label: &'static str, entries: &[Entry], curre .flatten() } +/// Shows `rows` (one host's [`main_rows`] and [`advanced_rows`]) in one field group, so every row's label takes the +/// width of the widest and the selects and sliders start at the same x. +pub(crate) fn settings_group(ui: &mut Ui, mut rows: impl FnMut(&mut Ui) -> R) -> R { + FieldGroup::new(tl!("Tracing Settings")).show(ui, |ui, _| rows(ui)).inner.unwrap_or_default() +} + /// One number setting: its key, name, range, unit and the value shown when the setting is absent. struct Slider { key: &'static str, diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 28973d5897..29ed937ca9 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -706,6 +706,25 @@ fn advanced_is_a_section_that_stays_as_it_was_left() { assert!(panel.app().ui.image_trace_advanced && panel.shows("Corners")); } +#[test] +fn the_sliders_and_selects_start_in_one_column() { + use craft::ui::contract::Role; + let mut panel = panel_over(traced_app()); + panel.room(egui::vec2(320.0, 1400.0)); + panel.frame(); + panel.frame(); + assert!(panel.app().ui.image_trace_advanced); + // Threshold sits with the main rows and the others in Advanced; the Stroke slider shows dimmed. + let sliders: Vec<(&str, egui::Rect)> = + ["Threshold", "Paths", "Corners", "Noise", "Stroke"].into_iter().map(|n| (n, panel.rect_role(n, Role::SLIDER))).collect(); + let (_, first) = sliders[0]; + for (name, rect) in &sliders { + assert_eq!(rect.left(), first.left(), "the {name} slider starts where Threshold's does"); + assert_eq!(rect.width(), first.width(), "the {name} slider is as long as Threshold's"); + } + assert_eq!(panel.rect_role("Mode:", Role::COMBO_BOX).left(), first.left(), "the Mode select starts in the sliders' column"); +} + #[test] fn the_palette_shows_in_color_mode_and_traces_again() { let mut panel = panel_over(traced_app()); diff --git a/crates/ui-egui/src/panels/swatches.rs b/crates/ui-egui/src/panels/swatches.rs index a179e07a53..5caf20c7b5 100644 --- a/crates/ui-egui/src/panels/swatches.rs +++ b/crates/ui-egui/src/panels/swatches.rs @@ -41,6 +41,7 @@ mod libraries; #[cfg(test)] use actions::{deletable, delete, mergeable, new_swatch, selected_group}; pub(crate) use actions::{menu_rows, menu_states, run}; +pub(crate) use dnd::{HeldRows, follow_drag}; pub(crate) use libraries::{ DOCUMENT_SWATCHES, SwatchLibraries, USER_SLOT, colour_libraries, library_entries, limit_key, limit_name, load_library, open_library, other_library, user_library, window_menu, @@ -130,6 +131,9 @@ pub(crate) struct Model { kept: Option<(String, Option)>, /// The art and the active swatch the last pass saw ([`Model::focus`]). seen: Option<(Option, Option)>, + /// The rows of the last drag from the list (as it started) and what its last check found + /// ([`dnd::follow`]). + drag: Option<(Arc, HeldRows)>, } impl Model { @@ -388,6 +392,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { super::color_guide::choose_base(app, c); apply_click(app, ui, json!({"color": color_json(&c)})); } + // A drag whose rows were all replaced or removed since it started (or that started in another + // document) is not taken. + let held = match craft::ui::runtime::drag::active::(ui.ctx()).as_deref() { + Some(PanelDrag::Paint { rows: Some(r), .. }) => !dnd::follow(app, r).is_empty(), + _ => true, + }; // The model leaves the app while the browser borrows the document, and comes back before the events run. let mut model = std::mem::take(&mut app.ui.swatches_panel); let view = app.ui.swatches_view; @@ -410,9 +420,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { let revision = (st.uid, st.revision); let lit: Vec = highlighted(&st.doc, &base).into_iter().map(str::to_string).collect(); let doc = Arc::clone(&st.doc); + let start = dnd::DragStart::of(st); let document = st.uid; let reverts = st.reverts; - let foot = Footer::of(app, &model); + let foot = Footer::of(app, &model, held); let shown_app: &VectorcraftApp = app; let search = model.show_find; let state = &mut model.state; @@ -425,10 +436,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { .fill() .footer(|ui, _| footed = Some(foot.show(ui))) .show(ui, |ui, _| { - let dragged_doc = Arc::clone(&doc); + let start = start.clone(); let thumbs = Thumbs { revision, lit: lit.clone(), doc: Arc::clone(&doc) }; let browser = SwatchesPanel::new(&data, Bind::bound(&mut *state), Srgba::rgb(0.0, 0.0, 0.0)) - .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&dragged_doc, document, &drag.grabbed, dragged_rows(drag)))) + .drag_payload(move |drag: &ListDrag| Some(dnd::drag_of(&start, &drag.grabbed, dragged_rows(drag)))) .thumb(thumbs, thumb) .row_icons(|key| match key { SwatchKey::Swatch(name) => row_icons(shown_app, name), @@ -445,6 +456,11 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui) { }) .inner; app.ui.swatches_panel = model; + // The rows being dragged from the list are checked on every pass, so the footer's drop finds + // the ones replaced since the drag started. + if let Some(PanelDrag::Paint { rows: Some(r), .. }) = craft::ui::runtime::drag::active::(ui.ctx()).as_deref() { + dnd::follow(app, r); + } let shown = shown_keys(&data); if let Some(out) = out { if let Some((at, _, alt)) = out.used @@ -791,11 +807,14 @@ struct Footer { group: Option, libraries_open: bool, document: Option, + /// Whether a drag from the list still has rows the document holds unchanged ([`dnd::follow`]). + held: bool, } impl Footer { - /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it. - fn of(app: &VectorcraftApp, model: &Model) -> Self { + /// The footer's state for the panel `model`, which is out of the app while the swatch browser borrows it, with + /// `held` from the drag check ([`Footer::held`]). + fn of(app: &VectorcraftApp, model: &Model, held: bool) -> Self { let sel = selected_in(app, model); let del = actions::deletable(app, &sel); let opts = actions::editable(app, &sel); @@ -804,6 +823,7 @@ impl Footer { kind: model.kind, libraries_open: library_panel::any_open::(&app.ui), document: app.session.active().map(|state| state.uid), + held, sel, del, opts, @@ -815,7 +835,8 @@ impl Footer { fn show(&self, ui: &mut Ui) -> FooterOutput { let icon = |id: &'static str| IconSpec::svg(IconId::new(id)); let document = self.document; - let rows_drag = move |d: &PanelDrag| matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); + let held = self.held; + let rows_drag = move |d: &PanelDrag| held && matches!(d, PanelDrag::Paint { rows: Some(rows), .. } if Some(rows.document) == document); let edit = if self.group.is_some() { FooterAction::new(icon("palette"), tl!("Edit or Apply Color Group")) } else { diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 6ff3420571..78ebf4a02d 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -1,8 +1,12 @@ -use super::{Document, Paint, PanelDrag, REGISTRATION, Value, VectorcraftApp, json, name_of, swatch_params}; +use std::sync::{Arc, Weak}; + +use super::{Document, Paint, PanelDrag, REGISTRATION, Swatch, Value, VectorcraftApp, json, name_of, swatch_params}; use crate::panel_drag::SwatchRows; use craft::color_ui::ui::SwatchKey; use craft::keymap::Mods; use craft::ui::contract::{DropAt, ReorderMove}; +use vectorcraft_color::SwatchGroup; +use vectorcraft_engine::{DocState, History, HistoryEntry}; /// Swatches take paints, and take swatch rows or canvas art from the current document. pub(super) fn accepts(drag: &PanelDrag, document: u64, reverts: u64) -> bool { @@ -50,9 +54,10 @@ impl Drop { } } -/// The drag a row of `key` starts, moving rows `names`. Colour groups have no paint of their own -/// (the chip under the pointer draws Registration's mark for Registration). -pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec) -> PanelDrag { +/// The drag a row of `key` starts in document `start`, moving rows `names`. Colour groups have no +/// paint of their own (the chip under the pointer draws Registration's mark for Registration). +pub(super) fn drag_of(start: &DragStart, key: &SwatchKey, names: Vec) -> PanelDrag { + let d = &start.doc; let name = name_of(key); let (paint, params, unlinked_process_color) = match key { SwatchKey::Swatch(_) if name == REGISTRATION => (Paint::registration(), swatch_params(d, name), false), @@ -65,10 +70,197 @@ pub(super) fn drag_of(d: &Document, document: u64, key: &SwatchKey, names: Vec (Paint::None, Value::Null, false), }; - let rows = SwatchRows { document, grabbed: name.to_string(), names, groups: matches!(key, SwatchKey::Group(_)), unlinked_process_color }; + let held = Arc::new(start.rows(&names)); + let groups = matches!(key, SwatchKey::Group(_)); + let rows = SwatchRows { document: start.uid, grabbed: name.to_string(), names, groups, unlinked_process_color, held }; PanelDrag::Paint { paint, params, rows: Some(rows), library: None } } +/// A row dragged from the list as it was when the drag started: its swatch or its colour group. +#[derive(Clone, PartialEq)] +enum HeldRow { + Swatch(Swatch), + Group(SwatchGroup), +} + +impl HeldRow { + /// Row `name` of `d`: its swatch, else the colour 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 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)] +} + +/// A document as a drag from the list finds it: its `uid` and its count of File › Revert +/// ([`DocState::reverts`]), its state, its newest steps ([`steps`]) and the state undoing the newest +/// undo step gives back (that step's document). +#[derive(Clone)] +pub(super) struct DragStart { + uid: u64, + reverts: u64, + doc: Arc, + steps: [u64; 4], + back: Option>, +} + +impl DragStart { + pub(super) fn of(st: &DocState) -> Self { + let back = st.history.undo.last().map(|e| Arc::clone(&e.doc)); + DragStart { uid: st.uid, reverts: st.reverts, doc: Arc::clone(&st.doc), steps: steps(st), back } + } + + /// Rows `names` as this document holds them. + fn rows(&self, names: &[String]) -> HeldRows { + let rows: Vec<_> = names.iter().map(|n| (n.clone(), HeldRow::of(&self.doc, n))).collect(); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(self.back.as_deref()).is_some_and(|(r, d)| r.unchanged_in(d))).collect(); + HeldRows { uid: self.uid, reverts: self.reverts, doc: Arc::downgrade(&self.doc), steps: self.steps, rows, back } + } +} + +/// The rows a drag from the list carries, in the order of its names, and the document (`uid`, and +/// its count of File › Revert) and the state and undo history they were last checked against. A +/// row is `None` once a state of the document since the drag started did not hold it unchanged: +/// deleted, edited, or deleted and made again under its name, also with the same paint. +#[derive(Clone, Default)] +pub(crate) struct HeldRows { + uid: u64, + reverts: u64, + doc: Weak, + /// The newest undo step of the document and the one under it, and the next redo step and the + /// one under it ([`steps`]). + 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, +} + +impl PartialEq for HeldRows { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid + && self.reverts == other.reverts + && self.doc.ptr_eq(&other.doc) + && self.steps == other.steps + && self.rows == other.rows + && self.back == other.back + } +} + +impl std::fmt::Debug for HeldRows { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let held: Vec<(&str, bool)> = self.rows.iter().map(|(n, r)| (n.as_str(), r.is_some())).collect(); + f.debug_struct("HeldRows").field("uid", &self.uid).field("steps", &self.steps).field("held", &held).finish_non_exhaustive() + } +} + +/// `held` checked against every state document `st` passed through since it was 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 on every +/// pass and 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 checked(held: HeldRows, st: &DocState) -> HeldRows { + 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 (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) + } + 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: Vec<_> = 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 last = undo.last(); + let back = rows.iter().map(|(_, r)| r.as_ref().zip(last).is_some_and(|(r, e)| r.unchanged_in(&e.doc))).collect(); + HeldRows { uid: held.uid, reverts: held.reverts, doc: Arc::downgrade(&st.doc), steps: now, rows, back } +} + +/// The names of drag `r` that the active document has held unchanged since the drag started +/// ([`checked`]), in the drag's order. Empty when the drag started in another document, or before +/// File › Revert replaced the document. The panel keeps what it found for the drag, so the next +/// check starts from there. +pub(super) fn follow(app: &mut VectorcraftApp, r: &SwatchRows) -> Vec { + let Some(st) = app.session.active() else { return vec![] }; + if st.uid != r.held.uid || st.reverts != r.held.reverts { + return vec![]; + } + let kept = &mut app.ui.swatches_panel.drag; + let from = match kept { + Some((start, now)) if Arc::ptr_eq(start, &r.held) => now.clone(), + _ => (*r.held).clone(), + }; + let now = checked(from, st); + let names = if now.rows.len() == r.names.len() { + r.names + .iter() + .zip(&now.rows) + .filter(|(n, (h, row))| *n == h && row.as_ref().is_some_and(|row| row.unchanged_in(&st.doc))) + .map(|(n, _)| n.clone()) + .collect() + } else { + vec![] + }; + *kept = Some((Arc::clone(&r.held), now)); + names +} + +/// Checks the rows being dragged from the list against the active document after a command ran +/// ([`follow`]), so that the commands after it cannot replace one unseen. +pub(crate) fn follow_drag(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if let Some(PanelDrag::Paint { rows: Some(r), .. }) = craft::ui::runtime::drag::active::(&ctx).as_deref() { + follow(app, r); + } +} + /// The row `at` names and whether the drop lands after it: onto a row it is that row; in a gap it is /// the row under the pointer, after it when the gap lies beyond its position in `shown`; a gap with /// no row under the pointer is the end of the list. @@ -123,13 +315,20 @@ pub(super) enum FooterTarget { /// Swatches or groups dragged from the list and released on a footer button (ap.AP8 `FooterDrop`): /// New Swatch duplicates the swatches among them, Delete Swatch asks to delete them as a click on -/// the button does. Other drags are left to their own targets. +/// the button does. Only rows the active document has held unchanged since the drag started count +/// ([`follow`]): a row deleted, edited or replaced under its name meanwhile, and every row of a drag +/// started in another document, is left alone. Other drags are left to their own targets. pub(super) fn on_footer_drop(app: &mut VectorcraftApp, target: FooterTarget, drag: &PanelDrag) { let PanelDrag::Paint { rows: Some(r), .. } = drag else { return }; if !app.session.active().is_some_and(|state| state.uid == r.document) { return; } - let rows = footer_rows(app, r); + let held = follow(app, r); + if held.is_empty() { + return; + } + // Rows of the drag must be unchanged since it started; selected rows the drag does not hold come with it. + let rows: Vec = footer_rows(app, r).into_iter().filter(|n| !r.names.contains(n) || held.contains(n)).collect(); match target { FooterTarget::Delete => { let names = super::actions::deletable(app, &rows); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 617fb83a35..dd993bb69d 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -94,10 +94,10 @@ fn dropped_below(app: &mut VectorcraftApp, drag: PanelDrag, mods: Mods) { dnd::on_dropped(app, &shown, &at, &drag, mods); } -/// The drag the row `name` starts, carrying rows `names`. +/// The drag the row `name` starts in the active document, carrying rows `names`. fn rows_drag(app: &VectorcraftApp, name: &str, names: &[&str]) -> PanelDrag { - let document = app.session.active().unwrap().uid; - dnd::drag_of(&doc(app), document, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) + let start = dnd::DragStart::of(app.session.active().expect("a document")); + dnd::drag_of(&start, &key_of(app, name), names.iter().map(|n| n.to_string()).collect()) } #[test] @@ -717,6 +717,184 @@ fn footer_drops_ignore_rows_from_another_document() { } } +/// The document and its undo step count. +fn doc_and_steps(app: &VectorcraftApp) -> (Document, usize) { + (doc(app), undo_steps(app)) +} + +/// Delete Swatch acts only on rows the document has held unchanged since the drag started: a swatch +/// deleted and made again under its name while it is dragged, a swatch the newest undo step made +/// that an undo takes back before one of that name is made again, and a swatch deleted and brought +/// back by an undo all ask nothing and are kept, also when the new swatch has the same color. A +/// swatch dragged while an undo takes back a step that left it alone is still deleted after +/// asking, and a drag started in another document deletes nothing. +#[test] +fn delete_swatch_skips_rows_replaced_during_the_drag() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + // Deleted and made again under its name, with the same color. + let drag = rows_drag(&app, "Orange", &["Orange"]); + let orange = doc(&app).swatch("Orange").cloned(); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let replaced = doc_and_steps(&app); + assert_eq!(replaced.0.swatch("Orange").cloned(), orange, "the new swatch is the same as the one deleted"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the new swatch of that name asks nothing"); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch of that name is kept"); + // Made by the newest undo step, undone, and made again. + let glass = json!({"name": "Sea Glass", "color": "#00a99d"}); + app.run("swatch.new", glass.clone()).unwrap(); + let made = doc(&app).swatch("Sea Glass").cloned(); + let drag = rows_drag(&app, "Sea Glass", &["Sea Glass"]); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert!(doc(&app).swatch("Sea Glass").is_none(), "the undo takes Sea Glass away"); + app.session.execute("swatch.new", &glass).unwrap(); + let replaced = doc_and_steps(&app); + assert_eq!(replaced.0.swatch("Sea Glass").cloned(), made, "the new swatch is the same as the one undone"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the new swatch made after the undo asks nothing"); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch made after the undo is kept"); + // Deleted and brought back by an undo. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.session.execute("swatch.delete", &json!({"names": ["Orange"]})).unwrap(); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc_and_steps(&app), replaced, "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "a swatch brought back by an undo asks nothing"); + // An undo of a step that left the swatch alone. + app.run("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})).unwrap(); + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("edit.undo", json!({})).unwrap(); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(dialog_open(&app, key), "a swatch an undo left alone is deleted after asking"); + cancel(&mut app, key); + // Dragged from this document, dropped while another document with the same swatches is active. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let other = doc_and_steps(&app); + assert!(other.0.swatch("Orange").is_some(), "the other document has Orange"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the other document asks nothing"); + assert_eq!(doc_and_steps(&app), other, "the other document keeps Orange"); +} + +/// New Swatch duplicates only rows the document has held unchanged since the drag started: a +/// swatch deleted and made again under its name while it is dragged, a swatch the newest undo step +/// made that an undo takes back before one of that name is made again, and a swatch deleted and +/// brought back by an undo between two passes of the panel are not duplicated. A swatch that stays +/// unchanged is. +#[test] +fn new_swatch_skips_rows_replaced_during_the_drag() { + let mut app = app(); + // Deleted and made again under its name, with the same color. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("swatch.delete", json!({"names": ["Orange"]})).unwrap(); + app.run("swatch.new", json!({"name": "Orange", "color": "#f7931e"})).unwrap(); + let replaced = doc_and_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert!(open_dialogs(&app).is_empty(), "the new swatch of that name opens no dialog"); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch of that name is not duplicated"); + // Made by the newest undo step (a batch), undone, and made again. + 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 drag = rows_drag(&app, "Sea Glass", &["Sea Glass"]); + app.session.execute("edit.undo", &json!({})).unwrap(); + app.session.execute("swatch.new", &glass).unwrap(); + let replaced = doc_and_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), replaced, "the new swatch made after the undo is not duplicated"); + // Deleted and brought back by an undo, then an edit that clears the redo steps, each seen by a + // pass of the panel. + let drag = rows_drag(&app, "Orange", &["Orange"]); + let PanelDrag::Paint { rows: Some(rows), .. } = &drag else { panic!("a rows drag") }; + for (id, params) in [ + ("swatch.delete", json!({"names": ["Orange"]})), + ("edit.undo", json!({})), + ("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})), + ] { + app.run(id, params).unwrap(); + dnd::follow(&mut app, rows); + } + let restored = doc_and_steps(&app); + assert!(restored.0.swatch("Orange").is_some(), "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is not duplicated"); + // A swatch that stays unchanged is duplicated. + let drag = rows_drag(&app, "Orange", &["Orange"]); + app.run("shape.rectangle", json!({"x": 90, "y": 0, "width": 20, "height": 20})).unwrap(); + let undo = undo_steps(&app); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert!(doc(&app).swatch("Orange copy").is_some(), "an unchanged swatch is duplicated"); + assert_eq!(undo_steps(&app), undo + 1); +} + +/// A drag started before File › Revert replaced the document duplicates and deletes nothing, also +/// when the reverted document holds the same swatches. +#[test] +fn rows_dragged_before_a_revert_are_left_alone() { + let mut app = app(); + let key = crate::dialogs::confirm::KIND; + let drag = rows_drag(&app, "Orange", &["Orange"]); + let at = app.session.active_index().expect("a document"); + let copy = doc(&app); + assert!(app.session.replace_document(at, copy)); + let reverted = doc_and_steps(&app); + assert!(reverted.0.swatch("Orange").is_some(), "the reverted document has Orange"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), reverted, "the reverted document's Orange is not duplicated"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "the reverted document asks nothing"); + assert_eq!(doc_and_steps(&app), reverted, "the reverted document keeps Orange"); +} + +/// The rows of a drag running in the drag session are checked after every command the app runs: +/// a swatch deleted and brought back by an undo, then an edit that clears the redo steps, all with +/// no pass of the panel in between, is neither duplicated by New Swatch nor deleted by Delete +/// Swatch. +#[test] +fn rows_dragged_in_the_session_are_checked_after_every_command() { + use craft::behavior::keyed; + use craft::ui::contract::ShowCollection as _; + use craft::ui::list::{List, ListRow}; + use craft::ui::testing::Fixture; + + let mut app = app(); + let payload = rows_drag(&app, "Orange", &["Orange"]); + // A list row that starts the drag through the drag session, as a row of the panel does. + let mut fixture = Fixture::new(move |ui| { + let payload = payload.clone(); + let _ = List::::new("Drag source").drag_payload(move |_: &ListDrag| Some(payload.clone())).show_items( + ui, + &keyed(&[0u32], |key: &u32| *key), + &mut |_, _| ListRow::new("Dragged"), + ); + }); + fixture.room(vec2(240.0, 120.0)); + fixture.settle(); + app.ui_ctx = Some(fixture.ctx().clone()); + let from = fixture.by_label("Dragged").expect("the drag source").center(); + let key = crate::dialogs::confirm::KIND; + fixture.drag_at_pausing(from, vec2(0.0, 60.0), |f| { + let drag = craft::ui::runtime::drag::active::(f.ctx()).expect("the rows drag"); + for (id, params) in [ + ("swatch.delete", json!({"names": ["Orange"]})), + ("edit.undo", json!({})), + ("shape.rectangle", json!({"x": 60, "y": 0, "width": 20, "height": 20})), + ] { + app.run(id, params).unwrap(); + } + let restored = doc_and_steps(&app); + assert!(restored.0.swatch("Orange").is_some(), "the undo brings Orange back"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::New, &drag); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is not duplicated"); + dnd::on_footer_drop(&mut app, dnd::FooterTarget::Delete, &drag); + assert!(!dialog_open(&app, key), "a swatch brought back by an undo asks nothing"); + assert_eq!(doc_and_steps(&app), restored, "a swatch brought back by an undo is kept"); + }); +} + /// A selected swatch dragged onto New Swatch or Delete Swatch carries the selected swatches that /// the find field hides, which the browser leaves out of the drag, as a click on Delete Swatch /// takes them too. The copies are selected in panel order. A grabbed swatch outside the selection 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 b26c84c00d..2f938cc8e2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -1,13 +1,11 @@ -//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and -//! the AA and AAA results, the color behind the selection, a pinned background, a drag on the -//! wheel, the panel menu and `ui.colorWheel`. +//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and the +//! AA and AAA results, the color behind the selection, a pinned background, the panel menu, a drag +//! on the wheel, and `ui.colorWheel`. -use craft::ui::runtime::access::Role; use serde_json::{Value, json}; use vectorcraft_color::wcag; use vectorcraft_engine::Session; -use super::color_wheel::{BehindKey, RatioKey}; use super::tests_color_wheel::Panel; use crate::VectorcraftApp; use crate::i18n::LangExt as _; @@ -26,6 +24,18 @@ fn shows(p: &Panel, text: &str) -> bool { p.fx.by_label(text).is_some() } +/// The background read on its own, as `#rrggbb`, if the row read one. +fn behind(p: &Panel) -> Option> { + p.app().ui.color_wheel_panel.behind.as_ref().map(|(_, hex)| hex.clone()) +} + +/// The background in the row's kept answer. +fn measured(p: &Panel) -> Option { + let app = p.app(); + let answer = app.ui.color_wheel_panel.ratio.as_ref().and_then(|(_, r)| r.as_ref()); + answer.and_then(|r| r["against"].as_str().map(str::to_string)) +} + #[test] fn the_row_cuts_the_ratio_off_and_fails_aa_just_under_it() { let mut app = app("#fdc96e"); @@ -45,25 +55,24 @@ fn the_contrast_for_menu_shows_the_categories_in_the_interface_language() { assert_ne!(names[0], Category::NormalText.label()); } -/// The panel menu's Show Contrast, Contrast For and Contrast Background rows set the settings, and +/// The panel menu's Show Contrast, Contrast For and Contrast Background rows set the row, and /// Current Color pins the color the panel edits. #[test] -fn the_panel_menu_sets_the_contrast_settings() { +fn the_panel_menu_sets_the_row_its_category_and_its_background() { let mut app = app("#336699"); app.run("ui.colorWheel", json!({"contrast": false})).unwrap(); - let run = |app: &mut VectorcraftApp, row: &str| super::color_wheel::run(app, &format!("ui.colorWheel.{row}"), &json!({})).unwrap().unwrap(); - assert_eq!(run(&mut app, "contrast")["contrast"], true); - assert_eq!(run(&mut app, "contrastFor.graphics")["contrastFor"], "graphics"); - run(&mut app, "contrastBackground.current"); + let run = |app: &mut VectorcraftApp, row: &str| super::color_wheel::run(app, &format!("ui.colorWheel.{row}"), &Value::Null).expect("a menu row"); + run(&mut app, "contrast").unwrap(); + assert!(app.ui.color_wheel.contrast); + run(&mut app, "contrastFor.largeText").unwrap(); + assert_eq!(app.ui.color_wheel.contrast_for, wcag::Category::LargeText); + run(&mut app, "contrastBackground.current").unwrap(); assert_eq!(app.ui.color_wheel.contrast_background.map(|c| c.to_hex()).as_deref(), Some("#336699")); - assert_eq!(run(&mut app, "contrastBackground.below")["contrastBackground"], Value::Null); - let mut states = craft::ui::runtime::commands::CommandStates::new(); + run(&mut app, "contrastBackground.below").unwrap(); + assert_eq!(app.ui.color_wheel.contrast_background, None); + // With no solid color in the active proxy there is no color to pin. app.run("paint.setFill", json!({"none": true})).unwrap(); - super::color_wheel::menu_states(&app, &mut states); - let current = states.get(&craft::keymap::CommandRef::new("ui.colorWheel.contrastBackground.current")).expect("a state"); - assert!(!current.is_enabled(), "Current Color needs a color to pin"); - let e = super::color_wheel::run(&mut app, "ui.colorWheel.contrastBackground.current", &json!({})).unwrap().unwrap_err(); - assert_eq!(e, "Current Color needs a solid color in the active proxy"); + assert!(run(&mut app, "contrastBackground.current").is_err()); assert_eq!(app.ui.color_wheel.contrast_background, None, "the error pins nothing"); } @@ -75,11 +84,13 @@ fn an_answer_kept_under_other_color_settings_is_asked_again() { app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap(); let mut p = Panel::new(app); assert!(shows(&p, "21.00:1")); - let (mut key, answer) = p.app().ui.color_wheel_panel.ratio.clone().expect("the row keeps its answer"); - let mut stale = answer.expect("an answer"); - stale["ratio"] = json!(1.0); - key.under.1 = u64::MAX; - p.app_mut().ui.color_wheel_panel.ratio = Some((key, Some(stale))); + { + let mut app = p.app_mut(); + let (key, answer) = app.ui.color_wheel_panel.ratio.as_mut().expect("the row keeps its answer"); + let stale = answer.as_mut().expect("an answer"); + stale["ratio"] = json!(1.0); + key.under.1 = u64::MAX; + } p.fx.idle(2); assert!(shows(&p, "21.00:1"), "the answer is asked again under the current settings"); } @@ -127,11 +138,21 @@ fn the_background_is_the_art_behind_the_selection() { let want = wcag::ratio_text(wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0])); assert!(shows(&p, &want), "black on the locked yellow: {want}"); // Screen readers find the chip by its name, with the background's hex value as its value. - let chip = p.node("Background"); - assert_eq!(p.fx.tree().role_of(chip.node), Some(Role::COLOR_WELL)); assert_eq!(p.value("Background").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 p = Panel::new(app); + assert!(shows(&p, "21.00:1"), "white on black"); + assert_eq!(p.value("Background").as_deref(), Some("#000000")); +} + #[test] fn nothing_selected_and_nothing_pinned_shows_no_ratio() { let mut app = app("#000000"); @@ -157,39 +178,30 @@ fn the_row_follows_the_default_fill_with_nothing_selected() { assert!(shows(&p, "1.00:1"), "white on the pinned white"); } -/// The background read on its own, with what it was read for. -fn behind(p: &Panel) -> Option<(BehindKey, Option)> { - p.app().ui.color_wheel_panel.behind.clone() -} - -/// The background in the row's kept answer. -fn measured(p: &Panel) -> Option { - let kept: Option<(RatioKey, Option)> = p.app().ui.color_wheel_panel.ratio.clone(); - kept.and_then(|(_, r)| r).and_then(|r| r["against"].as_str().map(str::to_string)) -} - /// During a drag on the wheel every preview raises the document's revision, and the row asks again -/// for the ratio, whose answer gives the chip: the background is not read on its own as well. The -/// drag is an interaction whose previews set the fill, as the Show Document Colors row's drag test -/// runs it. +/// for the ratio, whose answer gives the chip: the background is not read on its own as well. #[test] fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() { let mut p = Panel::new(app("#336699")); assert_eq!(measured(&p).as_deref(), Some("#ffffff")); assert!(behind(&p).is_none(), "the answer gave the background"); - p.app_mut().session.begin_interaction("test").unwrap(); - for fill in ["#3a6a9a", "#406f9f", "#4675a5"] { - p.run("paint.setFill", json!({"color": fill})); - } + let ratio = |p: &Panel| p.app().ui.color_wheel_panel.ratio.as_ref().and_then(|(_, r)| r.as_ref()).and_then(|r| r["ratio"].as_f64()); + let first = ratio(&p); + // A drag on the hue ring, near its right edge. + let wheel = p.node("Color wheel").rect; + let at = wheel.center() + egui::vec2(wheel.width() * 0.45, 0.0); + let by = egui::vec2(0.0, 24.0); + p.fx.drag_hold_at(at, by); assert!(p.app().session.in_interaction(), "the drag previews on an interaction"); - p.app_mut().session.commit_interaction().unwrap(); - p.fx.idle(2); + assert_ne!(ratio(&p), first, "the row asked again for the previewed color"); + p.fx.release_at(at + by).idle(2); + assert!(!p.app().session.in_interaction(), "the release ends the drag"); assert!(behind(&p).is_none(), "the background was not read on its own during or after the drag"); assert_eq!(measured(&p).as_deref(), Some("#ffffff")); } -/// 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()); @@ -205,13 +217,12 @@ fn a_paint_with_no_color_still_shows_the_background() { app.run("ui.colorWheel", json!({"contrast": true})).unwrap(); let mut p = Panel::new(app); assert!(shows(&p, "—"), "a fill of None has no ratio"); - let hex = |p: &Panel| behind(p).and_then(|(_, hex)| hex); - assert_eq!(hex(&p).as_deref(), Some("#ffff00")); - assert_eq!(p.value("Background").as_deref(), Some("#ffff00"), "the chip shows it"); + assert_eq!(p.value("Background").as_deref(), Some("#ffff00")); + assert!(behind(&p).is_none(), "the background a pick is measured against was not read again on its own"); p.app_mut().run("select.set", json!({"ids": [b]})).unwrap(); p.app_mut().session.begin_interaction("test").unwrap(); p.fx.idle(2); - assert_eq!(hex(&p).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction"); + assert_eq!(p.value("Background").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 @@ -227,14 +238,13 @@ 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 p = Panel::new(app); - let hex = |p: &Panel| behind(p).and_then(|(_, hex)| hex); p.app_mut().session.begin_interaction("test").unwrap(); p.fx.idle(2); - assert_eq!(hex(&p).as_deref(), Some("#ffff00")); + assert_eq!(p.value("Background").as_deref(), Some("#ffff00")); p.app_mut().run("object.move", json!({"dx": 110, "dy": 0})).unwrap(); assert!(p.app().session.in_interaction(), "the move is part of the interaction"); p.fx.idle(2); - assert_eq!(hex(&p).as_deref(), Some("#ffffff"), "the background at the new place"); + assert_eq!(p.value("Background").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 @@ -257,7 +267,7 @@ fn an_interaction_reads_the_background_again_for_another_selection() { p.app_mut().session.begin_interaction("test").unwrap(); p.fx.idle(2); assert_eq!(measured(&p).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction"); - assert_eq!(p.value("Background").as_deref(), Some("#ffffff"), "the chip shows it"); + assert_eq!(p.value("Background").as_deref(), Some("#ffffff")); } /// Without a pin the row asks for the color behind the selection, so a translucent group holding @@ -280,10 +290,13 @@ fn the_row_answers_as_color_contrast_does_inside_a_translucent_group() { app.run("select.set", json!({"ids": [front]})).unwrap(); app.run("ui.colorWheel", json!({"contrast": true})).unwrap(); let p = Panel::new(app); - let want = p.app_mut().session.execute("color.contrast", &json!({})).unwrap(); - let against = want["against"].clone(); - let given = p.app_mut().session.execute("color.contrast", &json!({"against": against})).unwrap(); - let (want, given) = (wcag::ratio_text(want["ratio"].as_f64().unwrap()), wcag::ratio_text(given["ratio"].as_f64().unwrap())); + let (want, given) = { + let mut app = p.app_mut(); + let want = app.session.execute("color.contrast", &json!({})).unwrap(); + let against = want["against"].clone(); + let given = app.session.execute("color.contrast", &json!({"against": against})).unwrap(); + (wcag::ratio_text(want["ratio"].as_f64().unwrap()), wcag::ratio_text(given["ratio"].as_f64().unwrap())) + }; assert_ne!(want, given, "the group's other art makes the two answers differ"); assert!(shows(&p, &want), "the row shows {want}, not {given}"); } 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..7580367be6 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -0,0 +1,260 @@ +//! 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 through the `Fixture`. + +use egui::{Color32, Modifiers}; +use serde_json::json; +use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb}; +use vectorcraft_engine::Session; + +use super::color_wheel::{Channel, Lines, contrast_lines, field_pick}; +use super::tests_color_wheel::Panel; +use crate::VectorcraftApp; + +/// 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 lines(p: &Panel) -> Lines { + p.app().ui.color_wheel_panel.lines.clone().expect("the field's contrast lines were found").1 +} + +/// Whether the lines were found coarsely, during a drag that changes the field. +fn coarse(p: &Panel) -> bool { + p.app().ui.color_wheel_panel.lines.as_ref().expect("lines were found").0.4 +} + +/// 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(p: &Panel, 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 = p.app_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))] +} + +/// The display HSB of #FDC96E. +fn shown_hsb() -> [f32; 3] { + vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap())) +} + +/// The clip rects of the dark strokes of the solid (AA) lines the panel draws, in a fresh frame. +fn dark_line_clips(p: &mut Panel) -> Vec { + p.fx.frame_clipped_shapes() + .into_iter() + .filter(|(_, shape)| matches!(shape, egui::Shape::Path(path) if path.stroke.width == 3.0 && matches!(path.stroke.color, egui::epaint::ColorMode::Solid(c) if c == Color32::BLACK))) + .map(|(clip, _)| clip) + .collect() +} + +#[test] +fn the_box_marks_where_its_colors_meet_aa() { + let mut p = Panel::new(app("box", "hue")); + let lines = lines(&p); + assert_eq!(lines.len(), 2, "AA and AAA for normal text"); + let hsb = shown_hsb(); + let at = move |x: f32, y: f32| field_pick(Channel::Hue, x, y, hsb); + let [above, below] = either_side(&lines); + let (a, b) = (passes_aa(&p, &at, above), passes_aa(&p, &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); + let field = p.node("Color box").rect; + let clips = dark_line_clips(&mut p); + assert!(!clips.is_empty() && clips.iter().all(|c| *c == field), "the lines are drawn over the field: {clips:?} {field:?}"); +} + +#[test] +fn the_wheels_square_marks_where_its_colors_meet_aa() { + let mut p = Panel::new(app("wheel", "hue")); + let lines = lines(&p); + let hsb = shown_hsb(); + let at = move |x: f32, y: f32| [hsb[0], x, 1.0 - y]; + let [above, below] = either_side(&lines); + assert!(passes_aa(&p, &at, above) && !passes_aa(&p, &at, below)); + let square = p.node("Saturation and brightness").rect; + let clips = dark_line_clips(&mut p); + assert!(!clips.is_empty() && clips.iter().all(|c| *c == square), "the lines are drawn over the square: {clips:?} {square:?}"); +} + +/// 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 p = Panel::new(app); + let lines = lines(&p); + let aa = lines.first().expect("an AA level"); + assert!(aa.len() >= 2, "a line on each side of the band: {aa:?}"); + p.app_mut().run("paint.setFill", json!({"color": "#757575"})).unwrap(); + let r = p.app_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 p = Panel::new(app); + let lines = lines(&p); + 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:?}"); +} + +/// 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 p = Panel::new(app); + assert!(p.fx.by_label("—").is_some(), "no color to measure"); + let lines = lines(&p); + 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 p = Panel::new(app("box", "hue")); + p.app_mut().ui.color_wheel_panel.lines = None; + p.fx.hold(Modifiers::ALT).idle(2); + assert!(p.app().ui.color_wheel_panel.lines.is_none(), "no lines with Alt held"); + assert!(dark_line_clips(&mut p).is_empty(), "none drawn with Alt held"); + p.fx.hold(Modifiers::NONE).idle(2); + assert!(p.app().ui.color_wheel_panel.lines.is_some(), "the lines are back"); +} + +#[test] +fn graphics_have_one_line() { + let mut app = app("box", "saturation"); + app.run("ui.colorWheel", json!({"contrastFor": "graphics"})).unwrap(); + let p = Panel::new(app); + assert_eq!(lines(&p).len(), 1, "graphics have AA only"); +} + +const CHIP: &str = "The closest color that passes AA: click to apply it."; + +/// The fix `color.contrast` answers for AA against the pinned #355F78. +fn aa_fix(p: &Panel) -> Color { + let want = p.app_mut().session.execute("color.contrast", &json!({"against": "#355f78"})).unwrap(); + serde_json::from_value(want["fix"]["aa"].clone()).unwrap() +} + +fn fill(p: &Panel) -> Paint { + p.app().session.proxy_paints().0 +} + +#[test] +fn the_chip_applies_the_fix_color_answers() { + let mut p = Panel::new(app("wheel", "hue")); + let fix = aa_fix(&p); + p.point(CHIP); + match fill(&p) { + Paint::Solid { color, .. } => assert_eq!(color, fix), + other => panic!("the fill is {other:?}"), + } + assert!(p.fx.by_label(CHIP).is_none(), "the color now passes AA: no chip"); + assert!(p.fx.by_label("AA Pass").is_some()); +} + +/// A screen reader's click on the chip applies the color as a pointer click does. +#[test] +fn a_screen_readers_click_applies_the_fix() { + let mut p = Panel::new(app("box", "hue")); + let fix = aa_fix(&p); + p.click(CHIP); + match fill(&p) { + Paint::Solid { color, .. } => assert_eq!(color, fix), + other => panic!("the fill is {other:?}"), + } +} + +#[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 p = Panel::new(app); + assert!(p.fx.by_label(CHIP).is_none(), "4.49:1 meets large text AA"); + assert!(p.fx.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 p = Panel::new(app); + for level in ["AA", "AAA"] { + assert!(p.fx.by_label(&format!("The closest color that passes {level}: click to apply it.")).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(); + Panel::new(app).fx.shown().height() + }; + // #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 p = Panel::new(app("box", "hue")); + assert!(!coarse(&p)); + p.app_mut().session.begin_interaction("test").unwrap(); + p.fx.idle(2); + assert!(!coarse(&p), "the field is unchanged, so the full lines are kept"); + p.app_mut().run("paint.setFill", json!({"color": "#6efdc9"})).unwrap(); + assert!(p.app().session.in_interaction(), "the new color is part of the drag"); + p.fx.idle(2); + assert!(coarse(&p), "another hue during the drag"); + p.app_mut().session.commit_interaction().unwrap(); + p.fx.idle(2); + assert!(!coarse(&p), "found in full once the drag ends"); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index 4cdefb30fa..5ca8a2425e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -90,8 +90,9 @@ fn ui_color_wheel_sets_and_reads_the_settings() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); let settings = |view: &str, vision: bool| { json!({ - "view": view, "channel": "hue", "sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false, - "hexField": false, "contrast": false, "contrastFor": "normalText", "contrastBackground": null, "vision": vision, "documentColors": false + "view": view, "channel": "hue", "sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", + "opacity": false, "hexField": false, "contrast": false, "contrastFor": "normalText", "contrastBackground": null, + "vision": vision, "documentColors": false }) }; assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false)); diff --git a/crates/ui-egui/src/panels/tests_panel_rows.rs b/crates/ui-egui/src/panels/tests_panel_rows.rs index 15554da438..cc2174e2ee 100644 --- a/crates/ui-egui/src/panels/tests_panel_rows.rs +++ b/crates/ui-egui/src/panels/tests_panel_rows.rs @@ -117,6 +117,14 @@ fn the_appearance_swatches_and_labels_line_up() { } } +#[test] +fn the_appearance_swatches_of_neighboring_rows_do_not_touch() { + let panel = Panel::new(app_with_rect(), appearance::show); + let (stroke, fill) = (panel.rect("Stroke swatch"), panel.rect("Fill swatch")); + let gap = (fill.top() - stroke.bottom()).max(stroke.top() - fill.bottom()); + assert!(gap >= 1.0, "the stroke swatch at {stroke:?} and the fill swatch at {fill:?} touch or overlap (gap {gap})"); +} + #[test] fn the_fill_swatch_lines_up_with_a_dashed_stroke_that_has_a_profile() { let mut panel = Panel::new(app_with_rect(), appearance::show); diff --git a/crates/ui-egui/src/panels/transparency.rs b/crates/ui-egui/src/panels/transparency.rs index 3d5579e40f..193837507e 100644 --- a/crates/ui-egui/src/panels/transparency.rs +++ b/crates/ui-egui/src/panels/transparency.rs @@ -13,8 +13,9 @@ use craft::behavior::Mixed; use craft::behavior::item_source::keyed; use craft::ui::buttons::Button; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::contract::{Bind, CollectionEvent, FieldLayout, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing}; use craft::ui::display::{Divider, Shade, Text}; +use craft::ui::form::Field; use craft::ui::layout_components::{Row, Stack}; use craft::ui::list::{List, ListRow, RowEvent, ThumbSize, ThumbTarget}; use craft::ui::menu::PanelRow; @@ -247,15 +248,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut opacity = None; Row::new().show(ui, |ui, _| { Select::new(tl!("Blend Mode"), Bind::bound_mixed(&mut shown_blend).policy(EditPolicy::OnCommit), &entries).enabled(has).show(ui); - opacity = Some( - NumberField::new(tl!("Opacity"), Bind::given(op.map(|o| f64::from(o) * 100.0))) - .unit_kind(UnitKind::Percent) - .range(0.0..=100.0) - .popup_slider(0.0..=100.0) - .enabled(has) - .show(ui) - .edit, - ); + opacity = Field::new(tl!("Opacity")) + .layout(FieldLayout::Line) + .sizing(Sizing::Content) + .show(ui, |ui, _| { + NumberField::new(tl!("Opacity"), Bind::given(op.map(|o| f64::from(o) * 100.0))) + .unit_kind(UnitKind::Percent) + .range(0.0..=100.0) + .popup_slider(0.0..=100.0) + .enabled(has) + .show(ui) + .edit + }) + .inner; }); if let (Mixed::Same(b), true) = (&shown_blend, shown_blend != blend_before) { app.run("transparency.set", json!({"blend": b.label()})).ok(); @@ -493,6 +498,16 @@ mod tests { assert_eq!(values(&panel), whole); } + #[test] + fn opacity_field_has_a_visible_label_before_it() { + let mut app = new_app(); + run_cmd(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})); + let panel = Panel::new(app, show); + let field = panel.rect_role("Opacity", Role::SPIN_BUTTON); + let labels: Vec<_> = panel.texts().into_iter().filter(|(t, r)| t.trim_end_matches(':') == "Opacity" && r.right() <= field.left()).collect(); + assert_eq!(labels.len(), 1, "one Opacity label painted before the field at {field:?}: {:?}", panel.texts()); + } + #[test] fn panel_in_mask_editing_mode_shows_and_edits_the_masked_object() { let mut app = new_app(); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index bec5647de9..67a46f6c83 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1134,6 +1134,12 @@ fn is_tool(def: &CommandDef) -> bool { matches!(def.kind, CommandKind::Tool { .. }) } +/// A tool of the Tools panel: a tool in the app's scope. The tools of a workspace's own dialog +/// (Content-Aware Fill, Liquify, Select and Mask, Vanishing Point and others) are scoped to that dialog, and neither tab lists them. +fn is_app_tool(def: &CommandDef) -> bool { + is_tool(def) && def.scope.is_app() +} + /// The app's rule for the keys a command takes: a tool's shortcut is one key, alone or with Shift, /// or the tool's own default (the Quick Pen's Alt+P). fn accept(def: &CommandDef, binding: &Binding) -> Result<(), String> { @@ -1153,7 +1159,7 @@ fn options() -> Options { Options::default().with(|o| { o.area_tabs = true; o.own_areas = true; - o.areas = vec![Area::new("tools", "Tools", is_tool), Area::new("menu", MENU_COMMANDS, |def| !is_tool(def))]; + o.areas = vec![Area::new("tools", "Tools", is_app_tool), Area::new("menu", MENU_COMMANDS, |def| !is_tool(def))]; o.summary = false; o.accept = Some(Box::new(accept)); o.import_formats = vec![Format::new("kys", "Shortcut set", &["kys"]), Format::new("json", "VectorCraft shortcut set", &["json"])]; @@ -2287,6 +2293,27 @@ mod tests { assert_eq!(labels, ["Tools", "Menu Commands"]); } + /// The Tools tab lists the Tools panel's tools, each once, and none of the tools scoped to a workspace's dialog, + /// which the window's keymap also holds. + #[test] + fn the_tools_tab_lists_only_the_apps_tools() { + let (mut app, ctx) = app(); + open(&mut app); + dialog_pass(&mut app, &ctx); + dialog_pass(&mut app, &ctx); + let keymap = app.shortcuts_dialog.as_ref().and_then(|d| d.keymap.as_ref()).expect("the dialog's keymap"); + let options = options(); + let tools = options.areas.iter().find(|a| a.id == "tools").expect("the Tools area"); + assert!( + keymap.catalog().iter().any(|d| is_tool(d) && !d.scope.is_app()), + "the window's keymap holds tools of a dialog's scope, which the Tools tab must leave out" + ); + let listed: Vec = keymap.catalog().iter().filter(|d| (tools.rows)(d)).map(|d| d.command.key()).collect(); + let want: Vec = entries().iter().filter(|e| e.is_tool).map(|e| command_of(&e.key).key()).collect(); + assert_eq!(listed.iter().collect::>(), want.iter().collect::>()); + assert_eq!(listed.len(), want.len(), "each tool is listed once"); + } + /// An open dialog lists a live-effect plug-in installed while it is open, with the shortcut its /// set gives it, and drops the row while the plug-in is removed, keeping that shortcut in the /// set. diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index be89cd34c1..6f2f72d06a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -439,12 +439,14 @@ fn show_rail(app: &mut VectorcraftApp, ui: &mut Ui, owner: Owner, at: GroupAt, m let located = locate::wanted(&app.ui, &home); let holds = |tool: &str| model.slots.iter().any(|slot| slot.tools.iter().any(|t| t.id == tool)); let reveal = matches!(at, GroupAt::Show(_)).then(|| locate::take_reveal(&mut app.ui, &home, holds)).flatten(); - // The current tool in production's pressed fill, with no accent edge. + // The current tool in production's pressed fill, with no accent edge. A rail too short for its tools shows its + // scroll bar with the pointer away too, so the hidden tools can be found. let mut rail = ToolRail::new(tl!("Tools"), &model.slots, ¤t, &model.last_used) .opens(opens) .tips(&cards) .active_look(ActiveLook::Pressed) - .density(rail_density(app, &owner)); + .density(rail_density(app, &owner)) + .bar_at_rest(); if let Some(tool) = &located { rail = rail.mark(tool); } diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 5671cbe62e..2495ec4d03 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -582,3 +582,37 @@ fn the_rail_builds_its_slots_only_when_its_tool_groups_change() { let kept = app.dock_rt.rail_models.get(&Owner::Tools.panel()).map(|model| model.slots.len()); assert_eq!(kept, Some(advanced), "the rail shows the Advanced toolbar's slots"); } + +/// A window too short for the tools shows the rail's scroll bar with the pointer away from the rail: a narrow bar, +/// several times taller than wide, inside the rail's end edge. A window tall enough for every tool shows none. +#[test] +fn a_short_tools_rail_shows_its_scroll_bar_at_rest() { + let mut app = app_with(200, 200); + let ctx = reader(); + app.run("window.toolbarColumns", json!({ "double": false })).unwrap(); + let bars = |app: &mut VectorcraftApp, t0: f64, height: f32| { + let nodes = settled(app, &ctx, t0, height); + let rail = nodes.iter().find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools")).and_then(bounds).expect("the rail is drawn"); + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, egui::vec2(1200.0, height))); + let out = crate::testing::app_frame(app, &ctx, egui::RawInput { time: Some(t0 + 0.2), screen_rect, ..Default::default() }); + let mut stack: Vec = out.shapes.into_iter().map(|clipped| clipped.shape).collect(); + let mut found = 0; + while let Some(shape) = stack.pop() { + match shape { + egui::Shape::Vec(inner) => stack.extend(inner), + egui::Shape::Rect(r) => { + let b = r.rect; + let narrow = b.width() > 0.0 && b.width() <= rail.width() * 0.25 && b.height() >= b.width() * 3.0; + let at_end = rail.expand(0.5).contains_rect(b) && b.center().x > rail.center().x; + if narrow && at_end { + found += 1; + } + } + _ => {} + } + } + found + }; + assert!(bars(&mut app, 0.0, 400.0) > 0, "a short rail shows its scroll bar with the pointer away"); + assert_eq!(bars(&mut app, 10.0, 2000.0), 0, "a rail with room for every tool shows no scroll bar"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e7fa9af567..df9b36eee8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -241,11 +241,13 @@ 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 and large text and the AA result for 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 and large text and the AA result for 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 @@ -692,7 +694,8 @@ points, one or several, are refused when those points changed since the dialog o which of them pair as a discontinuous point) 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/gaps.md b/docs/gaps.md index 51775cc460..1acbfa6149 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -849,8 +849,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and - character and paragraph attributes, their links to each other and the stories they form, the installed fonts, and - each document's variables, data sets and variable libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, their links to each other and the stories they form, its character and + paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries. + 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 a5618543f6..88adc1d25f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -698,12 +698,19 @@ with a slider and a percent field sets the opacity of the fill row (`paint.setFi (`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point when none is selected), and `false` hides the row. 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. -`{"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. +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, 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. Keys left out keep their values. Params that are not an object, another key or a value off -the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity, +or the box. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or @@ -1275,7 +1282,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 @@ -1299,15 +1306,29 @@ is drawn); a picked object of a dynamic symbol instance hides only itself, and t These are errors: `"below"` with nothing selected; a "?" proxy (hidden objects count there, as in the Color panel); selected objects that draw one color with different blend modes, or at different opacities without `opacity` (with `"below"`, also in different groups or layers that are translucent, have a blend mode or isolate their blending, or -with a translucent or blending row over different shown rows below it), where hidden objects do not count, and the +with a translucent or blending row over different shown rows below it, or over a shown row that blends in objects +that differ in isolating their blending), where hidden objects do not count, and the error names `opacity` when giving it settles the difference; a proxy of None, a pattern or a hidden row without `color`; and without `color`, a proxy's object drawn through an opacity mask that is not disabled, its own or that of a group, layer or instance -around it, since the mask sets how much of the color shows at each point. `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 rows below it: there `"below"` reads the art below each such level, and a given background stands for that art. -Headless MCP answers it too. +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, 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. 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 @@ -2800,7 +2821,10 @@ shorthand and computed property names in object literals, and classes with `exte computed method names, `super` calls and properties and `new.target` (https://262.ecma-international.org/11.0/). `new.target` in a string given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`; at the top of a script, in an arrow function at the top of a script and through an indirect -`eval` it is a `SyntaxError`. A +`eval` it is a `SyntaxError`. In the same way, a string given to direct `eval` may use `super.name` and `super[key]` +inside a method, accessor or class constructor, and `super(…)` inside a derived class's constructor, also from an +arrow function within one; elsewhere, through an indirect `eval` and in a `Function` body they are a `SyntaxError` +(https://262.ecma-international.org/6.0/#sec-performeval). A class can extend a class, a function, `null` or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types. A class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is @@ -3080,6 +3104,33 @@ other files through `$`: string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `characterOffset` and `orientation` cannot be set yet. +- `Document.characterStyles` and `Document.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, + https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/) list the document's styles with `length`, `[i]`, + `index(key)`, `getByName(name)`, `add(name)` (`charStyle.new` or `paraStyle.new` with no attributes) and + `removeAll()` (`charStyle.delete` or `paraStyle.delete` of every style but the Normal style). A `CharacterStyle` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/) has `name` (`charStyle.rename`), `parent`, + `characterAttributes`, `applyTo(text, clearingOverrides?)` (`charStyle.apply`) and `remove()` (`charStyle.delete`); + a `ParagraphStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/) has the same members with + `paragraphAttributes` and the `paraStyle` commands. A style's attributes are those of a text range's + `characterAttributes` and `paragraphAttributes`, with the same ranges, and setting one runs `charStyle.setAttrs` or + `paraStyle.setAttrs`. `TextRange.characterStyles` and `TextRange.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) list the styles the range's text is in, with `length`, + `[i]`, `index(key)` and `getByName(name)`. A script loads styles from another document with `vc.run` and + `charStyle.load`, `paraStyle.load` or `textStyle.loadAll`, from a file the script may read. + VectorCraft's own rules: a document's list starts with `[Normal Character Style]` or `[Normal Paragraph Style]`, + followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. + An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the + style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the + style's document; a character style on an empty range inside text changes nothing, on empty text it styles the + text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left + out is false. A range lists each style once, in the order + its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove + styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made + through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws + `Stale style`. + One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not + available yet. - Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a `TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end), @@ -3130,6 +3181,29 @@ other files through `$`: `importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs no command. +- `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method + of the scripting reference + https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf + describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the + app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own + steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and + Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to + Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run + started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one + past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to + Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's + own rules: the action and its set are matched by their exact names, and a name that matches no action or more than + one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any + step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an + action cannot play itself. + Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts + as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an + error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an + uncaught error later puts them back with the rest of the run. `dialogs` must be `true` or `false` (default + `false`); no step opens a dialog, so it changes nothing. `app.loadAction` and `app.unloadAction` throw an error + that says they are not available yet when they are read or assigned. - `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each `Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page @@ -8914,9 +8988,12 @@ the corners where they are records none. Image info (`image.info`) gives a disto Info (`links.info`) gives its scale and rotation there. Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`) and Place with Replace -(`file.place` with `replace`) of anything but a text file refuse a -distorted image with an error that names the distortion; Place with Replace does not refuse a clipping group that holds -a distorted image of a DCS file's plates. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is +(`file.place` with `replace`) of a file that is not text, a raster image or a DCS file refuse a distorted image with an error that names the distortion; Place with Replace does not +refuse a clipping group that holds a distorted image of a DCS file's plates. Place with Replace of a distorted image by +a raster image or a DCS file puts the new image's pixels between the old image's corners, in one undo step; the new +image's transform is the old one scaled to the new pixel size, the clipping path a PSD, PSB or DCS file names is +drawn through the corners, and each slice a PSD or PSB file brings in covers the box around its part of the pixels +where the corners put it. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is given and lists each distorted image it leaves as it is in `skipped`, with its `id` and the error as `reason`; with nothing else to convert, it returns that error. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or @@ -9057,10 +9134,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) 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. `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 +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 +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. Double-clicking one with Direct Selection opens Corners (`ui.corners {id?, corners?}`, dialog `corners`: `kind`, `radii`, `radius`, a percentage of each corner's own maximum while `radii` is `relative`; OK runs @@ -14704,7 +14791,8 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The 64 MB limit also applies to `data` and to the +decoded bytes of `dataBase64`; a `dataBase64` string too long to decode to 64 MB or less is refused before it is decoded. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/roadmap.md b/docs/roadmap.md index 158326df56..964050ddc1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -206,7 +206,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) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 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, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; 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), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), 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 5d817693c9..989020e38e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -862,9 +862,10 @@ 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`. - **A press inside a selected group** (VectorCraft's own rule): with Direct Selection, a path inside a selected group counts as selected whole. A click on its fill keeps the group selected, a drag from its fill or one of its anchors moves the group whole, and a click on an anchor or a segment selects it alone. The path's anchors show the selected-anchor cursor and highlight, and an object above the group does not take a press on one. Group Selection adds the group above the outermost selected one. This also applies to the Cmd/Ctrl press the Selection tool lends Direct Selection. Test: `direct::tests::a_press_inside_a_selected_group_keeps_the_group`. - **A Shift-click inside a selected group** (VectorCraft's own rule): with Direct Selection, a Shift-click on the fill of a path inside a selected group deselects that path, and the group's other objects stay selected (`select.remove`); a Shift-drag from there moves nothing. A Shift-click on one of the path's anchors deselects only that anchor, and the path's other anchors and the group's other objects stay selected. Tests: `direct::tests::a_shift_press_inside_a_selected_group_deselects_the_path`, `selection_commands::remove_and_anchor_toggle_open_a_selected_group`, `selection::tests::expand_to_selects_a_member_in_place_of_its_selected_group`. +- **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). @@ -1115,13 +1116,15 @@ 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: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`. @@ -1182,7 +1185,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Check Script reports `file.write` and `filesWritten` when a script sets a File object's `length`, `hidden` or `readonly` (https://extendscript.docsforadobe.dev/file-system-access/file-object/), by plain or compound assignment, `++` or `--`, or the name as a string literal in brackets. It leaves out only objects that are always Folder objects, `new Folder(…)` and the `Folder` places such as `Folder.temp` other than `Folder.current`, which a script can assign; `Folder(…)` gives a File object when the path names a file and `Folder.selectDialog()` gives a File or Folder object (https://extendscript.docsforadobe.dev/file-system-access/folder-object/), so setting those counts, as it does on a variable that any assignment, in any branch or included file, gives such an object. Nothing counts as a Folder object in a check whose files use `with`, name `eval`, `Function`, `evalFile` or `constructor` as a word or as a string literal in brackets (`this['eval'](s)`, `(function () {}).constructor(s)`), read, call or assign a property in brackets on any object (a `[` after a value, not an array literal) when the brackets hold anything but one number or string literal (`g[k] = …`, `$['global'][k] = …`, `this[k](s)`, `this['ev' + 'al'](s)`, `this[('eval')](s)`, `this[0, 'eval'](s)`, `$[k](f)`, `(function () {})[k](s)`, or a preprocessor line inside the brackets) or the `[` opens while 4,096 other `[` are open, assign a property in brackets whose name is a string literal of more than 256 characters, assign properties of more than 1,000 different names on members, or assign or declare `Folder`, and a variable whose name a member assignment writes (`$.global.d = …`, `this.d = …`, `this['d'] = …`, with the string's escapes undone) counts as one that may hold a File object (`setting_a_folders_length_or_flags_does_not_write`, `a_variable_that_may_hold_a_file_counts_as_one`, `a_file_in_a_local_variable_leaves_an_outer_folder_alone`, `a_folder_that_other_code_may_rebind_counts_as_a_file`, `a_folder_that_unnamed_code_may_rebind_counts_as_a_file`, `a_bracketed_name_is_read_whole_or_counts_as_any_name`, `a_bracketed_variable_read_counts_as_any_name`, `a_bracketed_joined_name_counts_as_any_name`, `a_bracketed_name_in_parentheses_counts_as_any_name`, `a_bracketed_comma_expression_counts_as_any_name`, `a_bracketed_variable_call_on_dollar_counts_as_any_name`, `a_bracketed_variable_constructor_counts_as_any_name`, `a_literal_name_in_brackets_leaves_the_folder_alone`, `a_directive_in_a_bracketed_name_counts_as_any_name`). On the same Folder objects, calls of the File-only functions `open`, `read`, `readch`, `readln`, `write`, `writeln`, `copy`, `createAlias`, `openDlg` and `saveDlg`, which a Folder object does not have, count as no file read, write or dialog; `create`, `remove`, `rename`, `getFiles` and `selectDlg` still count (`file_only_calls_on_a_folder_do_nothing`). A test lists every global and member the script host adds to the JavaScript engine, except VectorCraft's own `vc` and its members, and fails when one has no row; for each one that reaches outside the document it checks that `script.check` reports the expected `outside` id, and it checks that the checker lists every directive the host reads. Tests: `crates/scriptcheck/src/tests.rs` (`setting_a_files_length_or_flags_writes_it`), `crates/engine/tests/it/script_host_vs_scriptcheck.rs` (`every_name_the_host_adds_has_a_row`, `every_name_that_reaches_outside_has_its_checker_id`, `the_checker_lists_every_directive_the_host_reads`). - `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. A comma may follow the last argument of a call or `new` expression and the last parameter of a function other than a setter, as ECMAScript 2017 allows (https://tc39.es/ecma262/2017/#sec-left-hand-side-expressions, https://tc39.es/ecma262/2017/#sec-function-definitions); `f(,)` and `f(1,,)` give a `SyntaxError`. 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`. + - `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,676 of 4,682 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 uses the iterator protocol (see the `for`-`of` line below). 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. Modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: when these forms were added, 390 of 390 negative parse runs and 565 of 589 other runs passed with it (373 and 27 without it), and the 24 failing runs expected function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions. The object-literal line below adds function names and configurable lengths; the `caller` and `arguments` restrictions are still not implemented. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. The collector retains tagged-template cache entries only while the site's code is reachable. - With `Options::es2015`, `vectorcraft-js` also reads and runs classes (https://262.ecma-international.org/6.0/#sec-class-definitions): declarations, scoped to their block like `let`, and expressions, with `extends`, `static` members, getters and setters, generator methods, and computed method names, Symbols included; class code is strict mode code, methods are not enumerable and cannot be constructed, and calling a class without `new` throws a `TypeError`. A derived constructor's `this` is unusable until `super(…)` returns (a `ReferenceError`), and its own default constructor passes its arguments on. `super.name` and `super[key]` read, call and write through the prototype of the method's home object with `this` as the receiver, in class methods and in methods and accessors written in object literals, which are enumerable, computed names included. A class takes its own name, or the name it is assigned to, and each method takes the name of its key (`get ` or `set ` before an accessor's, a Symbol's description in brackets). `new.target` names the constructor `new` was applied to, in functions and the arrow functions inside them. A class can extend `null`, a function, a class, or the built-in constructors `Object`, `Function`, `Array`, `String`, `Number`, `Boolean`, `RegExp`, `Date` and the error types; a class can name another built-in constructor in `extends`, but `new` on that class throws a `TypeError` when it reaches the built-in constructor, a rule that is VectorCraft's own. Each class and method takes fuel, and deep chains of constructors stop at the frame limit. `new.target` in code given to direct `eval` inside a function, or inside an arrow function within one, reads that function's `new.target`, and outside a function it is a `SyntaxError`; `super` in code given to direct `eval` is not supported yet. `cargo xtask test262` runs the `class`, `super` and `new.target` tests with the other ES2015 forms. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`. @@ -1190,12 +1193,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - `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), `Boolean`, which converts a value when called and makes a Boolean object with `new` (15.6), 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: 7,000 of 7,070 runs pass (the 35 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,421 of 1,453 pass for `String`, 304 of 304 for `Number`, 962 of 996 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`. - - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,266 of 1,514 runs pass, and the 248 others expect a configurable function `length` and a function `name` property. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. + - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Map`, `Set`, `WeakMap` and `WeakSet`, and `ArrayBuffer`, `DataView` and the nine typed arrays from `Int8Array` to `Float64Array` with `%TypedArray%.from`, `of` and the prototype methods (ECMA-262 6th edition, sections 22.2 to 24.2, https://262.ecma-international.org/6.0/); a realm without it, the ExtendScript realm included, has none of these names. `Map` and `Set` compare keys with SameValueZero, keep insertion order, and a `forEach` or an iterator's `next()` skips entries deleted before it reaches them and visits entries added during the walk. A `WeakMap` entry does not keep its key alive: the collector drops the entries of unreachable keys, also when the value refers back to its key. Typed arrays store their elements little-endian and `DataView` reads and writes big-endian unless `littleEndian` is true. A numeric property name of a typed array is an element or nothing, and its elements are writable, enumerable and configurable but cannot be deleted, as later editions define them. An `ArrayBuffer` longer than 2^32 - 1 bytes or than the heap limit gives a `RangeError` before anything is allocated, and every element a method visits takes fuel. `Map`, `Set` and the typed arrays are iterable, and their iterators inherit `%IteratorPrototype%`. The collection constructors read their argument through its `@@iterator` method and close the iterator when adding an entry throws (sections 23.1.1.1, 23.2.1.1, 23.3.1.1 and 23.4.1.1), so an object without `@@iterator` is a `TypeError`, and so is a `Map` or `WeakMap` entry that is not an object. A typed array constructor given an object that is not a buffer or a typed array, and `%TypedArray%.from`, read a source with an `@@iterator` method through its iterator to the end before mapping it, and any other source as an array-like object, by index (sections 22.2.1.4 and 22.2.2.1); a typed array constructor converts a first argument that is not an object to a length. Check Script counts `new` of these constructors as the language's, not as document-model types. `cargo xtask test262` runs the suite's tests of the eight `built-ins` folders that need only these built-ins in such a realm: 1,514 of 1,514 runs pass. The `TypedArray` folder's tests include a harness file that uses `Symbol` and `Array.from`, so they are skipped. Tests: `crates/js/src/collections_tests.rs`, `crates/scriptcheck/src/tests.rs` (`collections_and_typed_arrays_are_not_type_names`), `crates/js/tests/test262.rs`. - Scripts: a script run from a `.js` file has `Promise` as ECMA-262 11th edition section 25.6 defines it (https://262.ecma-international.org/11.0/#sec-promise-objects): the constructor, `then`, `catch`, `finally`, `Promise.resolve`, `reject`, `all`, `allSettled` and `race`; `.jsx` scripts keep the ES5.1 built-ins only (`Options::es2015` in `vectorcraft-js`), except in a named engine (`#targetengine`) that a `.js` script has run in, which keeps `Promise` from that run on. The callbacks run as jobs in the order they were queued after the script's own code ends and before the run ends, on the run's fuel and limits with 1 unit of fuel for each job, and with no native recursion along a `then` chain, so an endless chain stops at the fuel limit. More than 1,048,576 waiting jobs end the run with a `Jobs` limit error, and a run that fails or is stopped drops its waiting jobs and rolls back as before. A rejection still unhandled at the end goes to the report's `unhandledRejections` and to the Script Console with its file, line and column when known. For rejections from code compiled by `eval` or `Function`, the `script.run` report omits the file and sets the line and column to 0. `all` and `race` preserve an input rejection's known location; calling a saved reject function from script uses that call's location. `all`, `allSettled` and `race` read `Symbol.iterator`, including user-defined iterables and overridden array iterators; string iterators keep surrogate pairs together, and objects with only a whole-number `length` reject with a `TypeError`. A failure while processing a yielded value closes the iterator with `return` when present, preserving the original exception if closing throws; a step that throws or finishes is not closed. The statics always make plain `Promise` objects (VectorCraft's own rule). `cargo xtask test262` runs the suite's `built-ins/Promise` tests whose feature tags name only `Promise`, `Promise.allSettled` and `Promise.prototype.finally` and whose code parses and needs only the built-ins present, asynchronous tests included: 440 of 538 runs pass, where none ran before. The 98 others expect the statics to build their result with another constructor passed as `this`, `then` to read `constructor`, or a configurable `length` and an own `name` on the resolve and reject functions a promise passes to its executor. `Promise.any` is not provided. Tests: `crates/js/src/promise_tests.rs`, `crates/js/tests/test262.rs` (`promise_builtins_run`), `crates/engine/src/tests/script_include.rs` (`a_js_script_has_promise_and_a_jsx_script_does_not`, `a_named_engine_gets_promise_at_its_first_js_run_and_keeps_it`, `unhandled_rejections_reach_the_report_and_the_console_with_their_file_and_line`). - With `Options::es2015` set, which it is not by default, a `vectorcraft-js` realm also has `Symbol` (ECMA-262 11th edition, section 19.4, https://262.ecma-international.org/11.0/): `Symbol(description)`, which `new` refuses with a `TypeError`, the `description` getter, `toString`, `valueOf`, and `Symbol.for` and `Symbol.keyFor` over a registry that lasts as long as the realm. `typeof` gives `"symbol"`. Symbols are property keys: `Object.getOwnPropertySymbols` lists an object's Symbol keys in the order they were added, `Object.defineProperty`, `getOwnPropertyDescriptor`, `freeze`, `seal`, `in`, `delete` and `hasOwnProperty` take them, and `for`-`in`, `Object.keys`, `Object.getOwnPropertyNames` and `JSON.stringify` leave them out. `String(symbol)` and `symbol.toString()` give `Symbol(description)`; any other conversion of a Symbol to a string or a number, such as `Symbol() + ''`, throws a `TypeError`. A string such as `'0b10'` or `'0o2'` converts to a number, as section 7.1.3.1 gives. The well-known Symbols `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.toPrimitive` and `Symbol.toStringTag` are defined: conversion to a primitive calls an object's `@@toPrimitive` method, `instanceof` calls the right side's `@@hasInstance` method, and `Object.prototype.toString` writes a string `@@toStringTag`; `JSON.stringify` calls a String or Number object's `@@toPrimitive` method too. `Date.prototype[Symbol.toPrimitive]` (section 20.4.4.45) converts a Date with `toString` first for the hints `"string"` and `"default"` and with `valueOf` first for `"number"`, so `date + 1` joins the date's string; an object without an `@@toPrimitive` method, a Date whose method is `null` included, tries `valueOf` first when no hint is given. Nothing reads `Symbol.asyncIterator` yet. `Array.prototype.values` (also `Array.prototype[Symbol.iterator]`), `keys` and `entries`, `String.prototype[Symbol.iterator]` and every `arguments` object's `Symbol.iterator` return iterators whose `next()` gives `{value, done}` objects; a string iterator steps by code point and keeps a surrogate pair together. An array iterator reads the `length` at each step, so it visits elements added during the walk. Each step takes fuel, as does each prototype a Symbol-keyed lookup passes, and each Symbol and registry entry counts against the heap limit. A realm made without the option, including one a `.jsx` script starts in the app, has none of these names, and `Realm::set_es2015` changes only the syntax later runs read, so a realm keeps the built-ins it was made with (an engine that `#targetengine` keeps after a `.js` script made it has them in later `.jsx` runs too); a host function that returns a Symbol while the option is off throws a `TypeError`. `for`-`of`, spread and array destructuring call `next()` (see the next line). `cargo xtask test262` runs the suite's tests of `Symbol`, `ArrayIteratorPrototype`, `StringIteratorPrototype`, `Object.getOwnPropertySymbols`, `Array.prototype.values`, `keys`, `entries` and `Symbol.iterator`, and `String.prototype[Symbol.iterator]` that need only these built-ins and parse as ES5, in such a realm: when these built-ins were added, 164 of 216 runs passed (6 passed before), and the 52 others expected a configurable function `length` and a function `name` property, which the object-literal line below adds. Tests: `crates/js/src/symbol_tests.rs`, `crates/js/tests/test262.rs`. - With `Options::es2015`, `vectorcraft-js` also reads and runs `for`-`of` loops and destructuring (ECMA-262 11th edition, sections 13.7.5, 12.15.5 and 13.3.3, https://262.ecma-international.org/11.0/). `for`-`of` takes `var`, `let` and `const` declarations, patterns and any assignment target, gives a `let` or `const` loop a new binding for each iteration, and calls the iterator's `return` method, when it has one, when `break`, `continue` to an outer loop, `return` or an exception leaves the loop early; an iterator whose `next()` threw or said it was done is not closed, and an exception on its way out wins over one that `return` throws. Array patterns step the iterator with holes, defaults and a rest element, and close it when they stop before its end. Object patterns read names, string and number keys and computed keys, with defaults. Patterns work in `var`, `let` and `const` declarations, assignments (with any assignment target as a leaf, such as `[o.a, o["b"]] = …`), function and arrow parameters, and `catch` clauses, and nest. A default runs only when the value is `undefined`. Destructuring `undefined` or `null` throws a `TypeError`. Object literals also take shorthand properties (`{ a }`) and computed names (`{ [k]: v }`, `get [k]()`), Symbol keys included. Object rest properties (`{ a, ...rest }`, ECMAScript 2018) are syntax errors. In a realm made without the option that `Realm::set_es2015` later switches to it, which has no `Symbol.iterator` (an engine that `#targetengine` keeps after a `.jsx` script made it), `for`-`of`, spread and array patterns walk arrays, `arguments` objects and strings by code point, and other values are a `TypeError`; that rule is VectorCraft's own. Each step takes fuel, a rest element counts against the heap limit, and nested patterns count against `Options::max_depth`. `cargo xtask test262` reads the suite's tests under `language/statements/for-of`, `language/expressions/assignment/dstr` and the `dstr` folders of `var`, `let`, `const`, `function`, function expressions, arrow functions, `try`, `for` and `for`-`in` whose feature tags this engine has: when these forms were added, 609 of 617 runs passed (529 before, most of them negative parse tests), and the 8 others expected a function given as a default to take the name of its binding, a `name` property the object-literal line below adds. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - With `Options::es2015`, `vectorcraft-js` object literals also take methods (`m() {}`, with a computed name too; ECMA-262 2015 section 14.3, https://262.ecma-international.org/6.0/), and `__proto__: value` with a written-out name sets the new object's prototype to an object or `null` (section B.3.1). A second `__proto__: value` in the same literal is a syntax error unless the literal is read as a destructuring pattern, and a computed or shorthand `__proto__` is an ordinary property. A method cannot be a destructuring target. Methods, getters and setters have no `prototype` and cannot be constructed. Functions get the `name` property of section 9.2.11, not writable, not enumerable and configurable: their own name, or the name of the `var`, `let` or `const` binding, default parameter, default value of a destructured name, identifier assignment or property an anonymous function or arrow is first given to (with `get ` or `set ` for an accessor, and a Symbol key's description in brackets), `bound ` and the target's name from `bind`, `anonymous` from `Function`, and an own empty `name` otherwise, as the 12th edition gives it (https://262.ecma-international.org/12.0/, section 20.2.4.2). Function `length` properties are configurable (section 19.2.4.1), and the built-in functions get their names and configurable lengths the first time a realm reads code with the option, keeping them after it is turned off. Without the option the new forms are syntax errors and functions get no `name`. `cargo xtask test262` now also reads the suite's `expressions/object` and `computed-property-names` folders, the `Function` built-in tests and the function `name` tests: with the option, 458 of 458 negative parse runs and 1,751 of 2,196 other runs pass, against 456 of 458 and 1,504 of 2,200 without this change (the runner selects 1,422 tests with this change and 1,426 without it). The `for`-`of` and destructuring runs go from 3,344 to 3,572 of 3,644 and the `Symbol` and iterator runs from 178 to 230 of 230, since the runs that expected function `name` properties and a configurable function `length` now pass. Of the 445 failing runs of the subset, 428 do not parse because the tests also use forms that are not added (classes in most of them, generators, `super`, trailing commas in parameter lists, binary and octal number literals, and forms of later editions), and 17 expect integer keys listed before other keys, the `caller` and `arguments` restrictions of later editions, `Number.MAX_SAFE_INTEGER` and a harness file the runner does not load. Tests: `crates/js/src/es2015_object_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,267 of 1,287 runs of 668 tests pass. Of the 20 others, 16 do not parse because the tests also use classes, and 4 expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. + - With `Options::es2015`, a `vectorcraft-js` realm also has generators (ECMA-262 11th edition, sections 14.4 and 25.4, https://262.ecma-international.org/11.0/): `function*` declarations and expressions, `*name() {…}` methods in object literals (with a computed name too), `yield`, and `yield*`, which passes `next`, `throw` and `return` on to the iterator it delegates to and closes an iterator without `throw` before it throws a `TypeError`. A generator object's `next`, `return` and `throw` come from `%GeneratorPrototype%`, which inherits from `%IteratorPrototype%`; `return` runs the `finally` blocks around the `yield`, `throw` raises the value there, and resuming a generator while its body runs throws a `TypeError`. `%GeneratorFunction%` builds a generator function from source as `Function` does, and is reached through a generator function's `constructor`. A generator function, a generator method included, has a `prototype` and is not a constructor. In sloppy code outside a generator function's body and parameters, `yield` stays an identifier, and a realm without the option reads `function*` as a syntax error. A suspended generator keeps its frame and operands in its object, which the collector keeps while the object is reachable and frees with it. A resumption pushes that frame on the interpreter's frame stack and takes fuel, so a generator driven from a script uses no native stack, and a deep `yield*` chain stops at the frame limit. A realm made without the option that reads the syntax later has no generator built-ins, and calling a generator function there throws a `TypeError`. `script.run` runs generators in a `.js` script. `cargo xtask test262` runs the suite's tests under `language/statements/generators`, `language/expressions/generators`, `language/expressions/yield`, `built-ins/GeneratorPrototype` and `built-ins/GeneratorFunction` that need only the built-ins present, in such a realm: 1,285 of 1,289 runs of 669 tests pass. The 4 others expect the `caller` and `arguments` restrictions. Tests: `crates/js/src/generator_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`. - Scripts: `cargo xtask corpus --scripts` fetches 397 public scripts and 1 file they include from 19 MIT and Apache-2.0 repositories at pinned commits into `corpus/scripts` (gitignored), each repository's license file beside its scripts. `xtask/script-corpus.txt` lists every file with its size and SHA-256, and a download is checked against both before it replaces anything; one more candidate is left out because it is over the 1 MiB limit for one script. `cargo xtask scripts --pass-rate [--report ]` runs each script headless in a process of its own (a new document, 5,000,000 instructions, no dialog answers, file reads only in its repository's folder and a new folder of its own, file writes only in that folder, no command it can start, stopped after 10 seconds) and writes a JSON report: the pass rate overall, per repository and for the scripts without dialogs or windows, how many parse, and each script's outcome. Script failures never fail the command, and without the corpus it skips. These limits are VectorCraft's own. Tests: `xtask/src/script_corpus.rs`, `crates/engine/tests/script_corpus.rs`. - With `Options::e4x` set, an E4X name standing alone (`@a`, `@ns::a`, `@[expr]`, `ns::a`, `*`) inside `with` or a filter predicate can be assigned, with `=` or a compound operator, incremented, decremented, deleted and used as a `for` or `for each` variable, as well as read. Each of these uses the nearest XML or XMLList value in scope that holds the name and evaluates the name once. When no XML value in scope holds the name, the read or write throws a `ReferenceError` before the right-hand side runs and creates no child or attribute, as ECMA-357 section 11.1 (https://ecma-international.org/publications-and-standards/standards/ecma-357/) specifies, so a filter such as `list.(@id == '1')` throws when an item has no `@id` and no outer XML value holds one. Tests: `crates/js/src/xml_tests.rs`. - `vectorcraft-js` runs ECMAScript for XML (ECMA-357, 2nd edition, https://ecma-international.org/publications-and-standards/standards/ecma-357/) when `Options::e4x` is set, which it is not by default: XML and XMLList literals with embedded `{}` expressions, the `..`, `.@`, `.*`, `.()` and `::` selectors, assignment and `delete` on selected nodes, `for each`, `default xml namespace`, and the `XML`, `XMLList`, `Namespace` and `QName` objects with their methods and settings. `xml.xpath(expression[, variables])` evaluates an XPath 1.0 expression (https://www.w3.org/TR/1999/REC-xpath-19991116/) with all 13 axes and the 27 core functions, and returns the selected nodes as an XMLList in document order without repeats. Each property of `variables` binds the variable of its name, an XMLList runs the expression on each of its elements in turn, and a prefix in a name test resolves through the context element's in-scope namespaces. An expression that breaks the grammar gives a `SyntaxError`; an unknown function, a wrong argument count, an unbound prefix or variable, and a result that is not a node-set or that holds the root or a namespace node give a `TypeError`. `id()` selects nothing, and evaluation uses no native stack, takes fuel and counts against the heap limit. `` in an XML string gives a `SyntaxError`. An XML declaration at the start of an XML string, after optional white space, is checked against XML 1.0's grammar (https://www.w3.org/TR/xml/#NT-XMLDecl): a version of `1.` and digits, then an optional encoding name and an optional standalone `yes` or `no`, in that order; any other declaration, or one with a character XML does not allow, gives a `SyntaxError`. The parser takes fuel for the length of every name, white space run and declaration it scans, and for the text it searched when a quote, CDATA section, comment or processing instruction is not closed. Parsing, serializing, comparing and copying trees use no native stack, and each takes fuel and counts against the heap limit. Inserting a node into itself or its descendants throws a `TypeError` before the tree changes, a literal or XML string nested past `Options::max_depth` gives a `SyntaxError`, and a tree built past that depth stops at the heap limit. Tests: `crates/js/src/xml_tests.rs`. @@ -1321,8 +1324,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image and the placed file is not text, a raster image or a DCS file, so it does not refuse when the replaced object is a DCS file's plates); Update Links, Relink and Place with Replace of a raster image or a DCS file put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::place_with_replace_keeps_a_distorted_images_corners`, `dcs::place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners`, `cmd::fileio::tests_psdslices::slices_placed_over_a_distorted_image_follow_its_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - Perspective Distort and Free Distort (`object.distort`) put the corners of a type object's box and of a symbol instance's box exactly where the warp takes them, alone or with other objects; the object stays type or a symbol instance and is drawn through the warp, after any perspective projection it had, as type and symbols in perspective are, with the images in a symbol's art and their linked masks drawn in perspective between the corners the projection gives them; and corners that would fold its box over, carry it past the warp's horizon or lie too close together for a perspective map are refused with an error that names it, as is a perspective warp of type that Edit Text shows flat. VectorCraft's own rule (engine `xform::distort_puts_the_corners_of_type_and_symbol_instances_on_the_handles`, `distort_moves_type_and_symbol_instances_with_a_path_as_one`, `distort_refuses_corners_type_and_symbol_instances_cannot_follow`, `distort_refuses_type_being_edited_flat`; effects `group::tests::a_projection_puts_the_corners_of_the_images_in_a_symbols_art_where_it_takes_them`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - Object › Create Object Mosaic on an image changed by Perspective Distort or Free Distort places each tile's cell of pixels between the image's corners, so the tiles are four-sided shapes that follow the perspective, in one undo step; a new size scales them from the top left of the image's bounds, and the spacing and Use Ratio measure a pixel by the mean length of the image's two sides along each axis (VectorCraft's own rule; engine `object_mosaic_tiles_of_a_distorted_image_follow_its_corners`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). @@ -1630,7 +1633,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`). Shift pressed once a drag from an anchor (or a spine point) is under way keeps the handles it pulls out at 45° steps round the anchor from the Constrain Angle, as the Pen does when it pulls out handles ([Pen, Curvature and Pencil help page](https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html)), and releasing Shift frees them. 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 with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), 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 with Direct Selection for the Corners dialog ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)) or with the Selection tool for the Transform panel (a double-click on a selected live shape's corner widget shows the Transform panel, [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html); which tool gives which is VectorCraft's own rule), 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. With the pointer on a Direct Selection corner widget or close to it, the canvas marks the cut of that widget's corner with a thicker line (#1232). The help page describes this marking of a widget's corner while the pointer is on the widget or close to it ([Live Corners help page, archived](https://web.archive.org/web/2016id_/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html)). As VectorCraft's own rules, the mark also shows with the Selection tool and the shape tools on the widgets they show, it is a 2 px line of the layer color within 5 px of the widget, a square corner gets none, and none is drawn while a mouse button is down. Tests: `corners::tests::a_widget_under_the_pointer_gives_its_corners_cut`, `corners::tests::a_square_corner_gives_no_cut_and_a_plain_paths_corner_gives_its_own`, `corners::tests::a_polygons_widget_gives_its_cut_and_a_hidden_widget_gives_none`, `canvas::widgets::tests::hovering_a_corner_widget_highlights_its_corner`. - **Corners link:** the Control bar and the Properties panel have a Corners link beside the radius field, which opens the Corners pop-up with the corner kind, the radius and the type of rounding of the selected corners; [the archived help page](https://web.archive.org/web/20200308215011/https://helpx.adobe.com/illustrator/using/reshape-with-live-corners.html) describes the link and these three settings. The pop-up picks corners across every selected path, names the rounding Relative or Absolute, shows the radius blank while the picked corners differ and no rounding while their paths differ, sets a typed value on the picked corners alone, and makes each change one undo step; these are VectorCraft's own rules (`the_corners_link_opens_the_settings_of_the_picked_corners`, `the_corners_pop_up_sets_picked_corners_across_paths`, `the_control_bar_corners_link_opens_the_pop_up_for_the_picked_corners`, `relative_rounding_without_live_corners_adds_no_undo_step`, `a_relative_radius_that_stores_the_same_fraction_adds_no_undo_step`; part of #1232). @@ -2148,6 +2151,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). 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 row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {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}`; `oklch()` only while the active document's 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. 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 (AA only for 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 (AA only for 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}`). **Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index a2adfd855e..26c7a55ce7 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -279,7 +279,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, Direct Selection 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; a double-click on a selected live shape's corner widget shows the Transform panel ([Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)) and a Direct Selection double-click opens Corners ([Create and modify live shapes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)); giving the Transform panel to the Selection tool and Corners to Direct Selection is VectorCraft's own rule; 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, Direct Selection 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); a double-click on a selected live shape's corner widget shows the Transform panel ([Live shape properties](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)) and a Direct Selection double-click opens Corners ([Create and modify live shapes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/create-and-modify-live-shapes.html)); giving the Transform panel to the Selection tool and Corners to Direct Selection is VectorCraft's own rule; 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)) |