diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000000..e3ff66fc1c
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+# The DXF writer goldens are compared byte for byte with the writer's output (LF line endings).
+crates/cad/tests/data/*.dxf -text
diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json
index 507caffe10..6b6099e7b6 100644
--- a/.github/nightly-signing-policy.json
+++ b/.github/nightly-signing-policy.json
@@ -130,7 +130,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
- }
+ },
+ "package_formats": [
+ "appimage",
+ "arch",
+ "deb",
+ "flatpak",
+ "oci",
+ "rpm"
+ ]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
diff --git a/assets/app-icon/vectorcraft-nightly.png b/assets/app-icon/vectorcraft-nightly.png
index 4211c1ddb8..09b2747606 100644
Binary files a/assets/app-icon/vectorcraft-nightly.png and b/assets/app-icon/vectorcraft-nightly.png differ
diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs
index ef42eec957..ba5bb3b974 100644
--- a/crates/color/src/wcag.rs
+++ b/crates/color/src/wcag.rs
@@ -2,6 +2,7 @@
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
+//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
/// What the content in front is, which sets the ratio it needs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
}
+/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
+/// passes.
+const LIGHTNESS_SAMPLES: usize = 16;
+/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
+const LIGHTNESS_STEPS: usize = 32;
+/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
+/// which leave it within 1e-7 of the step.
+const PEAK_STEPS: usize = 32;
+/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
+/// single peak between them. `f` is called 34 times.
+pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
+ let g = (5f64.sqrt() - 1.0) / 2.0;
+ let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
+ let (mut fa, mut fb) = (f(a), f(b));
+ for _ in 0..PEAK_STEPS {
+ if fa < fb {
+ (lo, a, fa) = (a, b, fb);
+ b = lo + g * (hi - lo);
+ fb = f(b);
+ } else {
+ (hi, b, fb) = (b, a, fa);
+ a = hi - g * (hi - lo);
+ fa = f(a);
+ }
+ }
+ if fa > fb { a } else { b }
+}
+
+/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
+/// () with the lightness raised or lowered, whichever
+/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
+/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
+/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
+/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
+/// so a color that passes only in a narrow band between white and black (as under a Difference
+/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
+/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
+/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
+/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
+/// steps before the first passing one is missed, and a farther color can be returned.
+pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
+ let passes = |c: [f32; 3]| ratio(c) >= minimum;
+ let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
+ if passes(srgb) {
+ return Some(srgb);
+ }
+ let [l, c, h] = crate::oklab::to_oklch(srgb);
+ let mut best: Option<(f64, [f32; 3])> = None;
+ for end in [1.0, 0.0] {
+ let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
+ let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
+ let ratios: Vec = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
+ // `lo` fails and `hi` passes, the step before the first sample that passes.
+ let found = match ratios.iter().position(|r| *r >= minimum) {
+ Some(i) => Some((step(i), step(i + 1))),
+ None => {
+ // Every sample fails: look for a higher ratio around the highest one.
+ let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
+ let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
+ let peak = peak_between(lo, hi, &|t| ratio(at(t)));
+ passes(at(peak)).then_some((lo, peak))
+ }
+ };
+ let Some((mut lo, mut hi)) = found else { continue };
+ for _ in 0..LIGHTNESS_STEPS {
+ let mid = (lo + hi) / 2.0;
+ if passes(at(mid)) { hi = mid } else { lo = mid }
+ }
+ let step = (end - l).abs() * hi;
+ if best.is_none_or(|(d, _)| step < d) {
+ best = Some((step, at(hi)));
+ }
+ }
+ best.map(|(_, c)| c)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -137,6 +214,80 @@ mod tests {
assert_eq!(Category::parse("NormalText"), None);
}
+ fn hue(srgb: [f32; 3]) -> f64 {
+ let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
+ b.atan2(a).to_degrees()
+ }
+
+ #[test]
+ fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
+ let (fg, bg) = (hex("fdc96e"), hex("355f78"));
+ let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
+ let r = contrast_ratio(fix, bg);
+ assert!((4.5..4.501).contains(&r), "{r}");
+ assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
+ // A color lighter than the background gets lighter.
+ assert!(relative_luminance(fix) > relative_luminance(fg));
+ }
+
+ #[test]
+ fn the_closest_passing_gray_on_white_is_a_darker_gray() {
+ let white = [1.0; 3];
+ let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
+ let r = contrast_ratio(fix, white);
+ assert!((4.5..4.501).contains(&r), "{r}");
+ assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
+ }
+
+ #[test]
+ fn a_color_that_passes_only_between_white_and_black_is_found() {
+ // White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
+ // mid gray draws black, 5.3:1.
+ let gray = [0.5; 3];
+ let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
+ let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
+ let r = contrast_ratio(difference(fix), gray);
+ assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
+ assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
+ }
+
+ #[test]
+ fn a_narrow_band_between_the_samples_is_found() {
+ // Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
+ // for 3:1 (black reaches 3.04:1), and no even step from white lands there.
+ let gray = hex("5a5a5a");
+ let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
+ let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
+ let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
+ let r = ratio(fix);
+ assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
+ }
+
+ /// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
+ /// blue that needs a little more contrast keeps nearly all of its chroma.
+ #[test]
+ fn a_blue_that_darkens_a_little_keeps_its_chroma() {
+ let gray = hex("b8b8b8");
+ let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
+ let blue = [0.0, 0.0, 1.0];
+ assert!(ratio(blue) < 4.5, "{}", ratio(blue));
+ let fix = closest_passing(blue, 4.5, &ratio).unwrap();
+ let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
+ assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
+ assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
+ }
+
+ #[test]
+ fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
+ let white = [1.0; 3];
+ assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
+ assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
+ // Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
+ let mid = hex("777777");
+ assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
+ assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
+ }
+
#[test]
fn half_opaque_black_over_white_is_mid_gray() {
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index 009fc4efd8..8a4e6ebe6f 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -851,6 +851,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
+pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs
index 401879bc91..dd18bcadcb 100644
--- a/crates/engine/src/cmd/colorcmds.rs
+++ b/crates/engine/src/cmd/colorcmds.rs
@@ -151,7 +151,7 @@ pub fn specs() -> Vec {
"Contrast",
[],
None,
- "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
+ "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}",
always,
contrast
),
@@ -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,
+ /// The color and amount a fill stains the picked object of a dynamic symbol instance with.
+ stain: Option<(Color, f32)>,
+ /// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black).
+ rich_black: bool,
+}
+
+/// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color
+/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of
+/// the art below it inside the level around it, while a blending level lies further out.
+#[derive(Clone, Debug, PartialEq)]
+struct Pass {
+ blend: BlendMode,
+ opacity: f32,
+ backdrop: ([f32; 3], f32),
+ blends: bool,
+ isolate: bool,
+ inner: f32,
+}
+
+/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next
+/// level out holds drawn alone.
+type Through = ([f32; 3], f32, f32);
+
+impl Pass {
+ /// What the level draws for color and alpha `x`, drawn over the art below it: a level that
+ /// blends takes that art back out by `alone`, the alpha of what it holds drawn alone.
+ fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) {
+ if !self.blends {
+ return x;
+ }
+ if alone <= 0.0 {
+ return (x.0, 0.0);
+ }
+ let b = self.backdrop;
+ (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone)
+ }
+
+ /// `d` drawn through the level. The level's opacity applies to what it holds, a level that
+ /// isolates its blending carries out the alpha of what it holds composited on its own, and the
+ /// art beside it in the level around it adds to the alpha once.
+ fn draw(&self, (color, alpha, alone): Through) -> Through {
+ let source = self.source((color, alpha), alone);
+ let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0);
+ let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop);
+ (color, alpha, drawn + self.inner * (1.0 - drawn))
+ }
+
+ /// The level with its opacity, the art below it and its alphas passed through `q`.
+ fn with(&self, q: impl Fn(f32) -> f32) -> Pass {
+ let (color, alpha) = self.backdrop;
+ Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() }
+ }
+}
+
+impl Backdrop {
+ /// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
+ /// fill stains mixes its solid color towards the stain.
+ pub fn drawn_color(&self, c: &Color) -> Color {
+ match self.stain {
+ Some((stain, amount)) => c.lerp(&stain, amount),
+ None => *c,
+ }
+ }
+
+ /// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through
+ /// `cms` and the Appearance of Black the backdrop was read with.
+ pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] {
+ shown_rgb(cms, self.rich_black, &self.drawn_color(c))
+ }
+
+ /// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
+ pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
+ let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d));
+ if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) }
+ }
+
+ /// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
+ /// the background.
+ pub fn ratio(&self, shown: [f32; 3]) -> f64 {
+ wcag::contrast_ratio(self.front(shown), self.against)
+ }
+
+ /// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art
+ /// below each level, the background, the opacities, and the color and alpha each level gives.
+ fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 {
+ let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
+ let painted = |c: [f32; 3]| c.map(eight);
+ let against = painted(self.against);
+ let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| {
+ let (color, alpha, alone) = p.with(eight).draw(d);
+ (painted(color), eight(alpha), eight(alone))
+ });
+ let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) };
+ wcag::contrast_ratio(painted(front), against)
+ }
+
+ /// The background as `#rrggbb` in working RGB, the form a color param takes.
+ pub fn against_hex(&self) -> String {
+ let [r, g, b] = self.written;
+ format!("#{r:02x}{g:02x}{b:02x}")
+ }
+}
+
+/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
+/// 100 % K alone shows as black.
+fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
+ match *c {
+ Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
+ _ => cms.display_rgb(c),
+ }
+}
+
+/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
+/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
+/// Gray color as gray.
+fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
+ let [r, g, b] = cms.srgb_to_rgb(srgb);
+ let rgb = Color::rgb(r, g, b);
+ match like {
+ Color::Rgb { .. } => rgb,
+ Color::Cmyk { .. } => {
+ let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
+ Color::cmyk(c, m, y, k)
+ }
+ Color::Lab { .. } => {
+ let l = cms.lab(&rgb);
+ Color::lab(l.l, l.a, l.b)
+ }
+ Color::Gray { .. } => keep_model(*like, rgb),
+ }
+}
+
+/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
+/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
+/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8
+/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by
+/// [`Backdrop::ratio`], or when no lightness of its hue does.
+fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option {
+ let cms = vectorcraft_color::cms::active();
+ let ratio = |srgb: [f32; 3]| {
+ let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color));
+ backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown))
+ };
+ if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum {
+ return None;
+ }
+ let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?;
+ Some(in_model_of(&cms, fix, color))
+}
+
fn contrast(s: &mut Session, p: &Value) -> Result {
+ contrast_measure(s, p).map(|(answer, _)| answer)
+}
+
+/// `color.contrast`'s answer for params `p`, and what it measured the color against.
+pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
+ const C: &str = "color.contrast";
+ let category = match p.get("for") {
+ None | Some(Value::Null) => Category::NormalText,
+ Some(v) => {
+ let key = "for";
+ let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
+ v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
+ }
+ };
+ let (color, backdrop) = contrast_backdrop(s, p)?;
+ let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color));
+ let levels = |c: Category| {
+ let (aa, aaa) = c.passes(ratio);
+ match aaa {
+ Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
+ None => json!({ "aa": aa }),
+ }
+ };
+ let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) {
+ Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
+ None => Value::Null,
+ };
+ let fixes = match category.minimums() {
+ (aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
+ (aa, None) => json!({ "aa": fix(aa) }),
+ };
+ let answer = json!({
+ "ratio": ratio,
+ "against": backdrop.against_hex(),
+ "normalText": levels(Category::NormalText),
+ "largeText": levels(Category::LargeText),
+ "graphics": levels(Category::Graphics),
+ "for": category.id(),
+ "fix": fixes,
+ });
+ Ok((answer, backdrop))
+}
+
+/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
+/// what it measures it against.
+fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
+ let (color, backdrop) = contrast_reading(s, p, true)?;
+ let color = color.ok_or_else(|| bad("color.contrast", no_color()))?;
+ Ok((color, backdrop))
+}
+
+/// What a color picked for the active proxy would be measured against by `color.contrast` with
+/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the
+/// Color Wheel's contrast lines show where a pick would pass.
+pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result {
+ contrast_reading(s, p, false).map(|(_, backdrop)| backdrop)
+}
+
+/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when
+/// `need_color`.
+fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option, Backdrop)> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
@@ -1044,23 +1266,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result {
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
+ let given = p.get("color").is_some_and(|v| !v.is_null());
let (color, drawn) = match p.get("color") {
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
- Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
+ Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
};
+ if need_color && color.is_none() {
+ return Err(bad(C, no_color()));
+ }
let rich_black = s.prefs.black_on_screen == "rich";
let cms = vectorcraft_color::cms::active();
- let shown = |c: &Color| match *c {
- Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
- _ => cms.display_rgb(c),
- };
+ let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
+ // Whether the background read is one color across its pixels.
+ let mut uniform = true;
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
let (against, written) = match p.get("against").filter(|_| !below) {
None => {
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
// one the ratio uses, and giving it back answers the same ratio.
- let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
+ let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
+ uniform &= one;
+ let working = to_8bit(cms.srgb_to_rgb(sample));
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
}
Some(v) => {
@@ -1096,60 +1323,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result {
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
+ // The alphas, the art below each level and `alone` do not depend on the color, so each level
+ // is read once here and [`Backdrop::front`] draws any color through the levels.
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
- let mut x = (shown(&color), 1.0f32);
+ let mut passes = vec![];
+ let mut alpha = 1.0f32;
let mut alone = 1.0f32;
+ // Whether a level so far read art that is not one color.
+ let mut mixed = false;
for (k, step) in steps.iter().enumerate() {
- if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
+ if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 {
continue;
}
let above = &steps[k + 1..];
let scope = above.iter().find(|a| a.isolate);
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::>();
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
- let backdrop = match scope {
- Some(_) if !sampled => ([0.0; 3], 0.0),
- None if !sampled => (against, 1.0),
+ let (backdrop, one) = match scope {
+ Some(_) if !sampled => (([0.0; 3], 0.0), true),
+ None if !sampled => ((against, 1.0), uniform),
// The background itself, as the answer writes it.
- None if step.hide.is_none() && full.is_empty() => (against, 1.0),
+ None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
_ => read(scope.map(|a| &a.within))?,
};
// The alpha of the art below the level inside the level around it, while a blending level
// lies further out (none for a given background).
- let inner = match above.first() {
- Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
- _ => 0.0,
+ let (inner, inner_one) = match above.first() {
+ Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
+ let ((_, a), one) = read(Some(&around.within))?;
+ (a, one)
+ }
+ _ => (0.0, true),
};
- let source = if !blends(step) {
- x
- } else if alone <= 0.0 {
- (x.0, 0.0)
- } else {
- (std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
- };
- // A level that isolates its blending carries out the alpha of what it holds composited on
- // its own.
- let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
- x = composite(step.blend, source, step.opacity, backdrop);
- alone = drawn + inner * (1.0 - drawn);
- }
- let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
- let ratio = wcag::contrast_ratio(front, against);
- let levels = |c: Category| {
- let (aa, aaa) = c.passes(ratio);
- match aaa {
- Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
- None => json!({ "aa": aa }),
+ // A blend mode mixes the color with the art below it pixel by pixel, which one color read for
+ // art of several colors does not stand for, also when that art reaches it through the levels
+ // inside it.
+ mixed |= !one || !inner_one;
+ if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
+ return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
}
- };
- let [r, g, b] = written;
- Ok(json!({
- "ratio": ratio,
- "against": format!("#{r:02x}{g:02x}{b:02x}"),
- "normalText": levels(Category::NormalText),
- "largeText": levels(Category::LargeText),
- "graphics": levels(Category::Graphics),
- }))
+ let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
+ (_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
+ passes.push(pass);
+ }
+ let stain = if given { None } else { stain_of(s, !need_color) };
+ Ok((color, Backdrop { against, written, passes, stain, rich_black }))
}
/// An object around the proxy's object: one in the document, or a group of the picked object's
@@ -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, 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, 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 {
/// 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.
diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs
index d9c575eeae..47eccccba9 100644
--- a/crates/engine/src/cmd/textstyles.rs
+++ b/crates/engine/src/cmd/textstyles.rs
@@ -148,8 +148,11 @@ macro_rules! style_cmds {
};
}
+/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes.
+pub const MAX_LOAD_BYTES: usize = 64 << 20;
+
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
-const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
+const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
pub fn specs() -> Vec {
let mut v = style_cmds!(
@@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result {
_ => "textStyle.loadAll".to_string(),
};
let path = str_param(p, "path");
- let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
- (Some(path), ..) => super::fileio::read_file(path)?,
- (None, Some(text), _) => text.as_bytes().to_vec(),
- (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?,
+ let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20));
+ let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
+ (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(),
+ (None, Some(text), _) => text.as_bytes().into(),
+ (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()),
+ (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(),
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
};
+ if bytes.len() > MAX_LOAD_BYTES {
+ return Err(too_large());
+ }
let file = str_param(p, "name").or(path).unwrap_or("Styles");
let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?;
if src.preview_only {
diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs
index 2939657c55..fffd80f2c5 100644
--- a/crates/engine/src/cmd/textstyles/tests.rs
+++ b/crates/engine/src/cmd/textstyles/tests.rs
@@ -896,6 +896,27 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
assert_eq!(s.doc().unwrap().doc, before);
}
+/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit.
+#[test]
+fn loading_refuses_a_file_larger_than_64_mb() {
+ let (mut s, _) = session_with_text("Title");
+ let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("Big.vectorcraft");
+ std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap();
+ let before = s.doc().unwrap().doc.clone();
+ let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()}));
+ std::fs::remove_dir_all(&dir).ok();
+ assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
+ let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8);
+ let r = s.execute("paraStyle.load", &json!({"dataBase64": b64}));
+ assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
+ let text = " ".repeat(MAX_LOAD_BYTES + 1);
+ let r = s.execute("textStyle.loadAll", &json!({"data": text}));
+ assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
+ assert_eq!(s.doc().unwrap().doc, before);
+}
+
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or
/// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped.
#[test]
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 46e6c04343..2cdb0f6239 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -373,6 +373,9 @@ pub struct Session {
pub(crate) startup_failures: Vec<(String, String)>,
/// Each open document's highest next id a run has seen, by [`DocState::uid`].
pub(crate) script_high_water: std::collections::HashMap,
+ /// The styles the steps of a batch a script runs removed or renamed and the documents they
+ /// reverted ([`script::note_style_lists`]).
+ pub(crate) script_style_trail: script::StyleTrail,
/// While a slice of a script runs in this session.
pub(crate) script_in_run: bool,
/// The desktop app supplies each window by (document uid, runtime window identity) while a
diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs
index 168f033166..7c50925bf0 100644
--- a/crates/engine/src/script/dom.rs
+++ b/crates/engine/src/script/dom.rs
@@ -196,19 +196,24 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result(
Ok(v)
}
+/// Marks stale the style objects whose styles a command the run ran removed or renamed.
+pub(super) fn after_kept_command(h: &Host) {
+ text::styles::after_command(h);
+}
+
/// Runs `id` with `params` on the item's document, its selection kept.
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result {
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
@@ -2318,7 +2328,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
}
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
-const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
+pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
/// The error of `move` and `duplicate` given an object of another document.
pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available";
@@ -2746,6 +2756,7 @@ fn classes(link: &Link) -> Vec {
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
("toString", method(l, doc_to_string), returns("string", &[])),
]);
+ document.extend(text::styles::doc_members(l));
document.extend(
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"]
.into_iter()
diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs
index 8d15f1b19e..998652b81c 100644
--- a/crates/engine/src/script/dom/text.rs
+++ b/crates/engine/src/script/dom/text.rs
@@ -50,6 +50,7 @@ use super::{
};
use crate::{DocState, Document, NodeId, NodeKind};
+pub(super) mod styles;
pub(super) mod threads;
/// The error of a text range, or of a collection of one, whose frame's text changed other than
@@ -201,6 +202,8 @@ pub(in crate::script) struct TextState {
made: Cell,
/// The span of each range object, by its number, whose `length` the script set.
resized: RefCell>,
+ /// The styles the run's style objects name.
+ styles: styles::StyleState,
}
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
@@ -1680,14 +1683,13 @@ pub(super) fn classes(l: &Link) -> Vec {
range.extend(attr_members(l));
range.push(threads::range_member(l));
range.extend(para_members(l));
+ range.extend(styles::range_members(l));
range.extend(
[
"lines",
"insertionPoints",
"textRanges",
"kerning",
- "characterStyles",
- "paragraphStyles",
"textSelection",
"changeCaseTo",
"select",
@@ -1786,6 +1788,7 @@ pub(super) fn classes(l: &Link) -> Vec {
None,
),
];
+ out.extend(styles::classes(l));
out.extend(stories);
out
}
diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs
new file mode 100644
index 0000000000..8317e1ae04
--- /dev/null
+++ b/crates/engine/src/script/dom/text/styles.rs
@@ -0,0 +1,802 @@
+//! Character and paragraph styles in the script object model: `document.characterStyles` and
+//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
+//! of a `TextRange` uses, as the help pages
+//! ,
+//! ,
+//! ,
+//! and
+//! describe them.
+//!
+//! VectorCraft's own rules, which the help pages do not state:
+//! - A document's collection lists its Normal style first, then its other styles in the order the
+//! panel lists them.
+//! - A style object names its style for the rest of the run, also after the script renames it
+//! through `name`. Once the style is removed, or renamed or removed other than through the object
+//! model, or its document is closed or reverted with File › Revert, every member throws
+//! `Stale style`; a style added later under the same name is another style.
+//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
+//! characters.
+//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
+//! style does not set. Setting one redefines the style: text in the style takes the new value
+//! where it had the style's old one and keeps its other changes.
+//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
+//! or paragraphs of one, in the style's document. A character style styles exactly that text and
+//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
+//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
+//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
+//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
+//! no other style. They do not add or remove styles.
+//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
+//! look and is in the Normal style after.
+//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
+//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
+
+use std::cell::RefCell;
+use std::rc::Rc;
+
+use serde_json::{Map, Value, json};
+use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
+use vectorcraft_geom::Point;
+use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
+
+use super::{
+ ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
+ function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
+ text_of, this_range, typename_of, usize_of, whole_span, with_doc,
+};
+use crate::DocState;
+use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
+use crate::script::dom::{Described, returns, typed};
+
+/// The error of a style object whose style is gone.
+pub const STALE_STYLE: &str = "Stale style";
+/// The longest style name, in characters, after trimming.
+pub const MAX_STYLE_NAME: usize = 256;
+/// The most styles one run's style objects name.
+pub const MAX_HELD: usize = 4096;
+
+/// A style that a run's style objects name: its document and the document's revert count then, its
+/// kind and its name now.
+struct Slot {
+ uid: u64,
+ reverts: u64,
+ para: bool,
+ name: String,
+ live: bool,
+}
+
+/// A document's uid and its character and paragraph style lists when the slots were last checked.
+type Seen = (u64, Shared>, Shared>);
+
+/// The styles a run's style objects name; an object holds its slot's number.
+#[derive(Default)]
+pub(super) struct StyleState {
+ slots: RefCell>,
+ seen: RefCell>,
+}
+
+/// Marks stale each style object whose style the command just run removed or renamed, so a style
+/// removed and made again under its name by later commands, or by later steps of the same batch,
+/// is another style. A document whose style lists did not change is not checked again. A live
+/// slot's style was in its document's list when the command started, so a step that removed or
+/// renamed it is in the trail's removed names.
+pub(in crate::script) fn after_command(h: &Host) {
+ let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail);
+ let mut slots = h.dom.text.styles.slots.borrow_mut();
+ if !slots.iter().any(|s| s.live) {
+ return;
+ }
+ for slot in slots.iter_mut().filter(|x| x.live) {
+ if trail.reverted.contains(&slot.uid)
+ || (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone())))
+ {
+ slot.live = false;
+ }
+ }
+ let s = h.session.borrow();
+ let mut seen = h.dom.text.styles.seen.borrow_mut();
+ seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
+ for st in s.documents() {
+ let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
+ if same {
+ continue;
+ }
+ seen.retain(|(uid, ..)| *uid != st.uid);
+ seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
+ for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
+ slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name);
+ }
+ }
+ for slot in slots.iter_mut().filter(|x| x.live) {
+ if !s.documents().iter().any(|d| d.uid == slot.uid) {
+ slot.live = false;
+ }
+ }
+}
+
+/// The style objects' state when a savepoint was taken: each slot's name and whether it was
+/// live, and the style lists last checked.
+pub(in crate::script) struct Mark {
+ slots: Vec<(String, bool)>,
+ seen: Vec,
+}
+
+/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored.
+pub(in crate::script) fn mark(h: &Host) -> Mark {
+ let styles = &h.dom.text.styles;
+ let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect();
+ Mark { slots, seen: styles.seen.borrow().clone() }
+}
+
+/// Puts the style objects back as they were at `mark`, after the documents were put back to the
+/// savepoint taken with it. A slot added since then stays live only while its document has the
+/// style and no older live slot names it.
+pub(in crate::script) fn put_back(h: &Host, mark: Mark) {
+ let styles = &h.dom.text.styles;
+ let mut slots = styles.slots.borrow_mut();
+ let kept = mark.slots.len();
+ for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) {
+ slot.name = name;
+ slot.live = live;
+ }
+ let s = h.session.borrow();
+ for i in kept..slots.len() {
+ let (older, newer) = slots.split_at_mut(i);
+ let Some(slot) = newer.first_mut() else { break };
+ let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name);
+ slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name));
+ }
+ *styles.seen.borrow_mut() = mark.seen;
+}
+
+fn normal(para: bool) -> &'static str {
+ if para { NORMAL_PARA } else { NORMAL_CHAR }
+}
+
+fn cmd(para: bool, verb: &str) -> String {
+ format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
+}
+
+fn style_class(para: bool) -> &'static str {
+ if para { "ParagraphStyle" } else { "CharacterStyle" }
+}
+
+fn list_class(para: bool) -> &'static str {
+ if para { "ParagraphStyles" } else { "CharacterStyles" }
+}
+
+fn defs(st: &DocState, para: bool) -> &Vec {
+ if para { &st.doc.para_styles } else { &st.doc.char_styles }
+}
+
+/// The document's style names of a kind, the Normal style first.
+fn names(st: &DocState, para: bool) -> Vec {
+ let mut out = vec![normal(para).to_string()];
+ out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
+ out
+}
+
+fn has_style(st: &DocState, para: bool, name: &str) -> bool {
+ name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
+}
+
+fn stale() -> HostError {
+ HostError::Error(STALE_STYLE.into())
+}
+
+fn held_too_many() -> HostError {
+ HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))
+}
+
+/// The style object for the style `name` of the document `uid`: the same slot as every other
+/// object naming it in this run.
+fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
+ let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
+ let mut slots = h.dom.text.styles.slots.borrow_mut();
+ let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) {
+ Some(i) => i,
+ None => {
+ if slots.len() >= MAX_HELD {
+ return Err(held_too_many());
+ }
+ slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true });
+ slots.len() - 1
+ }
+ };
+ Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
+}
+
+/// A style a style object names.
+struct Style {
+ doc: Doc,
+ para: bool,
+ slot: usize,
+ name: String,
+}
+
+/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
+fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result