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/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs
index 9b0147174e..fecd16ed2a 100644
--- a/crates/engine/src/tests/colorcontrast.rs
+++ b/crates/engine/src/tests/colorcontrast.rs
@@ -776,6 +776,33 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
+ // The fix is the color to store: the stain mixes it half way to black again, and the result
+ // just meets AA against white.
+ let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
+ assert_eq!(r["normalText"]["aa"], false, "{r}");
+ let fix = fix_color(&r["fix"]["aa"]);
+ let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
+ let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
+ assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}");
+}
+
+/// A pick for a picked symbol object with a fill of None puts a solid color there, which the
+/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained.
+#[test]
+fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() {
+ let mut s = picked_symbol_part();
+ let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
+ s.active_mut().unwrap().selection.symbol_part = None;
+ s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
+ s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
+ s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
+ s.execute("paint.setFill", &json!({"none": true})).unwrap();
+ assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
+ let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap();
+ let cms = vectorcraft_color::cms::active();
+ let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0)));
+ let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
+ assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}");
}
#[test]
@@ -877,3 +904,309 @@ fn a_fill_of_none_has_no_color_to_measure() {
assert!(e.contains("has no color"), "{e}");
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
}
+
+fn fix_color(v: &Value) -> vectorcraft_color::Color {
+ crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
+}
+
+fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
+ let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
+ b.atan2(a).to_degrees()
+}
+
+#[test]
+fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
+ assert_eq!(r["for"], "normalText");
+ let aa = fix_color(&r["fix"]["aa"]);
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
+ assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
+ let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
+ assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
+ assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
+ // White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
+ assert!(r["fix"]["aaa"].is_null(), "{r}");
+ let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
+ let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
+ assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
+}
+
+/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too:
+/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again,
+/// and the fix has to paint as #767676 (4.54:1) or darker.
+#[test]
+fn a_fix_passes_as_the_canvas_paints_it() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
+ let fix = fix_color(&r["fix"]["aa"]);
+ let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
+ let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]);
+ assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}");
+ // The fix is the closest one: the gray one 8-bit step lighter fails.
+ let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0));
+ assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}");
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap();
+ assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
+}
+
+/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black,
+/// so the Color Wheel's contrast lines use the same color.
+#[test]
+fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() {
+ let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
+ let cms = vectorcraft_color::cms::active();
+ let mut s = Session::new();
+ let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"});
+ let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
+ assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]);
+ s.prefs.black_on_screen = "rich".into();
+ let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
+ assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]);
+ assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}");
+}
+
+/// A translucent fix also meets the minimum with the color, the opacity, the background and the
+/// composited pixel rounded to 8 bits per channel.
+#[test]
+fn a_translucent_fix_passes_at_eight_bits() {
+ let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
+ let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| {
+ let (a, b) = (eight(opacity), eight(against));
+ let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a)));
+ vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3])
+ };
+ let mut s = Session::new();
+ // A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at
+ // 232 / 255 its pixel is #747474 (4.49:1).
+ let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap();
+ let fix = fix_color(&r["fix"]["aa"]);
+ assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}");
+ // #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is
+ // 4.4965:1.
+ let bg = 137.51 / 255.0;
+ let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0});
+ let r = s.execute("color.contrast", &p).unwrap();
+ let fix = fix_color(&r["fix"]["aa"]);
+ assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}");
+ // Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray
+ // at that opacity gets a fix.
+ let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"});
+ let r = s.execute("color.contrast", &p).unwrap();
+ assert_eq!(r["graphics"]["aa"], false, "{r}");
+ assert!(r["fix"]["aa"].is_null(), "{r}");
+}
+
+#[test]
+fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
+ assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
+ let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
+ assert_eq!(g["for"], "graphics");
+ let fix = g["fix"].as_object().unwrap();
+ assert_eq!(fix.keys().collect::>(), ["aa"], "{g}");
+ let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
+ assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
+ let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
+ assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
+ assert!(!large["fix"]["aaa"].is_null(), "{large}");
+}
+
+#[test]
+fn a_cmyk_color_answers_a_cmyk_fix() {
+ let mut s = Session::new();
+ let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
+ assert_eq!(r["normalText"]["aa"], false, "{r}");
+ let fix = fix_color(&r["fix"]["aa"]);
+ assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
+ assert!(ratio(&back) >= 4.5, "{back}");
+}
+
+#[test]
+fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
+ let mut s = Session::new();
+ // #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
+ // meets large text AA (3:1) but not AAA (4.5:1).
+ let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
+ let r = s.execute("color.contrast", &p).unwrap();
+ assert_eq!(r["largeText"]["aa"], false, "{r}");
+ assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
+ let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
+ assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
+}
+
+/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a
+/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws
+/// as it is, on the canvas and in the answer, for each blend mode of the object.
+#[test]
+fn isolation_leaves_a_translucent_normal_row_as_it_draws() {
+ let id = |v: Value| v["id"].as_u64().unwrap();
+ for blend in ["normal", "multiply", "screen", "difference", "overlay"] {
+ for fill in ["#808080", "#ffffff", "#2040a0"] {
+ for lower in [false, true] {
+ let mut s = session();
+ s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
+ s.execute("object.lock", &json!({})).unwrap();
+ let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
+ s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
+ if lower {
+ s.execute("appearance.addFill", &json!({})).unwrap();
+ }
+ let st = s.active().unwrap();
+ let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
+ let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
+ s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap();
+ s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
+ s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap();
+ if lower {
+ s.execute("object.group", &json!({})).unwrap();
+ s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
+ s.execute("select.set", &json!({"ids": [n]})).unwrap();
+ }
+ let plain = s.execute("color.contrast", &json!({})).unwrap();
+ let (p, drawn) = canvas_ratio(&s, &plain);
+ s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
+ let isolated = s.execute("color.contrast", &json!({})).unwrap();
+ let (q, _) = canvas_ratio(&s, &isolated);
+ let case = format!("{blend} {fill} lower row and group: {lower}");
+ assert_eq!(p, q, "the canvas draws the same: {case}");
+ assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}");
+ assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}");
+ }
+ }
+ }
+}
+
+/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one
+/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the
+/// other, so the white draws over different rows and there is no one answer. A given background
+/// stands for the rows below and answers.
+#[test]
+fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() {
+ let mut s = session();
+ let id = |v: Value| v["id"].as_u64().unwrap();
+ s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
+ s.execute("object.lock", &json!({})).unwrap();
+ let square = |s: &mut Session, x: i32, isolate: bool| {
+ let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
+ s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
+ s.execute("appearance.addFill", &json!({})).unwrap();
+ let st = s.active().unwrap();
+ let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
+ let top = items.iter().rposition(|i| i.is_fill()).unwrap();
+ let lower = items.iter().position(|i| i.is_fill()).unwrap();
+ s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
+ s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap();
+ s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
+ if isolate {
+ s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
+ }
+ n
+ };
+ let a = square(&mut s, 30, false);
+ let b = square(&mut s, 120, true);
+ s.execute("select.set", &json!({"ids": [a]})).unwrap();
+ let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap());
+ s.execute("select.set", &json!({"ids": [b]})).unwrap();
+ let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap());
+ assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}");
+ s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
+ let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
+ assert!(e.contains("the selected objects' colors differ"), "{e}");
+ s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
+ // A blending row at no opacity does not show, so the isolation no longer changes the answer.
+ for n in [a, b] {
+ let st = s.active().unwrap();
+ let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap();
+ s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap();
+ }
+ s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
+ s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
+ s.execute("color.contrast", &json!({})).unwrap();
+}
+
+/// A Difference square centered on the edge between locked black and white art: the art behind it
+/// is not one color where it is read, so no one color stands for it; a given background answers,
+/// and over one color the background is read as before.
+#[test]
+fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
+ let mut s = session();
+ s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
+ s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
+ s.execute("select.all", &json!({})).unwrap();
+ // Without the default stroke, which would cover the edge.
+ s.execute("paint.setStroke", &json!({"none": true})).unwrap();
+ s.execute("object.lock", &json!({})).unwrap();
+ s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
+ s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
+ let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
+ assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}");
+ let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
+ assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}");
+ // In Normal mode the color is drawn as it is, over the background read as one color.
+ s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
+ s.execute("color.contrast", &json!({})).unwrap();
+ // Moved over the white art alone, the square blends with one color again.
+ s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
+ s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap();
+ let r = s.execute("color.contrast", &json!({})).unwrap();
+ assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
+}
+
+/// A Difference square over a white square in a 50 % group that isolates its blending, over the
+/// edge between black and white art: the square blends only with the white inside the group, so
+/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
+#[test]
+fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
+ let mut s = session();
+ let id = |v: Value| v["id"].as_u64().unwrap();
+ s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
+ s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
+ s.execute("select.all", &json!({})).unwrap();
+ s.execute("paint.setStroke", &json!({"none": true})).unwrap();
+ s.execute("object.lock", &json!({})).unwrap();
+ let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
+ s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
+ s.execute("paint.setStroke", &json!({"none": true})).unwrap();
+ let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
+ s.execute("paint.setStroke", &json!({"none": true})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
+ s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
+ s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
+ s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
+ s.execute("select.set", &json!({"ids": [square]})).unwrap();
+ s.execute("color.contrast", &json!({})).unwrap();
+}
+
+/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
+/// contrast lines show where a solid color in its place passes.
+#[test]
+fn a_pick_for_a_fill_of_none_is_measured_against_the_background() {
+ let mut s = blended_over_red("normal");
+ s.execute("paint.setFill", &json!({"none": true})).unwrap();
+ assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
+ let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap();
+ let cms = vectorcraft_color::cms::active();
+ let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
+ let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]);
+ assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}");
+ assert_eq!(backdrop.against_hex(), "#ff0000");
+}
+
+#[test]
+fn for_takes_only_the_three_categories() {
+ let mut s = Session::new();
+ for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
+ let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
+ assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
+ }
+}
diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs
index c7e0e4ec5a..635b5f393a 100644
--- a/crates/engine/tests/color_settings.rs
+++ b/crates/engine/tests/color_settings.rs
@@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
/// behind the selection, given back, answers the same ratio.
#[test]
fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() {
- let _g = settings();
- let before = cms::active_settings();
+ let _g = restored_settings();
let mut s = session();
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"}));
@@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space
exec(&mut s, "paint.setFill", json!({"color": "#808080"}));
let below = s.execute("color.contrast", &json!({}));
let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok());
- cms::set_active(&before).unwrap();
let given = given.unwrap();
assert_eq!(given["against"], "#806040", "{given}");
let (below, again) = (below.unwrap(), again.unwrap());
diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs
index 7d1e74bc07..7accd98667 100644
--- a/crates/mcp/src/ui_catalog.rs
+++ b/crates/mcp/src/ui_catalog.rs
@@ -1615,7 +1615,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
- "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}",
+ "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Opacity, Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}",
),
(
"ui.savePdfDialog",
diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv
index f85c44afa0..6150887205 100644
--- a/crates/ui-egui/src/i18n/bg.tsv
+++ b/crates/ui-egui/src/i18n/bg.tsv
@@ -1752,6 +1752,7 @@ font-technology Variable Променливи
Fail Не покрива
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11).
The background is read at the center of the selection. Фонът се отчита в центъра на селекцията.
+ The closest color that passes {level}: click to apply it. Най-близкият цвят, който покрива {level}: щракнете, за да го приложите.
Graphics Processor Графичен процесор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv
index 73db292645..1e846faf46 100644
--- a/crates/ui-egui/src/i18n/bs.tsv
+++ b/crates/ui-egui/src/i18n/bs.tsv
@@ -2121,6 +2121,7 @@ digits Malayalam Malajalam
Fail Ne prolazi
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadina se očitava u sredini odabira.
+ The closest color that passes {level}: click to apply it. Najbliža boja koja zadovoljava {level}: kliknite da je primijenite.
Local Libraries Lokalne biblioteke
Add Content Dodaj sadržaj
Click to apply to the selected type Kliknite da primijenite na odabrani tekst
diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv
index c451ec9811..e2c38092d1 100644
--- a/crates/ui-egui/src/i18n/ca.tsv
+++ b/crates/ui-egui/src/i18n/ca.tsv
@@ -2155,6 +2155,7 @@ digits Malayalam Malaiàlam
Fail No supera
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11).
The background is read at the center of the selection. El fons es llegeix al centre de la selecció.
+ The closest color that passes {level}: click to apply it. El color més proper que compleix {level}: feu clic per aplicar-lo.
Graphics Processor Processador gràfic
Graphics: {adapter} Gràfics: {adapter}
Gravity Gravetat
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index d2a89194fa..31030654e3 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2193,6 +2193,7 @@ digits Malayalam Malajálamské
Fail Nevyhovuje
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadí se čte uprostřed výběru.
+ The closest color that passes {level}: click to apply it. Nejbližší barva, která splňuje {level}: kliknutím ji použijete.
Local Libraries Místní knihovny
Add Content Přidat obsah
Click to apply to the selected type Kliknutím použijete na vybraný text
diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv
index 70c167b084..e9da516794 100644
--- a/crates/ui-egui/src/i18n/da.tsv
+++ b/crates/ui-egui/src/i18n/da.tsv
@@ -4860,6 +4860,7 @@ digits Malayalam Malayalam
Fail Ikke bestået
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11).
The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen.
+ The closest color that passes {level}: click to apply it. Den nærmeste farve, der består {level}: klik for at anvende den.
Local Libraries Lokale biblioteker
Add Content Tilføj indhold
Click to apply to the selected type Klik for at anvende på den markerede tekst
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index e2ce6c9202..36a98df5f8 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -1679,6 +1679,7 @@ file-filter Templates Vorlagen
Fail Nicht bestanden
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11).
The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen.
+ The closest color that passes {level}: click to apply it. Die nächste Farbe, die {level} besteht: Klicken Sie, um sie anzuwenden.
Graphics Processor Grafikprozessor
Graphics: {adapter} Grafik: {adapter}
Gravity Schwerkraft
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 51b04c5526..126ed5a57e 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -1598,6 +1598,7 @@ font-technology Variable Μεταβλητές
Fail Αποτυχία
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11).
The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής.
+ The closest color that passes {level}: click to apply it. Το πλησιέστερο χρώμα που περνά το {level}: κάντε κλικ για να το εφαρμόσετε.
Graphics Processor Επεξεργαστής γραφικών
Graphics: {adapter} Γραφικά: {adapter}
Gravity Βαρύτητα
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 053e35e721..f26d178b5e 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1688,6 +1688,7 @@ font-technology Variable Variables
Fail No cumple
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11).
The background is read at the center of the selection. El fondo se lee en el centro de la selección.
+ The closest color that passes {level}: click to apply it. El color más cercano que cumple {level}: haga clic para aplicarlo.
Graphics Processor Procesador gráfico
Graphics: {adapter} Gráficos: {adapter}
Gravity Gravedad
diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv
index 05c77549a0..05792769f9 100644
--- a/crates/ui-egui/src/i18n/fi.tsv
+++ b/crates/ui-egui/src/i18n/fi.tsv
@@ -2152,6 +2152,7 @@ digits Malayalam Malajalam
Fail Ei läpäise
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11).
The background is read at the center of the selection. Tausta luetaan valinnan keskeltä.
+ The closest color that passes {level}: click to apply it. Lähin väri, joka läpäisee tason {level}: käytä sitä napsauttamalla.
Local Libraries Paikalliset kirjastot
Add Content Lisää sisältöä
Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 8f843cc11f..85c2e3e977 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -1678,6 +1678,7 @@ font-technology Variable Variables
Fail Échec
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11).
The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection.
+ The closest color that passes {level}: click to apply it. La couleur la plus proche qui satisfait {level}. Cliquez pour l’appliquer.
Graphics Processor Processeur graphique
Graphics: {adapter} Carte graphique : {adapter}
Gravity Gravité
diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv
index 9bceb93b20..78410c0573 100644
--- a/crates/ui-egui/src/i18n/gu.tsv
+++ b/crates/ui-egui/src/i18n/gu.tsv
@@ -1742,6 +1742,7 @@
Fail નાપાસ
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11).
The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે.
+ The closest color that passes {level}: click to apply it. {level} પાસ કરતો સૌથી નજીકનો રંગ: તેને લાગુ કરવા ક્લિક કરો.
Graphics Processor ગ્રાફિક્સ પ્રોસેસર
Graphics: {adapter} ગ્રાફિક્સ: {adapter}
Gravity ગ્રેવિટી
diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv
index 3bc5aaf219..1a8ad42007 100644
--- a/crates/ui-egui/src/i18n/hi.tsv
+++ b/crates/ui-egui/src/i18n/hi.tsv
@@ -2629,6 +2629,7 @@ arrowhead Feather पंख
Fail फ़ेल
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)।
The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है।
+ The closest color that passes {level}: click to apply it. {level} पास करने वाला सबसे नज़दीकी रंग: लागू करने के लिए क्लिक करें।
Graphics Processor ग्राफिक्स प्रोसेसर
Graphics: {adapter} ग्राफिक्स: {adapter}
Gravity ग्रेविटी
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index fedcfcf62b..9673b9779b 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -2082,6 +2082,7 @@ file-filter Templates Sablonok
Fail Nem felel meg
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11).
The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program.
+ The closest color that passes {level}: click to apply it. A legközelebbi szín, amely megfelel a(z) {level} szintnek: kattintson az alkalmazásához.
Graphics Processor Grafikus processzor
Graphics: {adapter} Grafika: {adapter}
Gravity Gravitáció
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 3c434256fa..52815fe174 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2736,6 +2736,7 @@ digits Malayalam Malayalam
Fail Gagal
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11).
The background is read at the center of the selection. Latar dibaca di tengah seleksi.
+ The closest color that passes {level}: click to apply it. Warna terdekat yang lolos {level}: klik untuk menerapkannya.
Local Libraries Pustaka lokal
Add Content Tambahkan konten
Click to apply to the selected type Klik untuk menerapkan ke teks terpilih
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 13d0656137..d980fb9bc8 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -1716,6 +1716,7 @@ file-filter Templates Modelli
Fail Non superato
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11).
The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione.
+ The closest color that passes {level}: click to apply it. Il colore più vicino che soddisfa {level}: fai clic per applicarlo.
Graphics Processor Processore grafico
Graphics: {adapter} Scheda grafica: {adapter}
Gravity Gravità
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 97606b7e76..c8419ff162 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -4457,6 +4457,7 @@ file-filter Templates テンプレート
Fail 不合格
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。
+ The closest color that passes {level}: click to apply it. {level} を満たす最も近いカラー:クリックで適用します。
Greek & Cyrillic ギリシャ文字とキリル文字
Hex by Column 六角形 (列)
Hex by Row 六角形 (行)
diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv
index a8d2240536..f5e48eb141 100644
--- a/crates/ui-egui/src/i18n/ka.tsv
+++ b/crates/ui-egui/src/i18n/ka.tsv
@@ -4135,6 +4135,7 @@ digits Malayalam მალაიალამური
Fail არ აკმაყოფილებს
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11).
The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში.
+ The closest color that passes {level}: click to apply it. უახლოესი ფერი, რომელიც აკმაყოფილებს {level}-ს: დააწკაპუნეთ მის გამოსაყენებლად.
Local Libraries ლოკალური ბიბლიოთეკები
Add Content შიგთავსის დამატება
Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 96e84b418e..9329b98a3e 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -4447,6 +4447,7 @@ file-filter Templates 템플릿
Fail 실패
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11).
The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다.
+ The closest color that passes {level}: click to apply it. {level}을(를) 충족하는 가장 가까운 색상: 클릭하여 적용합니다.
Greek & Cyrillic 그리스어 및 키릴 문자
Hex by Column 열 기준 육각형
Hex by Row 행 기준 육각형
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index fada1fc205..5571004089 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -2721,6 +2721,7 @@ digits Malayalam Malayalam
Fail Niet geslaagd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11).
The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten.
+ The closest color that passes {level}: click to apply it. De dichtstbijzijnde kleur die aan {level} voldoet: klik om deze toe te passen.
Local Libraries Lokale bibliotheken
Add Content Inhoud toevoegen
Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 01d3571047..d17e80a23a 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -2109,6 +2109,7 @@ digits Malayalam Malajalam
Fail Nie spełnia
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11).
The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia.
+ The closest color that passes {level}: click to apply it. Najbliższy kolor spełniający {level}: kliknij, aby go zastosować.
Local Libraries Biblioteki lokalne
Add Content Dodaj zawartość
Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index e3dd5ffeda..5830595a41 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -4139,6 +4139,7 @@ font-technology Variable Variáveis
Fail Reprovado
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11).
The background is read at the center of the selection. O fundo é lido no centro da seleção.
+ The closest color that passes {level}: click to apply it. A cor mais próxima que atende a {level}: clique para aplicá-la.
Highlight Rows Destacar linhas
Highlight Variable Destacar variável
Sort Variables Ordenar variáveis
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index a2235998eb..96badacf8d 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1701,6 +1701,7 @@ file-filter Templates Шаблоны
Fail Не соответствует
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон определяется в центре выделения.
+ The closest color that passes {level}: click to apply it. Ближайший цвет, соответствующий {level}: щёлкните, чтобы применить его.
Graphics Processor Графический процессор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv
index 41bda9072e..ca968fc94e 100644
--- a/crates/ui-egui/src/i18n/sv.tsv
+++ b/crates/ui-egui/src/i18n/sv.tsv
@@ -1635,6 +1635,7 @@ font-technology Variable Variabla
Fail Underkänd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11).
The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen.
+ The closest color that passes {level}: click to apply it. Den närmaste färgen som klarar {level}: klicka för att använda den.
Graphics Processor Grafikprocessor
Graphics: {adapter} Grafik: {adapter}
Gravity Gravitation
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index 0ee286faa1..c7ab4d49b9 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -1599,6 +1599,7 @@ font-technology Variable Değişken
Fail Kaldı
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11).
The background is read at the center of the selection. Arka plan seçimin ortasında okunur.
+ The closest color that passes {level}: click to apply it. {level} düzeyini karşılayan en yakın renk: uygulamak için tıklayın.
Graphics Processor Grafik İşlemcisi
Graphics: {adapter} Grafik: {adapter}
Gravity Yerçekimi
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index e9dd432e72..007055151c 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -1710,6 +1710,7 @@ file-filter Templates Шаблони
Fail Не відповідає
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон визначається в центрі виділення.
+ The closest color that passes {level}: click to apply it. Найближчий колір, що відповідає {level}: клацніть, щоб застосувати його.
Graphics Processor Графічний процесор
Graphics: {adapter} Графіка: {adapter}
Gravity Гравітація
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index 8e9d5cac87..0f4220e58a 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -1944,6 +1944,7 @@ file-filter Templates Mẫu
Fail Không đạt
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11).
The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn.
+ The closest color that passes {level}: click to apply it. Màu gần nhất đạt {level}: bấm để áp dụng.
Graphics Processor Bộ xử lý đồ họa
Graphics: {adapter} Đồ họa: {adapter}
Gravity Trọng lực
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index a7e94e826f..a347bd1d33 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1644,6 +1644,7 @@ file-filter Templates 模板
Fail 未通过
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在所选对象的中心读取。
+ The closest color that passes {level}: click to apply it. 符合 {level} 的最接近颜色:单击即可应用。
Gravity 重力
Grays 灰度级数
Grays and Neutrals 灰色和中性色
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 3a86a5b728..05f45ecb68 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1680,6 +1680,7 @@ file-filter Templates 範本
Fail 未通過
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在選取範圍的中心讀取。
+ The closest color that passes {level}: click to apply it. 符合 {level} 的最接近顏色:按一下即可套用。
Graphics Processor 圖形處理器
Graphics: {adapter} 圖形:{adapter}
Gravity 重力
diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs
index 6b0aac8b1f..ada6e2d516 100644
--- a/crates/ui-egui/src/menus/ui_commands.rs
+++ b/crates/ui-egui/src/menus/ui_commands.rs
@@ -1616,7 +1616,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
- "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}",
+ "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Opacity, Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the active document's RGB space (its assigned profile, else the working RGB space) is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, opacity, hexField, contrast, contrastFor, contrastBackground, vision, documentColors}",
),
(
"ui.savePdfDialog",
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 10172f2c5a..ab3c06f3b1 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -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;
diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs
index eae545899e..8239244ffb 100644
--- a/crates/ui-egui/src/panels/color_wheel.rs
+++ b/crates/ui-egui/src/panels/color_wheel.rs
@@ -38,6 +38,9 @@
//! () of the color against the color drawn
//! behind the selection, or against a color pinned with Contrast Background › Current Color, and
//! whether it meets AA and AAA for the category picked under Contrast For (`color.contrast`).
+//! The wheel's square and the box's field then draw lines where the color picked there would meet
+//! AA and AAA (AAA dashed), and when the color fails, a chip in the row offers the closest color
+//! that passes, the one `color.contrast` answers as `fix`.
//!
//! Panel menu › Show Color Vision Preview adds a row under the wheel or the box with the color as
//! simulated for protanopia, deuteranopia and tritanopia, through the simulations View › Proof
@@ -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) -> Vec {
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) -> Vec {
for c in Category::ALL {
out.push(item(category_row_id(c), category_name(c), set.contrast_for == c, true, json!({ "contrastFor": c.id() })));
}
- let pinned = set.contrast_background.is_some();
- out.push(item("contrastBackground.below".into(), tl!("Behind Selection"), !pinned, true, json!({ "contrastBackground": null })));
- let params = current.map_or(Value::Null, |c| json!({ "contrastBackground": crate::panels::color_json(&c) }));
- out.push(item("contrastBackground.current".into(), tl!("Current Color"), pinned, current.is_some(), params));
+ out.push(item(
+ "contrastBackground.below".into(),
+ tl!("Behind Selection"),
+ set.contrast_background.is_none(),
+ true,
+ json!({ "contrastBackground": null }),
+ ));
+ out.push(item(
+ "contrastBackground.current".into(),
+ tl!("Current Color"),
+ set.contrast_background.is_some(),
+ current.is_some(),
+ json!({ "contrastBackground": current.as_ref().map(color_json) }),
+ ));
out.push(item("vision".into(), tl!("Show Color Vision Preview"), set.vision, true, json!({ "vision": !set.vision })));
out.push(item(
"documentColors".into(),
@@ -575,20 +586,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec {
));
rows.push(PanelRow::Submenu(
Label::from(tl!("Contrast Background").to_string()),
- ["contrastBackground.below", "contrastBackground.current"].into_iter().map(|row| command(row.into())).collect(),
+ vec![command("contrastBackground.below".into()), command("contrastBackground.current".into())],
));
rows.extend(["vision", "documentColors"].map(|row| command(row.into())));
rows
}
-/// The menu rows of `app`'s settings, with the color the panel edits for Current Color.
-fn app_items(app: &VectorcraftApp) -> Vec {
- items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), super::color::target_now(app).color())
-}
-
/// The labels, checks and enabled states of [`menu_rows`].
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.`); `None` when it is not one of this panel's.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option> {
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, ¶ms))
}
@@ -673,10 +680,14 @@ pub struct WheelUi {
rows_live: Option,
/// Whether a drag of the Show Opacity row previews on an open interaction, until it is released.
opacity_live: bool,
- /// The color behind the selection, as `#rrggbb`, with the [`BehindKey`] it was read for.
+ /// The color behind the selection as `#rrggbb`, with the [`BehindKey`] it was read for.
pub(super) behind: Option<(BehindKey, Option)>,
/// The contrast row's `color.contrast` answer, with the [`RatioKey`] it was asked for.
pub(super) ratio: Option<(RatioKey, Option)>,
+ /// What the contrast row's answer was measured against, with the [`RatioKey`] it was asked for.
+ backdrop: Option<(RatioKey, Option)>,
+ /// The contrast lines of the square or the field, with the [`LinesKey`] they were found for.
+ pub(super) lines: Option<(LinesKey, Lines)>,
}
/// The colors the row shows and whether they are the selection's, read with `color.used` once per
@@ -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)>,
/// Whether the Live Paint Bucket paints, which gives the proxies its paints without a revision.
pub(super) bucket: bool,
+ /// The Contrast For category, which the closest passing colors are for.
+ pub(super) category: Category,
+}
+
+/// What the contrast lines depend on: what the color is measured against, the category, the field
+/// (the view, the channel and the component the field holds fixed) with the model a pick there
+/// stores, the color settings, and whether they were found coarsely during a drag.
+pub(super) type LinesKey = (Backdrop, Category, String, Under, bool);
+/// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates.
+pub(super) type Lines = Vec>>;
+
+/// The columns and rows at which [`contrast_lines`] samples a field.
+const LINE_SAMPLES: usize = 32;
+/// The columns and rows at which [`contrast_lines`] samples a field, without the narrow-band
+/// search, while a drag changes the field (the hue ring, the box's strip).
+const COARSE_LINE_SAMPLES: usize = 8;
+/// The halvings that place a line on the edge between two samples.
+const LINE_STEPS: usize = 10;
+
+/// A point of a field: x across, y down, 0 to 1 each.
+type FieldPoint = (f32, f32);
+
+/// The passing bands found between the samples of one column or row: where each peaks along it, and
+/// its two crossings.
+type Bands = Vec<(f32, FieldPoint, FieldPoint)>;
+
+/// The edge from sample (i, j) across (true) or down (false).
+type EdgeKey = (usize, usize, bool);
+
+/// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in
+/// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell
+/// whose edges are crossed gets segments between the crossings on its edges, placed by bisection
+/// (marching squares; a cell crossed more than twice, as one with two opposite corners passing, is
+/// split by its center).
+/// With `narrow`, around a failing sample higher than its neighbors in a column or a row, the highest
+/// ratio is looked for, so a passing band narrower than the samples gets its two edges too, joined
+/// from column to column or from row to row. Where no band on the next or the previous line joins
+/// one, its two crossings count among the crossings of the cell on that side, so a band that widens
+/// past the samples or ends there is joined to the cell's other crossings instead of being cut
+/// across. Segments that share an end are joined into one polyline.
+pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64], n: usize, narrow: bool) -> Lines {
+ let n = n.max(1);
+ let at = |i: usize| i as f32 / n as f32;
+ // `grid[i][j]` is column i (x) and row j (y).
+ let grid: Vec> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect();
+ let r = |i: usize, j: usize| grid.get(i).and_then(|c| c.get(j)).copied().unwrap_or(f64::NAN);
+ minimums
+ .iter()
+ .map(|&min| {
+ let pass = |p: FieldPoint| ratio_at(p.0, p.1) >= min;
+ // The crossing between `p`, on the side `above` says, and `q`.
+ let cross = |p: FieldPoint, q: FieldPoint, above: bool| {
+ let lerp = |t: f32| (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t);
+ let (mut lo, mut hi) = (0.0, 1.0);
+ for _ in 0..LINE_STEPS {
+ let mid = (lo + hi) / 2.0;
+ if pass(lerp(mid)) == above { lo = mid } else { hi = mid }
+ }
+ lerp((lo + hi) / 2.0)
+ };
+ let mut edges: HashMap<(usize, usize, bool), Option> = HashMap::new();
+ // The crossing on the edge from sample (i, j) across (`across`) or down.
+ let mut edge = |i: usize, j: usize, across: bool| {
+ *edges.entry((i, j, across)).or_insert_with(|| {
+ let (i2, j2) = if across { (i + 1, j) } else { (i, j + 1) };
+ let (a, b) = (r(i, j) >= min, r(i2, j2) >= min);
+ (a != b).then(|| cross((at(i), at(j)), (at(i2), at(j2)), a))
+ })
+ };
+ let mut segments: Vec<[FieldPoint; 2]> = vec![];
+ // The crossings of the bands narrower than the samples on each edge between samples, with
+ // whether no band on the next line (the column to the right, the row below) and no band on
+ // the line before joins the band on that side.
+ let mut loose: HashMap> = HashMap::new();
+ // Bands narrower than the samples, along each column and then each row.
+ for across in [false, true].into_iter().filter(|_| narrow) {
+ let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) };
+ let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) };
+ let bands: Vec = (0..=n)
+ .map(|k| {
+ let mut found = vec![];
+ for s in 0..=n {
+ let (before, after) = (s.saturating_sub(1), (s + 1).min(n));
+ let v = value(k, s);
+ if v >= min || v < value(k, before) || (after != s && v <= value(k, after)) {
+ continue;
+ }
+ let peak = wcag::peak_between(f64::from(at(before)), f64::from(at(after)), &|t| {
+ let p = point(k, t as f32);
+ ratio_at(p.0, p.1)
+ }) as f32;
+ if pass(point(k, peak)) {
+ found.push((
+ peak,
+ cross(point(k, at(before)), point(k, peak), false),
+ cross(point(k, peak), point(k, at(after)), true),
+ ));
+ }
+ }
+ found
+ })
+ .collect();
+ // The band of `next` that the band peaking at `peak` joins.
+ let joins = |next: &Bands, peak: f32| next.iter().position(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32);
+ for (k, this) in bands.iter().enumerate() {
+ let next = bands.get(k + 1);
+ let before = k.checked_sub(1).and_then(|k| bands.get(k));
+ for (b, &(peak, p, q)) in this.iter().enumerate() {
+ let joined = next.and_then(|next| joins(next, peak).and_then(|m| next.get(m)));
+ if let Some(&(_, c, d)) = joined {
+ segments.extend([[p, c], [q, d]]);
+ }
+ let joined_before = before.is_some_and(|before| before.iter().any(|(bp, ..)| joins(this, *bp) == Some(b)));
+ let e = ((peak * n as f32).floor() as usize).min(n - 1);
+ let key = if across { (e, k, true) } else { (k, e, false) };
+ let open = [joined.is_none(), !joined_before];
+ loose.entry(key).or_default().extend([(p, open), (q, open)]);
+ }
+ }
+ }
+ for i in 0..n {
+ for j in 0..n {
+ let (x0, y0, w) = (at(i), at(j), 1.0 / n as f32);
+ // Where point `p` on edge `s` (0 to 3: top, right, bottom, left) lies going around
+ // the cell clockwise from its top left corner.
+ let place = |s: usize, p: FieldPoint| match s {
+ 0 => (p.0 - x0) / w,
+ 1 => 1.0 + (p.1 - y0) / w,
+ 2 => 2.0 + (x0 + w - p.0) / w,
+ _ => 3.0 + (y0 + w - p.1) / w,
+ };
+ // The cell's edges, each with the side of the edge's line the cell is on: after
+ // its top and left edges' lines (0) and before its right and bottom edges' (1).
+ let sides = [((i, j, true), 0), ((i + 1, j, false), 1), ((i, j + 1, true), 1), ((i, j, false), 0)];
+ let mut around: Vec<(f32, FieldPoint)> = vec![];
+ for (s, (key, side)) in sides.into_iter().enumerate() {
+ let (ei, ej, across) = key;
+ around.extend(edge(ei, ej, across).map(|p| (place(s, p), p)));
+ let band = loose.get(&key).into_iter().flatten().filter(|(_, open)| open.get(side).copied().unwrap_or(false));
+ around.extend(band.map(|&(p, _)| (place(s, p), p)));
+ }
+ around.sort_by(|a, b| a.0.total_cmp(&b.0));
+ let m = around.len();
+ if m < 2 {
+ continue;
+ }
+ // Going around from the top left corner, the side changes at each crossing. Where
+ // the crossings leave more than one passing stretch of the edges, the center says
+ // whether those stretches join inside the cell (the segments cut off the failing
+ // stretches) or not (they cut off the passing ones).
+ let corner = r(i, j) >= min;
+ let half = 0.5 / n as f32;
+ let cut = if m == 2 { !corner } else { !pass((x0 + half, y0 + half)) };
+ // The stretch between crossings 0 and 1 is on the side the corner is not.
+ let start = usize::from(corner == cut);
+ for k in (start..m).step_by(2) {
+ if let (Some(&(_, p)), Some(&(_, q))) = (around.get(k), around.get((k + 1) % m)) {
+ segments.push([p, q]);
+ }
+ }
+ }
+ }
+ chain(segments)
+ })
+ .collect()
+}
+
+/// `segments` joined end to end into polylines where they share an end.
+fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec> {
+ let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits());
+ let mut ends: HashMap<(u32, u32), Vec> = HashMap::new();
+ for (s, seg) in segments.iter().enumerate() {
+ for p in seg {
+ ends.entry(key(*p)).or_default().push(s);
+ }
+ }
+ let mut used = vec![false; segments.len()];
+ let mut lines = vec![];
+ for (start, [a, b]) in segments.iter().enumerate() {
+ if used.get(start).copied().unwrap_or(true) {
+ continue;
+ }
+ if let Some(u) = used.get_mut(start) {
+ *u = true;
+ }
+ let mut line = std::collections::VecDeque::from([*a, *b]);
+ for back in [true, false] {
+ loop {
+ let end = if back { line.back() } else { line.front() };
+ let Some(end) = end.copied() else { break };
+ let next = ends.get(&key(end)).and_then(|ss| ss.iter().copied().find(|s| !used.get(*s).copied().unwrap_or(true)));
+ let Some((s, [p, q])) = next.and_then(|s| segments.get(s).map(|seg| (s, *seg))) else { break };
+ if let Some(u) = used.get_mut(s) {
+ *u = true;
+ }
+ let other = if key(p) == key(end) { q } else { p };
+ if back { line.push_back(other) } else { line.push_front(other) }
+ }
+ }
+ lines.push(line.into_iter().collect());
+ }
+ lines
+}
+
+/// The contrast lines of the wheel's square or the box's field on HSB `hsb`, kept per [`LinesKey`]:
+/// where a pick there, stored as the wheel stores it in place of `tgt`'s color, meets each minimum
+/// of the chosen category against `backdrop`. While a drag is live and the field differs from the
+/// one the kept lines were found for, the lines are found coarsely ([`COARSE_LINE_SAMPLES`]), and
+/// in full once the drag ends.
+fn lines_for(app: &VectorcraftApp, panel: &mut WheelUi, backdrop: &Backdrop, cx: &Pick) -> Lines {
+ let set = &app.ui.color_wheel;
+ let (category, view) = (set.contrast_for, set.view);
+ // The wheel's square is the field of the hue box.
+ let ch = if view == View::Box { set.channel } else { Channel::Hue };
+ let was = replaced(app, cx.tgt, false);
+ let hsb = cx.shown;
+ let field = format!("{view:?} {ch:?} {} {:?} {}", field_fixed(ch, hsb), was.map(|c| c.model()), cx.cmyk_doc);
+ let dragging = app.session.in_interaction();
+ let key = |coarse: bool| -> LinesKey { (backdrop.clone(), category, field.clone(), under(), coarse) };
+ if let Some((k, lines)) = &panel.lines
+ && (*k == key(false) || (dragging && *k == key(true)))
+ {
+ return lines.clone();
+ }
+ let ratio_at = |x: f32, y: f32| backdrop.ratio(backdrop.shown(cx.cms, &stored(cx.cms, field_pick(ch, x, y, hsb), was.as_ref(), cx.cmyk_doc)));
+ let (aa, aaa) = category.minimums();
+ let minimums: Vec = std::iter::once(aa).chain(aaa).collect();
+ let samples = if dragging { COARSE_LINE_SAMPLES } else { LINE_SAMPLES };
+ let lines = contrast_lines(&ratio_at, &minimums, samples, !dragging);
+ panel.lines = Some((key(dragging), lines.clone()));
+ lines
+}
+
+/// Draw `lines` (from [`contrast_lines`]) over the field in `rect`: AA solid and AAA dashed, each
+/// a light line over a dark one, as the field's marker is drawn.
+fn draw_contrast_lines(ui: &Ui, rect: Rect, lines: &Lines) {
+ let painter = ui.painter().with_clip_rect(rect);
+ let at = |(x, y): &(f32, f32)| egui::pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height());
+ for (level, polylines) in lines.iter().enumerate() {
+ for line in polylines {
+ let points: Vec = line.iter().map(at).collect();
+ for stroke in [Stroke::new(3.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] {
+ if level == 0 {
+ painter.add(egui::Shape::line(points.clone(), stroke));
+ } else {
+ painter.extend(egui::Shape::dashed_line(&points, stroke, 4.0, 3.0));
+ }
+ }
+ }
+ }
}
/// The active color settings and profiles generation, which change how a color displays without
@@ -927,9 +1209,19 @@ fn background(app: &mut VectorcraftApp, panel: &mut WheelUi) -> Option {
Color::from_hex(&hex?)
}
-/// The `color.contrast` answer against `pinned`, else against the color behind the selection
-/// (`against: "below"`), kept per [`RatioKey`].
-fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option) -> Option {
+/// The contrast row's measurement: `color.contrast`'s answer for the chosen category, and what the
+/// lines measure picks against.
+struct Measured {
+ answer: Option,
+ backdrop: Option,
+}
+
+/// The `color.contrast` answer for the chosen category against the pinned background, else
+/// against the color behind the selection (`against: "below"`), with what it measured the color
+/// against, kept per [`RatioKey`].
+fn measure(app: &VectorcraftApp, panel: &mut WheelUi) -> Measured {
+ let category = app.ui.color_wheel.contrast_for;
+ let pinned = app.ui.color_wheel.contrast_background;
let st = app.session.active();
let key = RatioKey {
background: pinned.map_or_else(|| "below".to_string(), |bg| format!("{bg:?}")),
@@ -945,33 +1237,43 @@ fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option r.clone(),
+ match (&panel.ratio, &panel.backdrop) {
+ (Some((k, answer)), Some((kb, backdrop))) if *k == key && *kb == key => Measured { answer: answer.clone(), backdrop: backdrop.clone() },
_ => {
- let against = pinned.as_ref().map_or_else(|| json!("below"), crate::panels::color_json);
- let r = app.session.execute("color.contrast", &json!({ "against": against })).ok();
- panel.ratio = Some((key, r.clone()));
- r
+ let against = pinned.as_ref().map_or_else(|| json!("below"), color_json);
+ let p = json!({ "against": against, "for": category.id() });
+ // With no color to measure (a fill of None, a pattern), a pick there is still measured.
+ let (answer, backdrop) = match contrast_measure(&app.session, &p) {
+ Ok((r, b)) => (Some(r), Some(b)),
+ Err(_) => (None, contrast_pick_backdrop(&app.session, &p).ok()),
+ };
+ panel.ratio = Some((key.clone(), answer.clone()));
+ panel.backdrop = Some((key, backdrop.clone()));
+ Measured { answer, backdrop }
}
}
}
-/// The contrast row: the background's chip, the ratio cut off at two decimals and the AA and AAA
-/// results for the chosen category; a dash when there is no background or no color to measure.
-/// Without a pinned background the row asks `color.contrast` for the color behind the selection
-/// (`against: "below"`), also during an interaction, so translucent groups and layers count as the
-/// command counts them; the chip then shows the background in the answer. Only when there is no
-/// answer is the background read on its own ([`background`]), so the chip still shows it. The chip
-/// is a color well named Background whose value is the background's hex value, as the color vision
-/// chips are; a click on it does nothing.
-fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms) {
+/// The contrast row: the background's chip, the ratio cut off at two decimals, the AA and AAA
+/// results for the chosen category, and a chip of the closest color that passes the first level the
+/// color fails, when `color.contrast` finds one for that level; a dash when there is no background
+/// or no color to measure. Without a pinned background the row asks `color.contrast` for the color
+/// behind the selection (`against: "below"`), also during an interaction, so translucent groups and
+/// layers count as the command counts them. The first chip shows the background the answer
+/// measured against, pinned or not, else the one a pick would be measured against (a pinned 100 %
+/// K shows as black with a rich black Appearance of Black). Only when there is neither is the
+/// background read on its own ([`background`]), so the chip still shows it. The chip is named
+/// Background, with the background's hex value as its value, as the color vision chips are.
+/// Returns the fix color when its chip is clicked or activated.
+fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms, m: &Measured) -> Option {
let category = app.ui.color_wheel.contrast_for;
let pinned = app.ui.color_wheel.contrast_background;
- let answer = ratio_answer(app, panel, pinned);
- // The background the ratio was measured against.
- let measured = answer.as_ref().filter(|_| pinned.is_none()).and_then(|r| r["against"].as_str()).and_then(Color::from_hex);
- let chip = match pinned.or(measured) {
+ let answer = m.answer.as_ref();
+ let against = answer.and_then(|r| r["against"].as_str().map(str::to_string)).or_else(|| m.backdrop.as_ref().map(Backdrop::against_hex));
+ let measured = against.as_deref().and_then(Color::from_hex);
+ let chip = match measured.or(pinned) {
Some(c) => Some(c),
None => background(app, panel),
};
@@ -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) -> Option {
+ let level = if !aa {
+ Some(("aa", "AA"))
+ } else if aaa == Some(false) {
+ Some(("aaa", "AAA"))
+ } else {
+ None
+ };
+ let (color, name) = level.and_then(|(key, name)| {
+ let v = answer?.get("fix")?.get(key)?;
+ serde_json::from_value::(v.clone()).ok().map(|c| (c, name))
+ })?;
+ let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]);
+ let entries = [(Label::from(label), srgb(cms.display_rgb(&color)))];
+ let out = SwatchTable::new(tl!("Closest Passing Color").to_string(), &entries)
+ .per_row(1)
+ .tips(true)
+ .activate(ActivateOn::Click)
+ // The chip applies by click and holds no selection of its own.
+ .selection(Bind::given(Selection::default()))
+ .show_all(ui);
+ out.open.map(|_| color)
}
/// What the HSB picked last belongs to: the document, the selected objects or text characters,
@@ -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) {
let marked = cx.color.is_some();
let others: Vec<[f32; 3]> = if set.harmony && marked { set.harmony_rule.apply_hsb(cx.shown).into_iter().skip(1).collect() } else { Vec::new() };
let markers: Vec = others.iter().map(|&hsb| srgb(hsb_to_rgb(hsb))).collect();
@@ -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) {
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());
diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs
index b26c84c00d..2f938cc8e2 100644
--- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs
+++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs
@@ -1,13 +1,11 @@
-//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and
-//! the AA and AAA results, the color behind the selection, a pinned background, a drag on the
-//! wheel, the panel menu and `ui.colorWheel`.
+//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and the
+//! AA and AAA results, the color behind the selection, a pinned background, the panel menu, a drag
+//! on the wheel, and `ui.colorWheel`.
-use craft::ui::runtime::access::Role;
use serde_json::{Value, json};
use vectorcraft_color::wcag;
use vectorcraft_engine::Session;
-use super::color_wheel::{BehindKey, RatioKey};
use super::tests_color_wheel::Panel;
use crate::VectorcraftApp;
use crate::i18n::LangExt as _;
@@ -26,6 +24,18 @@ fn shows(p: &Panel, text: &str) -> bool {
p.fx.by_label(text).is_some()
}
+/// The background read on its own, as `#rrggbb`, if the row read one.
+fn behind(p: &Panel) -> Option