Merge main into feat/scripts-app-undo-redo

# Conflicts:
#	crates/engine/tests/it/script_host_vs_scriptcheck.rs
#	docs/target-app-parity.md
This commit is contained in:
dotCooCoo committed 2026-11-28 19:47:12 -08:00
commit ecf193cc06
110 files changed
+5063 -404

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]);
+2 -1
View File
@@ -851,11 +851,12 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
pub use docmenu::guide_indexes;
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
+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.
@@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() {
assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again");
}
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD
/// file with many more pixels keeps its corners when the image is tiny: the new image's transform
/// is the old one scaled down to the new pixel size, which is invertible however small it is.
#[test]
fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() {
let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted");
let plane = vec![255u8; 2000 * 2000];
let zero = vec![0u8; 2000 * 2000];
let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero]));
let cut = write_file(&dir, "big.psd", &big);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
let r = s
.execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]}))
.unwrap();
let old = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [old.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap();
assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted");
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap();
let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
assert!(image.is_distorted_image());
assert_eq!(image.image_corners().unwrap(), corners);
}
/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort
/// by a DCS file keeps the image's corners: the DCS file's image fills them.
#[test]
fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() {
let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs");
let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources()));
let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap();
let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap();
let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap()));
s.execute("select.set", &json!({"ids": [group.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap();
let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap();
let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone();
assert!(new.is_distorted_image(), "the DCS file's image takes the corners");
assert_eq!(new.image_corners().unwrap(), corners);
}
/// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective
/// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners,
/// a clip group of the old file's clipping path loses it when the new file names none, and a later
@@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() {
}
}
/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes
/// its corners, and its slices cover what the corners put their part of the pixels on.
#[test]
fn slices_placed_over_a_distorted_image_follow_its_corners() {
let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[]));
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
let png = crate::tests_links::png(4, 4, [0, 0, 255]);
s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap();
s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap();
let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap();
assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}");
let d = &s.doc().unwrap().doc;
let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap();
assert!(image.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") };
// The top left quarter of the 20 × 20 px canvas.
let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0);
let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap();
let got = slices(&s)[0].0;
let near = |a: f64, b: f64| (a - b).abs() < 1e-6;
assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}");
}
#[test]
fn linked_files_are_placed_without_their_slices() {
let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id()));
+1 -1
View File
@@ -1314,7 +1314,7 @@ fn refill_distorted(
/// `path` with its anchors and handles mapped through `map` as a distort maps a path's points
/// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front
/// of it, and one past it to the far side. `None` when a point maps to no finite page point.
fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
pub(super) fn warped(path: &PathData, map: &Homography) -> Option<PathData> {
let [[a, b, c], [d, e, f], [g, h, i]] = map.0;
let apply = |p: vectorcraft_geom::Point| {
let w = g * p.x + h * p.y + i;
+84 -16
View File
@@ -57,7 +57,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes};
use vectorcraft_geom::{Affine, Point, Rect, shapes};
use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes};
use vectorcraft_pdf::CropTo;
use super::fileio::{self, Format, RasterImage};
@@ -88,7 +88,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Place…",
["File"],
Some("Cmd+Shift+P"),
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its visible layers' objects (all objects without layers), guides left out, are placed as one group named after the file, from the bottom layer upward in each layer's listed Line truncated
"{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] center (default: the first artboard's center; all retained geometry, including art outside a crop frame, must stay within ±4,000,000 pt on either axis after transformation, including template placement), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.<id>\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 12 Line truncated
has_doc,
place
),
@@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
/// The transform that puts new art with the natural box `natural` where `old` is: an image's scale
/// and rotation relative to its 100% size (its resolution's) and its centre are kept (with
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by
/// its file's clipping path or not (`new_image`); other objects keep their centre.
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
let image = replace_measured(d, old, new_image);
@@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
let full = Affine::scale_non_uniform(sx, sy);
let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0);
if im.xf.determinant().abs() > 1e-12 {
if Homography::affine_is_invertible(im.xf) {
return im.xf * full.inverse() * Affine::translate(centre - natural.center());
}
}
@@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
}
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
/// image (`new_image`), except a DCS file's plates; else `old` itself.
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a
/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself.
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
match &old.kind {
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
@@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod
}
}
/// What Replace does when the image it measures, `old`, is distorted and the art placed is a
/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s
/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and
/// the map from the art's natural box to the page through those corners, which a PSD file's slices
/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't
/// fill ([`Node::set_image_corners`]).
fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> {
let NodeKind::Image(im) = &old.kind else { return None };
let q = old.image_quad()?;
let (pixels, width, height) = match art {
Art::Image(img, _) => {
let (sx, sy) = pt_per_px(img.ppi);
(Affine::scale_non_uniform(sx, sy), img.width, img.height)
}
Art::Dcs(a) => (a.xf, a.img.width, a.img.height),
_ => return None,
};
if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) {
return None;
}
let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height));
let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None };
let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new)));
probe.set_image_corners(q).ok()?;
let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?;
Some((xf * pixels.inverse(), q, page))
}
/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as
/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping
/// path is drawn through them as the pixels are. `None` when the corners can't hold the image.
fn with_corners(mut node: Node, q: [Point; 4]) -> Option<Node> {
match &mut node.kind {
NodeKind::Image(_) => node.set_image_corners(q).ok()?,
NodeKind::Group { children, clip: true } => {
let [path, image] = &mut children[..] else { return None };
let image = Arc::make_mut(image);
let NodeKind::Image(im) = &image.kind else { return None };
if !Homography::affine_is_invertible(im.xf) {
return None;
}
// The clipping path in the image's pixels, which its transform placed on the page.
let to_pixels = im.xf.inverse();
image.set_image_corners(q).ok()?;
let map = image.image_map()?;
let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None };
p.transform(to_pixels);
*p = super::links::warped(p, &map)?;
}
_ => return None,
}
Some(node)
}
/// `rect` fitted with `natural`'s aspect, centred.
fn fit(natural: Rect, r: Rect) -> Affine {
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
@@ -846,19 +900,24 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
}
let natural = loaded.natural;
// Replace keeps the transform of the image it measures (`replace_measured`), which a
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
// bounds of what it replaces, so a distorted image there is not refused.
// Replace keeps the transform of the image it measures (`replace_measured`). When that image
// is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other
// art is refused. Type, and any other object it measures, is placed by the bounds of what it
// replaces, so a distorted image there is not refused.
let mut distorted = None;
let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..));
if let Some(o) = old_node
&& !is_text
{
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
let image = replace_measured(&st.doc, o, new_image);
if image.is_distorted_image() {
return Err(super::xform::distorted_image_error(PLACE, image.id));
let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?;
distorted = Some((image.id, fit));
}
}
let m = match (old_node, rect) {
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
(Some(_), _) if let Some((_, (m, ..))) = distorted => m,
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image),
(None, Some(r)) => fit(natural, r),
// Its artboard's bottom-left corner on the target's.
(None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)),
@@ -908,13 +967,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
if let Art::Dcs(a) = &loaded.art {
warnings.extend(dcs::swatch_notes(&st.doc, &a.spots));
}
// A PSD file's slices move and scale with its art; one that would leave the canvas is left out.
// A PSD file's slices move and scale with its art, through a distorted image's corners when
// it takes them; one that would leave the canvas is left out.
let read_count = read_slices.len();
let slices: Slices = read_slices
.into_iter()
.filter_map(|(r, o)| {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c));
let placed = match distorted {
Some((_, (_, _, page))) => page.map_rect_bbox(r)?,
None => {
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c);
corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c))
}
};
super::slices::slice_rect_ok(placed).then_some((placed, o))
})
.collect();
@@ -924,7 +989,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
}
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
let node = transformed(build(d, loaded, link), m);
let mut node = transformed(build(d, loaded, link), m);
if let Some((old_image, (_, q, _))) = distorted {
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
}
let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default();
let (into, index) = match old {
Some(old) => {
+4 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul Line truncated
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event Line truncated
always,
run
),
@@ -195,6 +195,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
if s.script_frames && !answers.is_empty() {
return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"));
}
let actions = script::actions::parse(p.get("actions")).map_err(param)?;
let fuel = max_fuel(p)?;
let installed = switch_or(p, "installed", false, "script.run")?;
let mut checked_real = None;
@@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result<script::Request> {
fuel,
locale,
answers,
actions,
})
}
@@ -442,6 +444,7 @@ impl Session {
fuel,
locale,
answers: vec![],
actions: vec![],
};
let runs = self.script_runs;
self.script_start(request).map_err(|e| {
+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
+354
View File
@@ -0,0 +1,354 @@
//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's
//! run, as the VBScript reference's `DoScript` method of the Application object describes it
//! (<https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf>).
//!
//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps
//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app
//! they are the Actions panel's.
//!
//! VectorCraft's own rules, which the reference does not state:
//! - The action and its set are matched by their exact names; a name that matches no action, or
//! more than one, throws before any step runs.
//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins
//! the run's transaction and its one undo step for each changed document, it is counted as a host
//! call, it reads and writes files only where the script may, and a step that fails is put back
//! and throws an error that names the step and the action, while the steps before it stay done.
//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine
//! does not have (a View menu step, or one that plays an action), and a stop throw before any step
//! runs, as does such a command among those an `action.batch` step plays. An action cannot play
//! another action, so it cannot play itself.
//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it
//! changes nothing.
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Data, HostError, HostMember};
use super::{Host, Link, command, current, refused_to_scripts};
/// The most actions a run's request may carry.
pub const MAX_ACTIONS: usize = 4096;
/// The most steps one action may have, after a `command.batch` step gives its own steps.
pub const MAX_ACTION_STEPS: usize = 10_000;
/// The most steps the actions of one request may have in all.
pub const MAX_ALL_STEPS: usize = 100_000;
/// The most bytes of the request's actions, as JSON.
pub const MAX_ACTIONS_BYTES: usize = 16 << 20;
/// The longest name of an action or a set, in bytes.
pub const MAX_NAME_BYTES: usize = 1024;
/// The longest command id of a step, in bytes.
const MAX_ID_BYTES: usize = 256;
/// The command id of a stop, which waits for the person in the Actions panel.
pub const STOP_STEP: &str = "action.stop";
/// An action a run can play: its set's name, its name and the steps playback runs.
#[derive(Clone, Debug)]
pub struct Playable {
set: String,
name: String,
steps: Vec<Step>,
}
/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a
/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and
/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names.
#[derive(Clone, Debug)]
struct Step {
place: String,
id: String,
params: Value,
bytes: u64,
artboard: Option<u64>,
}
/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the
/// step's place in the action (1 for the first; default its place in the list), within the limits
/// above. A `command.batch` step gives its own steps, each at the batch's place and its own.
pub fn parse(v: Option<&Value>) -> Result<Vec<Playable>, String> {
let Some(v) = v else { return Ok(Vec::new()) };
let Value::Array(list) = v else { return Err("`actions` must be a list".into()) };
if list.len() > MAX_ACTIONS {
return Err(format!("`actions` holds more than {MAX_ACTIONS} actions"));
}
if let Some(place) = super::too_deep(v) {
return Err(format!("`actions{place}` is nested more than 64 levels deep"));
}
if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) {
return Err("`actions` is larger than 16 MiB".into());
}
let mut all = 0usize;
let mut out = Vec::with_capacity(list.len());
for (i, a) in list.iter().enumerate() {
let at = format!("`actions[{i}]`");
let Value::Object(a) = a else { return Err(format!("{at} must be an object")) };
only_keys(a, &["set", "name", "steps"], &at)?;
let set = name_of(a, "set", &at)?;
let name = name_of(a, "name", &at)?;
let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) };
let mut steps = Vec::new();
for (j, s) in given.iter().enumerate() {
let at = format!("{at}.steps[{j}]");
let Value::Object(s) = s else { return Err(format!("{at} must be an object")) };
only_keys(s, &["command", "params", "step"], &at)?;
let place = match s.get("step") {
None => (j + 1).to_string(),
Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) {
Some(n) => n.to_string(),
None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")),
},
};
let (id, params) = command_of(s, &at)?;
match params.get("commands") {
Some(Value::Array(inner)) if id == "command.batch" => {
// The batch's `artboard`, for its steps that act on the active artboard, as
// `command.batch` reads it.
let artboard = params.get("artboard").and_then(Value::as_u64);
for (k, c) in inner.iter().enumerate() {
let at = format!("{at}.params.commands[{k}]");
let Value::Object(c) = c else { return Err(format!("{at} must be an object")) };
let (id, params) = command_of(c, &at)?;
if id == "command.batch" {
return Err(format!("{at} is a command.batch inside a command.batch"));
}
steps.push(step(format!("{place}.{}", k + 1), id, params, artboard));
}
}
_ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")),
_ => steps.push(step(place, id, params, None)),
}
if steps.len() > MAX_ACTION_STEPS {
return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps"));
}
}
all += steps.len();
if all > MAX_ALL_STEPS {
return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all"));
}
out.push(Playable { set, name, steps });
}
Ok(out)
}
impl Playable {
/// The steps the action runs.
pub fn len(&self) -> usize {
self.steps.len()
}
/// Whether the action runs no step.
pub fn is_empty(&self) -> bool {
self.steps.is_empty()
}
}
fn only_keys(o: &Map<String, Value>, keys: &[&str], at: &str) -> Result<(), String> {
match o.keys().find(|k| !keys.contains(&k.as_str())) {
Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))),
None => Ok(()),
}
}
fn name_of(o: &Map<String, Value>, key: &str, at: &str) -> Result<String, String> {
match o.get(key) {
Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()),
Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")),
_ => Err(format!("{at}.{key} must be a string")),
}
}
/// A step's `command` and `params` (default `{}`).
fn command_of(o: &Map<String, Value>, at: &str) -> Result<(String, Value), String> {
let id = match o.get("command") {
Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(),
_ => return Err(format!("{at}.command must be a command id")),
};
let params = match o.get("params") {
None => json!({}),
Some(p @ Value::Object(_)) => p.clone(),
Some(_) => return Err(format!("{at}.params must be an object")),
};
Ok((id, params))
}
fn step(place: String, id: String, params: Value, artboard: Option<u64>) -> Step {
let bytes = serde_json::to_vec(&params).map_or(0, |b| b.len() as u64);
Step { place, id, params, bytes, artboard }
}
/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters
/// as U+FFFD.
fn shown(text: &str) -> String {
const MAX: usize = 80;
let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect();
if text.chars().nth(MAX).is_some() {
out.push('…');
}
out
}
/// The members of `app` this module adds.
pub(super) fn app_members(link: &Link) -> Vec<super::dom::Described> {
let l = link.clone();
let play = Rc::new(move |a: Vec<Data>| {
let h = current(&l)?;
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
do_script(&h, &a)
});
let info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]);
let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)];
members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name)));
members
}
fn arg(a: &[Data], i: usize) -> &Data {
a.get(i).unwrap_or(&Data::Undefined)
}
/// `app.doScript(action, set, dialogs?)`, its arguments after `this`.
fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
if a.len() > 4 {
return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into()));
}
let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else {
return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into()));
};
if action.is_empty() || set.is_empty() {
return Err(HostError::Error("doScript needs the action's name and its set's name".into()));
}
if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES {
return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes")));
}
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
}
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
let p = match found.as_slice() {
[p] => *p,
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
};
if p.steps.is_empty() {
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
}
// Every step is checked before the first runs, so a step that cannot run leaves the documents as
// they were.
for s in &p.steps {
if let Some((place, id)) = refused_step(s) {
let name = shown(&p.name);
return Err(HostError::Error(if id == STOP_STEP {
format!("step {place} of “{name}” is a stop, which a script cannot wait at")
} else {
format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id))
}));
}
}
for s in &p.steps {
// A run asked to stop runs no further step; the realm ends it at its next instruction and
// puts the documents back.
if h.session.borrow().script_stop.is_set() {
break;
}
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
h.session.borrow_mut().set_replaying(outer);
if let Err(e) = r {
let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id));
return Err(match e {
HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)),
other => other,
});
}
}
Ok(Data::Undefined)
}
/// The place and command of the first command step `s` would run that a script may not run: the
/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the
/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the
/// engine does not have are refused.
fn refused_step(s: &Step) -> Option<(String, String)> {
let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none();
if refused(&s.id) {
return Some((s.place.clone(), s.id.clone()));
}
if s.id != "action.batch" {
return None;
}
let commands = s.params.get("commands").and_then(Value::as_array)?;
commands.iter().enumerate().find_map(|(k, c)| {
let id = c.get("command").and_then(Value::as_str).unwrap_or("");
refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned()))
})
}
/// `params` of step `id`, with the active artboard of the active document added as a
/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for
/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to
/// Selected Art. The active artboard is the index `start` gives for the document (its index as the
/// run started, which the view keeps), past the last artboard the last one, as the view shows it
/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While
/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its
/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh
/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the
/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork
/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the
/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch`
/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past
/// the last artboard the last one, and none in a document without artboards, as `command.batch`
/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit
/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept.
pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value {
let mut params = params.clone();
let Some(st) = s.active() else { return params };
let n = st.doc.artboards.len();
let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) {
(Some(_), _) if n == 0 => return params,
(Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)),
(None, Some((_, i))) => (*i).min(n.saturating_sub(1)),
(None, None) => super::dom::active_artboard(st),
};
let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack");
let fit_art = id == "artboard.fitToArt";
let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) {
"artboard"
} else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) {
"index"
} else {
return params;
};
let Some(p) = params.as_object_mut() else { return params };
if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) {
return params;
}
let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() };
let kept: Vec<usize> = match start.picks {
Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => {
list.iter().copied().filter(|i| *i < n).collect()
}
_ => Vec::new(),
};
if kept.len() >= 2 {
p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept));
} else if picks.is_empty() {
p.insert(key.into(), json!(active));
} else if fit_art {
p.insert("indices".into(), json!(picks));
}
params
}
/// What [`on_active_artboard`] reads besides the session: the index of each open document's active
/// artboard as the run started, by document uid; the Artboard tool's selection as the run started,
/// with its document's uid; and the `artboard` a step's recorded `command.batch` names.
pub(crate) struct Start<'a> {
pub active: &'a [(u64, usize)],
pub picks: Option<&'a (u64, Vec<usize>)>,
pub batch: Option<u64>,
}
+21 -9
View File
@@ -199,19 +199,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
}
@@ -296,7 +301,7 @@ fn method(link: &Link, f: Member) -> HostMember {
}
/// A member of a class with what `reflect` tells of it.
type Described = (String, HostMember, MemberInfo);
pub(super) type Described = (String, HostMember, MemberInfo);
/// A property's or a method's result's type for `reflect`.
fn typed(data_type: &str) -> MemberInfo {
@@ -304,7 +309,7 @@ fn typed(data_type: &str) -> MemberInfo {
}
/// A method's result's type and its arguments' names and types, for `reflect`.
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
MemberInfo { arguments, ..typed(data_type) }
}
@@ -312,7 +317,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is
/// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out.
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
@@ -574,7 +579,7 @@ struct Frame {
}
/// The index of the active artboard of `st`, as the view keeps it.
fn active_artboard(st: &DocState) -> usize {
pub(super) fn active_artboard(st: &DocState) -> usize {
let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id);
st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0)
}
@@ -789,6 +794,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))
@@ -2345,7 +2355,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";
@@ -2701,6 +2711,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") }));
application.push(later(l, "Application", "beep"));
application.extend(super::actions::app_members(l));
let preset = {
let l = link.clone();
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
@@ -2774,6 +2785,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),
]
}
+87
View File
@@ -48,6 +48,7 @@
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
//! documents back and keeps the engine's globals; an internal error drops the engine.
pub mod actions;
pub mod console;
pub mod dialogs;
pub mod dollar;
@@ -206,6 +207,8 @@ pub(crate) struct Request {
pub locale: String,
/// The answers to the dialogs of a run with nobody to ask, in order.
pub answers: Vec<DialogAnswer>,
/// The actions `app.doScript` can play.
pub actions: Vec<actions::Playable>,
}
thread_local! {
@@ -806,6 +809,15 @@ struct Host {
args: RefCell<(Data, u64)>,
/// The run's state of the script object model (`app`).
dom: dom::State,
/// The actions `app.doScript` can play.
actions: Vec<actions::Playable>,
/// The index of each open document's active artboard as the run starts, by document uid. The
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
active_artboards: Vec<(u64, usize)>,
/// The artboards the Artboard tool had selected in the active document as the run starts (two or
/// more), with that document's uid. The run gives the tool fresh state, which drops them, so the
/// steps `app.doScript` plays read them here.
artboard_picks: Option<(u64, Vec<usize>)>,
/// The documents open when the run began as the person last left them, each with its own file
/// and the file it was read from ([`crate::DocState::as_person_left`],
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
@@ -1283,6 +1295,7 @@ fn note_ids(s: &mut Session) {
/// it, for a result that cannot cross to the script.
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<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));
@@ -1330,6 +1343,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
Ok((v, objects, bytes, save))
}
Err(e) => {
s.script_style_trail = StyleTrail::default();
if let Some(save) = save
&& !save.restore(s)
{
@@ -1408,9 +1422,76 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
}
}
dom::after_command(host, before);
// Style objects follow only a command that is kept.
if crossed.is_ok() {
dom::after_kept_command(host);
} else {
session.borrow_mut().script_style_trail = StyleTrail::default();
}
crossed.map(|data| (data, value))
}
/// A document's uid, revert count, and character and paragraph style lists.
pub(crate) type StyleLists =
(u64, u64, vectorcraft_doc::Shared<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> {
@@ -2063,6 +2144,9 @@ impl Session {
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
return Err(EngineError::Other(NO_RECOVERY_COPY.to_string()));
}
// The Artboard tool's selection, which the fresh tool state below drops.
let picks = cmd::artboard_tool_picks(self);
let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks));
self.reset_tool();
let open: Vec<u64> = self.docs.iter().map(|d| d.uid).collect();
self.script_high_water.retain(|uid, _| open.contains(uid));
@@ -2182,6 +2266,9 @@ impl Session {
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::new(heap_bytes),
actions: request.actions,
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
artboard_picks,
run_docs: RefCell::new(
self.docs
.iter()
+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
}
+3 -1
View File
@@ -49,7 +49,7 @@ mod css;
mod curvature_circle;
mod cut;
mod dashalign;
mod dcs;
pub(super) mod dcs;
mod delete_keeps_joined;
mod distort;
mod docsetup;
@@ -175,6 +175,7 @@ mod repeat_edit;
mod save;
mod saveoptions;
mod scalestrokes;
mod script_actions;
mod script_console;
mod script_dialogs;
mod script_dollar;
@@ -185,6 +186,7 @@ mod script_include;
mod script_io;
mod script_run;
mod script_scriptui;
mod script_styles;
mod script_tags;
mod script_text;
mod script_threads;
+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}");
}
}
+28 -1
View File
@@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec<u8> {
}
/// Cyan solid on the top row, PANTONE 185 C at 50% on the left column.
fn two_plates() -> Vec<u8> {
pub(crate) fn two_plates() -> Vec<u8> {
single_file(
&[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))],
"%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n",
@@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor
assert_eq!(node(&s).image_corners().unwrap(), corners);
}
/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts
/// the file's image between the corners and draws its clipping path through them.
#[test]
fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() {
let dir = temp_dir("replace-distorted-clip");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let png = crate::tests_links::png(4, 4, [255, 0, 0]);
let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap();
let old = NodeId(r["ids"][0].as_u64().unwrap());
s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap();
let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap();
let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap();
let group = NodeId(r["ids"][0].as_u64().unwrap());
let id = NodeId(r["image"].as_u64().unwrap());
let node = s.doc().unwrap().doc.node(id).unwrap().clone();
assert!(node.is_distorted_image());
assert_eq!(node.image_corners().unwrap(), corners);
let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") };
let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") };
let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect();
// The left half of the 2 × 2 pixels, where the corners put it.
let map = node.image_map().unwrap();
let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap());
assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}");
}
#[test]
fn update_link_clips_an_image_whose_file_gained_a_clipping_path() {
let dir = temp_dir("update-gained-clip");
+41
View File
@@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() {
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step:
/// the new file's pixels fill them, the new image is linked to that file, and its transform is the
/// old image's scaled to the new pixel size. Undo brings the old image back between the same
/// corners.
#[test]
fn place_with_replace_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-place-replace");
let (photo, other) = (dir.file("photo.png"), dir.file("other.png"));
write(&photo, &png(20, 10, RED));
write(&other, &png(60, 20, BLUE));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
// Around the artboard's center, where `centre_colour` looks.
s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap();
let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned();
let before = node(&s, id).unwrap().image_corners().unwrap();
let old_xf = image(&s, id).xf;
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
let undo = undo_len(&s);
let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap();
let new = NodeId(r["ids"][0].as_u64().unwrap());
assert_eq!(undo_len(&s), undo + 1);
assert!(node(&s, id).is_none(), "the old image is replaced");
let n = node(&s, new).unwrap();
assert!(n.is_distorted_image());
assert_eq!(n.image_corners().unwrap(), before);
let im = image(&s, new);
assert_eq!((im.width, im.height), (60, 20));
assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str()));
let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0);
assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf);
assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE));
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, new).is_none());
assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before);
assert!(near(centre_colour(&s.doc().unwrap().doc), RED));
}
/// Unembed into a folder keeps a distorted image's corners, in one undo step.
#[test]
fn unembed_to_a_folder_keeps_a_distorted_images_corners() {
+396
View File
@@ -0,0 +1,396 @@
//! `app.doScript`: a script plays an action of `script.run`'s `actions`.
use serde_json::{Value, json};
use crate::*;
fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions}))
}
fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec<Value> {
let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The error message a `try` around `call` logs, or `"ok"`.
fn caught(s: &mut Session, call: &str, actions: &Value) -> String {
let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}");
log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string()
}
fn doc() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn objects(s: &Session) -> usize {
s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum()
}
fn undo_labels(s: &Session) -> Vec<String> {
s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
}
fn rect(x: i64) -> Value {
json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}})
}
/// One set, `Set`, with the actions given as (name, steps).
fn set(actions: &[(&str, Vec<Value>)]) -> Value {
Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect())
}
#[test]
fn do_script_plays_every_step_as_one_undo_step_with_the_script() {
let mut s = doc();
let before = undo_labels(&s);
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions);
assert_eq!(out, vec![Value::Null], "doScript returns undefined");
assert_eq!(objects(&s), 3);
let after = undo_labels(&s);
assert_eq!(after.len(), before.len() + 1, "{after:?}");
assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL));
// The steps of a recorded `command.batch` run one by one, each counted as a host call.
let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]);
let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap();
assert_eq!(objects(&s), 6);
let r0 = run_with(&mut s, "1;", &batch).unwrap();
assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}");
}
#[test]
fn a_later_throw_puts_back_what_the_action_did() {
let mut s = doc();
let before = (objects(&s), undo_labels(&s));
let actions = set(&[("Two", vec![rect(0), rect(50)])]);
let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string();
assert!(e.contains("late"), "{e}");
assert_eq!((objects(&s), undo_labels(&s)), before);
}
#[test]
fn a_failed_step_is_put_back_and_the_steps_before_it_stay() {
let mut s = doc();
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]);
let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions);
assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}");
assert_eq!(objects(&s), 1, "the first step stays done and the third never runs");
}
#[test]
fn names_are_matched_exactly_and_must_be_one_action() {
let mut s = doc();
let actions = json!([
{"set": "Set", "name": "One", "steps": [rect(0)]},
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
{"set": "Set", "name": "Twice", "steps": [rect(0)]},
{"set": "Set", "name": "Empty", "steps": []},
]);
assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”");
assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”");
assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”");
assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps");
assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”");
assert_eq!(objects(&s), 0);
assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok");
assert_eq!(objects(&s), 1);
assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet");
assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet");
}
#[test]
fn bad_arguments_throw_and_change_nothing() {
let mut s = doc();
let actions = set(&[("One", vec![rect(0)])]);
for (call, want) in [
("app.doScript()", "TypeError"),
("app.doScript(1, 'Set')", "TypeError"),
("app.doScript('One', {})", "TypeError"),
("app.doScript('One', 'Set', 'yes')", "TypeError"),
("app.doScript('One', 'Set', 1)", "TypeError"),
("app.doScript('One', 'Set', false, 4)", "TypeError"),
("app.doScript('', 'Set')", "Error"),
("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"),
] {
let m = caught(&mut s, call, &actions);
assert!(m.starts_with(&format!("{want}:")), "{call}: {m}");
}
assert_eq!(objects(&s), 0);
}
#[test]
fn steps_a_script_may_not_run_stop_the_action_before_any_step() {
let mut s = doc();
s.prefs.show_external_script_warning = true;
let steps = [
(json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"),
(json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"),
(json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"),
(json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"),
(json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"),
(json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"),
];
for (bad, want) in steps {
let actions = set(&[("Loop", vec![rect(0), bad.clone()])]);
let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions);
assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}");
assert_eq!(objects(&s), 0, "{bad}: no step ran");
}
assert!(s.prefs.show_external_script_warning);
// A refused command inside a recorded batch is refused too.
let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]);
let m = caught(&mut s, "app.doScript('B', 'Set')", &batch);
assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}");
assert_eq!(objects(&s), 0);
// So is one among the commands a Batch step plays on each file, before the steps ahead of it run.
let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}});
let batch = set(&[("F", vec![rect(0), files])]);
let m = caught(&mut s, "app.doScript('F', 'Set')", &batch);
assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}");
assert_eq!(objects(&s), 0);
}
#[test]
fn an_action_step_keeps_the_scripts_file_gate() {
let mut s = doc();
let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id()));
let _ = std::fs::remove_file(&path);
let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}});
let actions = set(&[("Export", vec![export])]);
let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions);
assert!(m.contains("Script file access denied"), "{m}");
assert!(!path.exists());
}
#[test]
fn a_long_action_is_held_to_the_host_call_limit() {
let mut s = doc();
// Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the
// steps of one call cannot pass the limit.
let calls = |s: &mut Session, steps: usize| {
let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]);
run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap()
};
let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001));
assert!(many >= one + 2000, "{one} {many}");
}
#[test]
fn bad_action_lists_are_refused_before_the_script_runs() {
let mut s = doc();
let step = || json!({"command": "select.none"});
let cases = [
(json!({}), "`actions` must be a list"),
(json!([1]), "`actions[0]` must be an object"),
(json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"),
(json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"),
(json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"),
(json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"),
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"),
(json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"),
(json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"),
(
json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]),
"a command.batch inside a command.batch",
),
(json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"),
(Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"),
(json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"),
];
for (actions, want) in cases {
let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string();
assert!(e.contains(want), "{want}: {e}");
}
let many: Vec<Value> = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect();
let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string();
assert!(e.contains("more than 100000 steps in all"), "{e}");
assert_eq!(objects(&s), 0, "no run started");
}
#[test]
fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() {
let mut s = doc();
let first = set(&[("One", vec![rect(0)])]);
log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first);
assert_eq!(objects(&s), 0);
// The next run has no actions: the function kept from the first run finds none.
let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }";
assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]);
let two = set(&[("One", vec![rect(0), rect(30)])]);
assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]);
assert_eq!(objects(&s), 2);
}
/// Makes artboard `index` of the active document the view's active one, as the app does before each
/// command.
fn make_active(s: &mut Session, index: usize) {
let id = s.active().unwrap().doc.artboards[index].id;
s.doc_mut().unwrap().active_artboard = Some(id);
}
/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected
/// Art, acts on the active artboard's index as the run started; after the script deletes that
/// artboard, the last one. A step that names its artboard keeps it.
#[test]
fn steps_act_on_the_artboard_active_as_they_run() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let was = boards(&s);
make_active(&mut s, 2);
let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}});
let mut first = align(json!(0));
first["params"].as_object_mut().unwrap().remove("artboard");
let actions = set(&[
("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]),
("Align 1", vec![align(json!(0))]),
("Fit", vec![json!({"command": "artboard.fitToSelection"})]),
]);
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions);
let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was");
assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other");
log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions);
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
}
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
#[test]
fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 1);
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
let mut own = align.clone();
own["params"]["artboard"] = json!(1);
let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}});
let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]);
let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0;
log_with(&mut s, "app.doScript('First', 'Set');", &actions);
assert_eq!(left(&s), was[0].x0, "the batch's artboard 0");
log_with(&mut s, "app.doScript('Past', 'Set');", &actions);
assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one");
log_with(&mut s, "app.doScript('Own', 'Set');", &actions);
assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it");
}
/// The active artboard a step gets is the index it had as the run started: after a step deletes an
/// artboard before it, the artboard now at that index, as the view shows it.
#[test]
fn steps_keep_the_active_artboards_index() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
let uid = s.active().unwrap().uid;
let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None };
let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({}));
assert_eq!(add(&s), json!({"artboard": 1}));
s.execute("artboard.delete", &json!({"index": 0})).unwrap();
assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1");
s.execute("artboard.delete", &json!({"index": 1})).unwrap();
assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one");
}
/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its
/// `indices` fits those.
#[test]
fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
let mut art = Vec::new();
for b in &was {
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
}
make_active(&mut s, 1);
let actions = set(&[
("Fit", vec![json!({"command": "artboard.fitToArt"})]),
("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]),
]);
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art");
log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions);
assert_eq!(boards(&s), art, "the step's own indices");
}
/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it
/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps
/// still get the active one.
#[test]
fn paste_and_fit_steps_keep_the_artboard_tools_selection() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap();
make_active(&mut s, 1);
let start = script::actions::Start { active: &[], picks: None, batch: None };
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1}));
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([0, 2]));
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
assert_eq!(add(&s, id), json!({}), "{id}");
}
assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]}));
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
assert_eq!(add(&s, "object.align"), json!({"artboard": 1}));
assert_eq!(add(&s, "shape.rectangle"), json!({}));
}
/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays,
/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to
/// Artwork Bounds step fits them.
#[test]
fn a_run_keeps_the_artboard_tools_selection_for_its_steps() {
// Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2.
let setup = || {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
let mut art = Vec::new();
for b in &was {
let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap());
}
s.execute("edit.copy", &json!({})).unwrap();
make_active(&mut s, 1);
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
s.set_tool_option("selected", &json!([0, 2]));
(s, was, art)
};
let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]);
let (mut s, ..) = setup();
let before = objects(&s);
log_with(&mut s, "app.doScript('Paste', 'Set');", &actions);
assert_eq!(objects(&s), before + 2, "one copy on each selected artboard");
let (mut s, was, art) = setup();
log_with(&mut s, "app.doScript('Fit', 'Set');", &actions);
let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art");
// A kept artboard past the last one is left out; with fewer than two left, the active one applies.
let (mut s, ..) = setup();
s.reset_tool();
let uid = s.active().unwrap().uid;
let kept = (uid, vec![0, 2]);
let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None };
let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({}));
assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]}));
assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1}));
s.execute("artboard.delete", &json!({"index": 2})).unwrap();
assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1}));
}
+17
View File
@@ -1803,6 +1803,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();
+1
View File
@@ -376,6 +376,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() {
fuel: script::DEFAULT_FUEL,
locale: "en_US".into(),
answers: Vec::new(),
actions: Vec::new(),
};
s.script_start(request).unwrap();
assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1]));
+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());
}
+2 -1
View File
@@ -1044,9 +1044,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
("object.cropImage", json!({})),
("imageTrace.make", json!({})),
("object.mesh.create", json!({})),
// Vector art has no pixels to put between the corners.
(
"file.place",
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"<svg xmlns='http://www.w3.org/2000/svg' width='9' height='9'><rect width='9' height='9'/></svg>")}),
),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
+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());
@@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[
("Application.", "prototype"),
(
"Application.prototype.",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \
getIsFileOpen redo redraw selection selection= textFonts toString typename undo",
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \
undo unloadAction unloadAction=",
),
("DocumentPreset.", "prototype"),
(
@@ -105,10 +106,10 @@ const INSIDE: &[(&str, &str)] = &[
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= tags textFrames toString \
typename views width",
"activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \
documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \
pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
),
("Views.", "prototype"),
("Views.prototype.", "constructor index length parent toString typename"),
@@ -154,8 +155,9 @@ const INSIDE: &[(&str, &str)] = &[
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
(
"",
"CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \
TextOrientation TextRange TextType Words",
"CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \
ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \
TextFrames TextOrientation TextRange TextType Words",
),
("TextFrames.", "prototype"),
("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"),
@@ -173,11 +175,11 @@ const INSIDE: &[(&str, &str)] = &[
(
"TextRange.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \
characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \
characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \
duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \
getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
@@ -202,6 +204,30 @@ const INSIDE: &[(&str, &str)] = &[
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
),
("CharacterStyles.", "prototype"),
("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
("CharacterStyle.", "prototype"),
("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"),
("CharacterStyleAttributes.", "prototype"),
(
"CharacterStyleAttributes.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
underline= verticalScale verticalScale=",
),
("ParagraphStyles.", "prototype"),
("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
("ParagraphStyle.", "prototype"),
(
"ParagraphStyle.prototype.",
"applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename",
),
("ParagraphStyleAttributes.", "prototype"),
(
"ParagraphStyleAttributes.prototype.",
"constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \
rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename",
),
("TextFonts.", "prototype"),
("TextFonts.prototype.", "constructor getByName index length parent typename"),
("TextFont.", "prototype"),
+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]];
+2
View File
@@ -166,6 +166,8 @@ impl VectorcraftApp {
}
let mut params = params;
self.add_active_artboard(id, &mut params);
// A script's `app.doScript` plays the Actions panel's actions.
panels::actions::add_script_actions(self, id, &mut params);
// Edit Symbol from the Symbols panel in a document without artboards centers the symbol's
// art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit
// steps too.
+3 -2
View File
@@ -194,11 +194,12 @@ impl Rows<'_> {
self.range(key, label, range, 1, UnitKind::Percent)
}
/// A length in points, shown in the general unit.
/// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says.
fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param {
// Stored in points; a pixel is a point, as the rulers count it.
let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0);
self.range(key, label, range, 1, UnitKind::Pixels).length(crate::fields::bare_points(lengths, self.bare_points))
let shown = super::three_d_classic::length_unit(self.unit);
self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points))
}
fn flag(&self, key: &str, label: &'static str) -> Param {
@@ -494,6 +494,41 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() {
assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent)));
}
/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their
/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit.
#[test]
fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() {
use craft::ui::patterns::form_dialogs::DialogFields;
use craft::ui::runtime::env::UnitKind;
use vectorcraft_doc::Unit;
let app = VectorcraftApp::new(Session::new(), crate::Services::default());
let unit = |general: Unit, effect: &str, page: &str, key: &str| {
let mut data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new());
data.unit = general;
let mut fields = DialogFields::new();
fields.set("__page", FieldValue::Text(page.into()));
super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit)
};
let mut checked = 0;
for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] {
for key in ["depth", "bevelWidth", "bevelHeight"] {
assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}");
checked += 1;
}
let others = [
(REVOLVE, "rotation", "offset"),
(CLASSIC_EXTRUDE, "object", "depth"),
(CLASSIC_EXTRUDE, "object", "bevelHeight"),
(CLASSIC_REVOLVE, "object", "offset"),
];
for (effect, page, key) in others {
assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}");
checked += 1;
}
}
assert_eq!(checked, 21);
}
#[test]
fn reset_all_keeps_map_art_and_its_options() {
let mut h = drawn(SQUARE, CLASSIC_EXTRUDE);
@@ -50,9 +50,13 @@ const MAP_SYMBOL: &str = "mapSymbol";
/// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters.
pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]];
/// The unit of the general-unit length rows.
fn length_unit(unit: Unit) -> UnitKind {
crate::canvas::rulers::unit_kind(unit)
/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when
/// that counts the same number (points, or pixels at 72 per inch), and points otherwise.
pub(super) fn length_unit(unit: Unit) -> UnitKind {
match crate::canvas::rulers::unit_kind(unit) {
UnitKind::Pixels => UnitKind::Pixels,
_ => UnitKind::Points,
}
}
/// Where the rows show: the 3D and Materials panel marks its fields with `__panel`.
@@ -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.
+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;
+1 -1
View File
@@ -58,7 +58,7 @@ pub use playback::{
deserialize_playback, play, play_action, play_at, playback_drawn, playback_held, playback_options, playback_shown, tick_playback,
waiting_at_stop,
};
pub(crate) use playback::{KnownCommands, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
pub(crate) use playback::{KnownCommands, add_script_actions, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands};
pub use recording::{START_RECORDING, STOP_RECORDING, record, stop};
pub(crate) use recording::{after_journaled_edit, after_recorded_command, before_recorded_command};
@@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec<PlayStep> {
.collect()
}
/// For command `id` `script.run`, or the script of `script.startup.run`'s `then`: gives its
/// `params` the panel's actions as `actions`, which the script's `app.doScript` plays, unless the
/// caller gave them: every action of every set, in panel order, with its steps as playback runs
/// them ([`playback_steps`]) and each step's place in the action. An action that `actions` cannot
/// hold (a step that is not a command, a name that is too long, or one past the limits of
/// [`vectorcraft_engine::script::actions`]) is left out.
pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) {
use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, Playable, parse};
let target = match id {
"script.run" => Some(params),
"script.startup.run" => params.get_mut("then"),
_ => None,
};
let Some(p) = target.and_then(Value::as_object_mut) else { return };
if p.contains_key("actions") {
return;
}
let list = &app.ui.actions;
let (mut held, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize);
for set in list.sets() {
for a in model::members(list, set).into_iter().filter_map(|i| list.action(i)) {
if held.len() >= MAX_ACTIONS {
break;
}
// The commands of a recorded `command.batch` step go back into one batch step, so that an
// error names a failing command by the batch's place and its own (`3.2`).
let mut played: Vec<Value> = Vec::new();
for s in playback_steps(a) {
let params = match s.command.get("params") {
None | Some(Value::Null) => json!({}),
Some(p) => p.clone(),
};
let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params});
let place = s.row + 1;
if a.steps.get(s.row).is_none_or(|step| step.command != "command.batch") {
let mut one = one;
one["step"] = json!(place);
played.push(one);
continue;
}
match played.last_mut() {
Some(last) if last["command"] == "command.batch" && last["step"] == place => {
if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") {
inner.push(one);
}
}
_ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})),
}
}
let one = Value::Array(vec![json!({"set": set, "name": a.name, "steps": played})]);
let Ok(parsed) = parse(Some(&one)) else { continue };
let count = parsed.first().map_or(0, Playable::len);
let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len());
if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES {
continue;
}
steps += count;
bytes += size;
if let Value::Array(mut one) = one {
held.append(&mut one);
}
}
}
p.insert("actions".into(), Value::Array(held));
}
/// The steps of `action` whose command `known` does not hold, in order, as (step index, the index
/// of the command in a `command.batch` step, command id). A `command.batch` step's own commands are
/// checked one by one, as playback runs them ([`included_commands`]); a command of one with no
@@ -637,6 +637,79 @@ fn an_error_counts_excluded_steps() {
assert_eq!(x(&app), 0.0, "the failing batch changes nothing");
}
/// A script's `app.doScript` plays the panel's actions with their included steps; an action whose
/// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept.
#[test]
fn a_script_plays_the_panels_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let rect = |x: i64| ("shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}));
let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}});
let batch = json!({"commands": [{"command": "select.none"}, bad]});
let actions = vec![
action("Draw", &[rect(0), rect(20), rect(40)]),
action("Odd", &[rect(0), ("select.none", json!(5))]),
action("Batched", &[("select.none", json!({})), ("command.batch", batch)]),
];
push_set(&mut app, "Mine", actions);
let draw = model::members(&app.ui.actions, "Mine")[0];
app.ui.actions.set_step(draw, 1, false).unwrap();
let objects =
|app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::<usize>());
let undo = app.session.active().map_or(0, |d| d.history.undo.len());
app.session.script_frames = false;
let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }";
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"]));
assert_eq!(objects(&app), 2, "the excluded step does not run");
assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1);
// A failing command of a recorded batch is named by the batch's place and its own.
let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }";
let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
let m = r["log"][0].as_str().unwrap_or_default();
assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}");
let r =
app.run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})).unwrap();
assert_eq!(r["log"], json!(["there is no action set “Mine”"]));
assert_eq!(objects(&app), 2);
}
/// The script that `script.startup.run` runs after the startup scripts (its `then`) plays the
/// panel's actions too, as File › Scripts runs a script with Run Startup Scripts on.
#[test]
fn the_script_after_the_startup_scripts_plays_the_panels_actions() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
push_set(&mut app, "Mine", vec![action("Draw", &[("shape.rectangle", json!({"x": 0, "y": 10, "width": 10, "height": 10}))])]);
app.session.script_frames = false;
let then = json!({"source": "try { app.doScript('Draw', 'Mine'); vc.log('ok'); } catch (e) { vc.log(e.message); }", "name": "t.js"});
let r = app.run("script.startup.run", json!({"reason": "menu", "then": then})).unwrap();
assert_eq!(r["then"]["log"], json!(["ok"]), "{r}");
}
/// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's
/// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art.
#[test]
fn a_script_plays_the_actions_on_the_active_artboard() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setStroke", json!({"none": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}});
let batch = json!({"commands": [align]});
push_set(&mut app, "Mine", vec![action("Align", &[("command.batch", batch)]), action("Fit", &[("artboard.fitToSelection", json!({}))])]);
let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>();
let was = boards(&app);
app.view_mut().unwrap().artboard = 1;
app.session.script_frames = false;
let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');";
app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap();
let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap();
assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one");
assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1");
}
/// A step of a recorded `command.batch` that fails is named by the batch's place in the action
/// and its own command.
#[test]
+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));
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff. Show more