Merge main into fix/speed-i13929-dimmed-rows

# Conflicts:
#	crates/ui-egui/src/menus/model.rs
This commit is contained in:
dotCooCoo committed 2026-11-28 19:59:05 -08:00
commit 475ea6da12
93 files changed
+3971 -398

No files matched your search

+2
View File
@@ -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
+9 -1
View File
@@ -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",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 235 KiB

After

Width:  |  Height:  |  Size: 121 KiB

+151
View File
@@ -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
/// (<https://bottosson.github.io/posts/oklab/>) 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<f64> = (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]);
+1
View File
@@ -851,6 +851,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{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};
+320 -72
View File
@@ -151,7 +151,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
@@ -1032,7 +1032,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<Pass>,
/// 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<Color> {
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<Value> {
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<Backdrop> {
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<Color>, Backdrop)> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
@@ -1044,23 +1266,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
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) => {
@@ -1096,60 +1323,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
// 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::<Vec<_>>();
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
@@ -1232,7 +1450,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| {
@@ -1248,10 +1467,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()
@@ -1263,8 +1498,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<Color>, Drawn), String> {
let stroke = !s.fill_active;
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
if if stroke { stroke_mixed } else { fill_mixed } {
@@ -1320,20 +1556,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
@@ -1398,19 +1642,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, 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
@@ -1455,14 +1701,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
/// 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();
@@ -1591,8 +1837,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 {
@@ -1602,10 +1850,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.
+13 -5
View File
@@ -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<CommandSpec> {
let mut v = style_cmds!(
@@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
_ => "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 {
+21
View File
@@ -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]
+3
View File
@@ -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<u64, u64>,
/// 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
+16 -5
View File
@@ -196,19 +196,24 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
return f(h);
}
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
let styles = text::styles::mark(h);
let mark = h.growth_mark();
h.dom.saving.set(true);
let r = f(h);
h.dom.saving.set(false);
let mut s = h.session.borrow_mut();
if r.is_ok() {
save.keep(&mut s);
} else {
{
let mut s = h.session.borrow_mut();
if r.is_ok() {
save.keep(&mut s);
return r;
}
h.put_growth_back(mark);
if !save.restore(&mut s) {
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
}
// Style objects are put back with the documents.
text::styles::put_back(h, styles);
r
}
@@ -786,6 +791,11 @@ fn on_doc<T>(
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<Data, HostError> {
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";
@@ -2746,6 +2756,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
("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()
+5 -2
View File
@@ -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<u64>,
/// The span of each range object, by its number, whose `length` the script set.
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
/// 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<HostClass> {
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<HostClass> {
None,
),
];
out.extend(styles::classes(l));
out.extend(stories);
out
}
+802
View File
@@ -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
//! <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.
//!
//! 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<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
/// The styles a run's style objects name; an object holds its slot's number.
#[derive(Default)]
pub(super) struct StyleState {
slots: RefCell<Vec<Slot>>,
seen: RefCell<Vec<Seen>>,
}
/// 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<Seen>,
}
/// 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<TextStyleDef> {
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<String> {
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<Style, HostError> {
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, HostError> {
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<String, HostError> {
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<Data, HostError> {
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<Span, HostError> {
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<String, Value>), 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<String, Value>) -> 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<String, Value>, attrs: Map<String, Value>) -> 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<dyn Fn(&Host, &[Data]) -> 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<Data>| {
let h = super::super::current(&l)?;
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
f(&h, &a)
})
};
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
}
fn char_members(link: &Link) -> Vec<Described> {
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<Described> {
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<String>), 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<Option<String>> = 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<String> = 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<String> = 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<Described> {
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<Described> {
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<HostClass> {
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),
]
}
+69
View File
@@ -1295,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<Savepoint>)> {
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));
@@ -1342,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)
{
@@ -1420,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<Vec<vectorcraft_doc::TextStyleDef>>, vectorcraft_doc::Shared<Vec<vectorcraft_doc::TextStyleDef>>);
/// 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<StyleLists>,
pub(crate) gone: std::collections::HashSet<(u64, bool, String)>,
pub(crate) reverted: Vec<u64>,
}
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<Data, HostError> {
+1
View File
@@ -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"),
+3
View File
@@ -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
}
+1
View File
@@ -186,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;
+333
View File
@@ -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::<Vec<_>>(), ["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}");
}
}
+17
View File
@@ -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();
+434
View File
@@ -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<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
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<String>, 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<String> {
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::<String>::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::<usize>()
};
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<Value> = (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<TextStyleDef> = (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());
}
+1
View File
@@ -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,
+1 -3
View File
@@ -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());
@@ -106,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"),
@@ -155,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"),
@@ -174,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 \
@@ -203,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"),
+3
View File
@@ -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 {
+2 -10
View File
@@ -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<Value> {
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<bool> {
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<Value> {
@@ -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<Value> {
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 ----
+4
View File
@@ -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.
+20 -4
View File
@@ -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<u32> {
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<Source>, recursion: u32, bind_name: bool, es2015: bool) -> CResult<Rc<Code>> {
/// 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<Source>,
recursion: u32,
bind_name: bool,
es2015: bool,
outer: SuperRules,
) -> CResult<Rc<Code>> {
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<Source>,
pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kind: CodeKind) -> CResult<Rc<Code>> {
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)
}
+50
View File
@@ -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();";
+17
View File
@@ -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<bool> {
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<bool> {
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<Option<Data>> {
let Class::Host(h) = &self.object(id)?.class else { return Ok(None) };
+12 -14
View File
@@ -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<Rc<Code>, 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<Rc<Code>, 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<Rc<Code>, 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)
}
}
}
+1
View File
@@ -1048,6 +1048,7 @@ fn code(ops: Vec<Op>) -> Code {
own_name: None,
method: false,
generator: false,
supers: crate::parser::SuperRules::default(),
}
}
+4 -4
View File
@@ -222,11 +222,11 @@ pub fn parse_utf16(source: &[u16], options: &Options) -> Result<Program, SyntaxE
parser::Parser::new(source, options, false)?.parse_program().map(|(program, _)| program)
}
/// [`parse_utf16`] for code a direct `eval` runs inside a function, where `new.target` is allowed
/// (ECMA-262 2015 section 18.2.1.1).
pub(crate) fn parse_utf16_in_function(source: &[u16], options: &Options) -> Result<Program, SyntaxError> {
/// [`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<Program, SyntaxError> {
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
+30 -10
View File
@@ -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<crate::ast::FunctionId> {
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);
+1 -1
View File
@@ -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, Line truncated
"{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; Line truncated
),
(
"ui.savePdfDialog",
+2
View File
@@ -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`]).
+26 -6
View File
@@ -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<OrientedBox>,
}
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<f64> {
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
}
+75 -9
View File
@@ -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<Overlay>) {
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<Overlay>) {
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<f64> {
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),
}
}
+1
View File
@@ -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,
+1 -1
View File
@@ -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 };
+42
View File
@@ -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
+2 -2
View File
@@ -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)) }),
+34 -2
View File
@@ -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() {
+35
View File
@@ -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
+215 -17
View File
@@ -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::<Vec<_>>()
});
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<usize>], &[Option<usize>]),
(flat, stands_for, colors): (&[Option<usize>], &[Option<usize>], &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::<f64>().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<usize>| {
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<usize>], 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<usize>], between: &[[Option<usize>; 2]]) -> Vec<FlatColors> {
let mut colors: Vec<FlatColors> = 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::<f64>().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<Px>>,
}
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::<f64>().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<f32>], w: usize| pl.iter().take(3).map(|p| p[y * w + x]).collect::<Vec<_>>();
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::<usize>(), 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<Px> = (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]];
@@ -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<RowsData>) -> 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));
+1
View File
@@ -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 Гравитация
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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 Βαρύτητα
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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é
Can't render this file because it is too large.
+1
View File
@@ -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 ગ્રેવિટી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+1
View File
@@ -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 ग्रेविटी
Can't render this file because it is too large.
+1
View File
@@ -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ó
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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à
Can't render this file because it is too large.
+1
View File
@@ -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 六角形 (行)
Can't render this file because it is too large.
+1
View File
@@ -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 დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
Can't render this file because it is too large.
+1
View File
@@ -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 행 기준 육각형
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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 Гравитация
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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 Гравітація
Can't render this file because it is too large.
+1
View File
@@ -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
Can't render this file because it is too large.
+1
View File
@@ -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 灰色和中性色
Can't render this file because it is too large.
+1
View File
@@ -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 重力
Can't render this file because it is too large.
+137 -32
View File
@@ -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<CommandStates>,
catalog: Option<AppCatalog>,
/// The rows `catalog` was made from, kept while what they are made from stays the same.
rows: Option<CatalogRows>,
}
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<crate::shortcut_editor::Snapshot>,
platform: craft::keymap::Platform,
plays: Vec<(String, craft::keymap::Chord)>,
refs: Vec<(CommandRef, String, bool)>,
overrides: std::sync::Arc<craft::keymap::Overrides>,
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<CommandDef>,
known: HashSet<String>,
accepted: bool,
}
#[cfg(test)]
thread_local! {
/// How many times this thread made the catalog's rows.
pub(crate) static CATALOG_BUILDS: std::cell::Cell<usize> = 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<CommandDef> {
let snapshot = crate::shortcut_editor::snapshot();
fn catalog_defs(inputs: &CatalogInputs) -> (Vec<CommandDef>, HashSet<String>) {
#[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<CommandDef> = 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<String> = 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<CommandDef>) -> Option<AppCatalog> {
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):
@@ -522,13 +594,46 @@ impl Build<'_> {
mod tests {
use super::*;
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
#[test]
fn a_rebuild_checks_each_dimmed_row_once() {
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));
}
/// A rebuild asks each dimmed row's command once whether it can run, for its state and its reason together.
#[test]
fn a_rebuild_checks_each_dimmed_row_once() {
let (mut app, ctx) = app_with_document();
// `object.group` is a row of the Object menu; `appearance.addFill` is a catalog row only, dimmed with no subject.
let ids = ["object.group", "appearance.addFill"];
for id in ids {
+1 -1
View File
@@ -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, Line truncated
"{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; Line truncated
),
(
"ui.savePdfDialog",
+2
View File
@@ -1227,6 +1227,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_document_colors;
#[cfg(test)]
mod tests_color_wheel_gamut;
+4 -2
View File
@@ -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"))
}
+428 -78
View File
@@ -38,6 +38,9 @@
//! (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>) 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
@@ -62,6 +65,7 @@
//! Show Opacity, Show Hex Field, the contrast settings, Show Color Vision Preview and Show Document
//! Colors are kept with the preferences (`ui.colorWheel`).
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
@@ -74,7 +78,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;
@@ -83,7 +87,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};
@@ -92,10 +96,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, wheel_target};
use super::{Live, alt_held};
use super::color::{Target, apply, gamut, target_now, wheel_target};
use super::{Live, alt_held, color_json};
use crate::VectorcraftApp;
use crate::edits::{EditPath, apply_edits};
@@ -428,28 +433,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;
@@ -495,8 +496,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<Color>) -> Vec<Item> {
let item = |id: String, label: &str, checked: bool, enabled: bool, params: Value| Item {
id,
@@ -539,10 +540,20 @@ fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
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(),
@@ -575,20 +586,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
));
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
}
/// The menu rows of `app`'s settings, with the color the panel edits for Current Color.
fn app_items(app: &VectorcraftApp) -> Vec<Item> {
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`].
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
for item in app_items(app) {
for item in items(&app.ui.color_wheel, cms::active().rgb_is_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);
@@ -600,10 +606,11 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
/// Run the menu row `id` (`ui.colorWheel.<row>`); `None` when it is not one of this panel's.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option<Result<Value, String>> {
let row = id.strip_prefix("ui.colorWheel.")?;
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, &params))
}
@@ -673,10 +680,14 @@ pub struct WheelUi {
rows_live: Option<Sliders>,
/// 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<String>)>,
/// The contrast row's `color.contrast` answer, with the [`RatioKey`] it was asked for.
pub(super) ratio: Option<(RatioKey, Option<Value>)>,
/// What the contrast row's answer was measured against, with the [`RatioKey`] it was asked for.
backdrop: Option<(RatioKey, Option<Backdrop>)>,
/// 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
@@ -810,6 +821,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))
@@ -889,6 +921,256 @@ pub(super) struct RatioKey {
pub(super) mesh_points: Vec<(NodeId, Vec<usize>)>,
/// 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<Vec<Vec<(f32, f32)>>>;
/// 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<Vec<f64>> = (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<FieldPoint>> = 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<EdgeKey, Vec<(FieldPoint, [bool; 2])>> = 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<Bands> = (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<Vec<FieldPoint>> {
let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits());
let mut ends: HashMap<(u32, u32), Vec<usize>> = 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<f64> = 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<egui::Pos2> = 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
@@ -927,9 +1209,19 @@ fn background(app: &mut VectorcraftApp, panel: &mut WheelUi) -> Option<Color> {
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<Color>) -> Option<Value> {
/// The contrast row's measurement: `color.contrast`'s answer for the chosen category, and what the
/// lines measure picks against.
struct Measured {
answer: Option<Value>,
backdrop: Option<Backdrop>,
}
/// 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:?}")),
@@ -945,33 +1237,43 @@ fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option<Co
under: under(),
mesh_points: app.session.fill_mesh_points(),
bucket: app.session.tool_paints(!app.session.fill_active),
category,
};
match &panel.ratio {
Some((k, r)) if *k == key => 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<Color> {
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),
};
@@ -983,22 +1285,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<bool>) -> Option<Color> {
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::<Color>(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,
@@ -1626,8 +1961,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<Rect>) {
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<Srgba> = others.iter().map(|&hsb| srgb(hsb_to_rgb(hsb))).collect();
@@ -1640,14 +1975,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<Rect>) {
let ch = set.channel;
let mode = area_mode(ch);
let values = cx.color.map(|_| box_values(ch, cx.shown));
@@ -1656,8 +1995,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) {
@@ -1696,13 +2036,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
@@ -1792,8 +2135,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());
+9 -6
View File
@@ -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] {
@@ -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<String>], 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<R: Default>(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,
@@ -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());
@@ -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<Option<String>> {
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<String> {
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<String>)> {
p.app().ui.color_wheel_panel.behind.clone()
}
/// The background in the row's kept answer.
fn measured(p: &Panel) -> Option<String> {
let kept: Option<(RatioKey, Option<Value>)> = 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}");
}
@@ -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<egui::Rect> {
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<f32>, Vec<f32>) = 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::<Vec<_>>();
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");
}
@@ -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));
@@ -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);
+25 -10
View File
@@ -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();
+28 -1
View File
@@ -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<String> = keymap.catalog().iter().filter(|d| (tools.rows)(d)).map(|d| d.command.key()).collect();
let want: Vec<String> = entries().iter().filter(|e| e.is_tool).map(|e| command_of(&e.key).key()).collect();
assert_eq!(listed.iter().collect::<HashSet<_>>(), want.iter().collect::<HashSet<_>>());
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.
+4 -2
View File
@@ -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, &current, &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);
}
+34
View File
@@ -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<egui::Shape> = 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");
}
+7 -5
View File
@@ -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
+3 -2
View File
@@ -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
+63 -11
View File
@@ -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
@@ -1256,7 +1263,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
@@ -1280,15 +1287,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
@@ -2781,7 +2802,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
@@ -3061,6 +3085,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),
@@ -14711,7 +14762,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
+1 -1
View File
@@ -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 `<pattern>`/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 <name>, 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 |
+6 -4
View File
@@ -1115,8 +1115,9 @@ 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`.
@@ -1183,7 +1184,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`.
@@ -1191,12 +1192,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 <path>]` 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. `<!DOCTYPE>` 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`.
@@ -2149,6 +2150,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. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged.
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.