Merge pull request #9005 from dotCooCoo/feat/color-wheel-contrast-lines

Color Wheel: the box and the wheel mark the contrast lines and offer the closest passing color
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 19:39:31 -08:00
commit 4f7fe4556e
43 files changed
+1639 -230

No files matched your search

+151
View File
@@ -2,6 +2,7 @@
//! the relative luminance of display sRGB with the 0.04045 threshold, the ratio
//! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3
//! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA).
//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum.
/// What the content in front is, which sets the ratio it needs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -87,6 +88,82 @@ pub fn ratio_text(ratio: f64) -> String {
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
}
/// The lightnesses [`closest_passing`] tests on each side before it narrows down the first that
/// passes.
const LIGHTNESS_SAMPLES: usize = 16;
/// The halvings [`closest_passing`] makes of the lightness step, which leave it within 1e-9.
const LIGHTNESS_STEPS: usize = 32;
/// The golden-section steps [`closest_passing`] takes to find the highest ratio between samples,
/// which leave it within 1e-7 of the step.
const PEAK_STEPS: usize = 32;
/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a
/// single peak between them. `f` is called 34 times.
pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 {
let g = (5f64.sqrt() - 1.0) / 2.0;
let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo));
let (mut fa, mut fb) = (f(a), f(b));
for _ in 0..PEAK_STEPS {
if fa < fb {
(lo, a, fa) = (a, b, fb);
b = lo + g * (hi - lo);
fb = f(b);
} else {
(hi, b, fb) = (b, a, fa);
a = hi - g * (hi - lo);
fa = f(a);
}
}
if fa > fb { a } else { b }
}
/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue
/// (<https://bottosson.github.io/posts/oklab/>) with the lightness raised or lowered, whichever
/// takes the smaller step, and the chroma lowered where sRGB cannot show it, to the largest chroma
/// below it that fits ([`crate::oklab::from_oklch`]). Each side is tested at
/// 16 even steps up to white or black, and the step before the first that passes is narrowed down.
/// When no step passes, the highest ratio between the neighbors of the highest step is looked for,
/// so a color that passes only in a narrow band between white and black (as under a Difference
/// blend) is found too. `srgb` itself when it passes, and None when nothing passes. The work is
/// bounded: at most 167 colors are tested. The answer is the nearest passing color when the colors
/// that pass on each side form one stretch up to white or black, as for a plain contrast ratio.
/// When `ratio` lets colors pass in more than one stretch, a stretch that lies between two tested
/// steps before the first passing one is missed, and a farther color can be returned.
pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> f64) -> Option<[f32; 3]> {
let passes = |c: [f32; 3]| ratio(c) >= minimum;
let srgb = srgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
if passes(srgb) {
return Some(srgb);
}
let [l, c, h] = crate::oklab::to_oklch(srgb);
let mut best: Option<(f64, [f32; 3])> = None;
for end in [1.0, 0.0] {
let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0;
let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64;
let ratios: Vec<f64> = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect();
// `lo` fails and `hi` passes, the step before the first sample that passes.
let found = match ratios.iter().position(|r| *r >= minimum) {
Some(i) => Some((step(i), step(i + 1))),
None => {
// Every sample fails: look for a higher ratio around the highest one.
let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0;
let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES)));
let peak = peak_between(lo, hi, &|t| ratio(at(t)));
passes(at(peak)).then_some((lo, peak))
}
};
let Some((mut lo, mut hi)) = found else { continue };
for _ in 0..LIGHTNESS_STEPS {
let mid = (lo + hi) / 2.0;
if passes(at(mid)) { hi = mid } else { lo = mid }
}
let step = (end - l).abs() * hi;
if best.is_none_or(|(d, _)| step < d) {
best = Some((step, at(hi)));
}
}
best.map(|(_, c)| c)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -137,6 +214,80 @@ mod tests {
assert_eq!(Category::parse("NormalText"), None);
}
fn hue(srgb: [f32; 3]) -> f64 {
let [_, a, b] = crate::libraries::srgb_to_oklab(srgb);
b.atan2(a).to_degrees()
}
#[test]
fn the_closest_passing_color_keeps_the_hue_and_just_passes() {
let (fg, bg) = (hex("fdc96e"), hex("355f78"));
let fix = closest_passing(fg, 4.5, &|c| contrast_ratio(c, bg)).unwrap();
let r = contrast_ratio(fix, bg);
assert!((4.5..4.501).contains(&r), "{r}");
assert!((hue(fix) - hue(fg)).abs() < 1.0, "{} {}", hue(fix), hue(fg));
// A color lighter than the background gets lighter.
assert!(relative_luminance(fix) > relative_luminance(fg));
}
#[test]
fn the_closest_passing_gray_on_white_is_a_darker_gray() {
let white = [1.0; 3];
let fix = closest_passing(hex("777777"), 4.5, &|c| contrast_ratio(c, white)).unwrap();
let r = contrast_ratio(fix, white);
assert!((4.5..4.501).contains(&r), "{r}");
assert!((fix[0] - fix[1]).abs() < 1e-4 && (fix[1] - fix[2]).abs() < 1e-4, "{fix:?}");
}
#[test]
fn a_color_that_passes_only_between_white_and_black_is_found() {
// White drawn with Difference over mid gray: white and black both draw mid gray (1:1), and
// mid gray draws black, 5.3:1.
let gray = [0.5; 3];
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
let fix = closest_passing([1.0; 3], 4.5, &|c| contrast_ratio(difference(c), gray)).unwrap();
let r = contrast_ratio(difference(fix), gray);
assert!((4.5..4.51).contains(&r), "{fix:?}: {r}");
assert!(fix[0] > 0.5, "the nearest side of mid gray from white: {fix:?}");
}
#[test]
fn a_narrow_band_between_the_samples_is_found() {
// Over #5A5A5A only colors within a few hundredths of it draw dark enough with Difference
// for 3:1 (black reaches 3.04:1), and no even step from white lands there.
let gray = hex("5a5a5a");
let difference = |c: [f32; 3]| -> [f32; 3] { std::array::from_fn(|i| (c[i] - gray[i]).abs()) };
let ratio = |c: [f32; 3]| contrast_ratio(difference(c), gray);
let fix = closest_passing([1.0; 3], 3.0, &ratio).unwrap();
let r = ratio(fix);
assert!((3.0..3.01).contains(&r), "{fix:?}: {r}");
}
/// Just below blue's lightness the chromas sRGB holds at blue's hue come in two stretches, so a
/// blue that needs a little more contrast keeps nearly all of its chroma.
#[test]
fn a_blue_that_darkens_a_little_keeps_its_chroma() {
let gray = hex("b8b8b8");
let ratio = |c: [f32; 3]| contrast_ratio(c, gray);
let blue = [0.0, 0.0, 1.0];
assert!(ratio(blue) < 4.5, "{}", ratio(blue));
let fix = closest_passing(blue, 4.5, &ratio).unwrap();
let ([_, c, h], [_, blue_c, blue_h]) = (crate::oklab::to_oklch(fix), crate::oklab::to_oklch(blue));
assert!(ratio(fix) >= 4.5 && (h - blue_h).abs() < 1.0, "{fix:?}");
assert!(c > blue_c - 0.02, "{fix:?}: chroma {c}, blue's {blue_c}");
}
#[test]
fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() {
let white = [1.0; 3];
assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3]));
assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None);
// Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches.
let mid = hex("777777");
assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None);
assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3]));
}
#[test]
fn half_opaque_black_over_white_is_mid_gray() {
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
+1
View File
@@ -851,6 +851,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, selection_fold_lines};
pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
+320 -72
View File
@@ -151,7 +151,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Contrast",
[],
None,
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color)} the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}",
"{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color` or while the active tool paints with the proxy's color), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} (with \"below\", a color drawn with a blend mode other than Normal over art that is not one color where it is read is an error) the WCAG 2 contrast ratio (https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, drawn at that opacity over the background with the blend modes the proxy's color is drawn with (its row's, the object's and those of its groups and layer, innermost first, each blending the result with the art below it inside the object, groups and layer around it, the object's rows below its row included (with `against` or `opacity` given, with the background); inside an object, group or layer that isolates its blending, the modes blend only with the art it holds; Normal for a given `color` or while the active tool paints with the proxy's color), against the background, in display sRGB: normal text needs 4.5:1 for AA and 7:1 for AAA, large text 3:1 and 4.5:1, and graphics 3:1 for AA; the unrounded ratio is compared → {ratio, against: \"#rrggbb\" (the background in working RGB, as `against` takes it; the sampled one rounded to 8 bits, so giving it back answers the same ratio unless `opacity` is omitted and a group or layer around the object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over rows below it, since a given background stands for the art below each such level), normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}, for, fix: {aa, aaa (not for graphics)}: for each level of `for`, the closest color that meets it, drawn the same way, in the model of the measured color (as the Color Wheel stores a pick): the same OKLCH hue with the lightness raised or lowered, whichever takes the smaller step, and the chroma lowered where sRGB cannot show it, that also meets the level with the color, the background, the art below each group or layer, the opacities, and the color and alpha each level gives rounded to 8 bits per channel (16 lightnesses are tested on each side and the first that passes is narrowed down, so where the passing ones fall apart in more than one stretch, a nearer one between two tested can be missed); null when the color already meets the level, or when no lightness of its hue does}",
always,
contrast
),
@@ -1032,7 +1032,229 @@ const BELOW_SIDE: f64 = 1.0;
/// The pixels per point [`color_below`] renders at.
const BELOW_SCALE: f64 = 4.0;
/// What `color.contrast` measures a color against: the background, and how the color is drawn over
/// it (its row, object, groups and layer, each with its blend mode and opacity over the art below
/// it). The Color Wheel panel's contrast lines measure many colors against one.
#[derive(Clone, Debug, PartialEq)]
pub struct Backdrop {
/// The background in display sRGB.
against: [f32; 3],
/// The background in working RGB, rounded to 8 bits, as the answer writes it.
written: [u8; 3],
/// The levels the color is drawn through, innermost first, without those that leave it as it is.
passes: Vec<Pass>,
/// The color and amount a fill stains the picked object of a dynamic symbol instance with.
stain: Option<(Color, f32)>,
/// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black).
rich_black: bool,
}
/// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color
/// and its alpha), whether it blends without isolating or isolates its blending, and the alpha of
/// the art below it inside the level around it, while a blending level lies further out.
#[derive(Clone, Debug, PartialEq)]
struct Pass {
blend: BlendMode,
opacity: f32,
backdrop: ([f32; 3], f32),
blends: bool,
isolate: bool,
inner: f32,
}
/// A color drawn through the levels so far: the color, its alpha, and the alpha of what the next
/// level out holds drawn alone.
type Through = ([f32; 3], f32, f32);
impl Pass {
/// What the level draws for color and alpha `x`, drawn over the art below it: a level that
/// blends takes that art back out by `alone`, the alpha of what it holds drawn alone.
fn source(&self, x: ([f32; 3], f32), alone: f32) -> ([f32; 3], f32) {
if !self.blends {
return x;
}
if alone <= 0.0 {
return (x.0, 0.0);
}
let b = self.backdrop;
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * b.0[i] * b.1) / alone).clamp(0.0, 1.0)), alone)
}
/// `d` drawn through the level. The level's opacity applies to what it holds, a level that
/// isolates its blending carries out the alpha of what it holds composited on its own, and the
/// art beside it in the level around it adds to the alpha once.
fn draw(&self, (color, alpha, alone): Through) -> Through {
let source = self.source((color, alpha), alone);
let drawn = if self.isolate { alpha } else { alone } * self.opacity.clamp(0.0, 1.0);
let (color, alpha) = composite(self.blend, source, self.opacity, self.backdrop);
(color, alpha, drawn + self.inner * (1.0 - drawn))
}
/// The level with its opacity, the art below it and its alphas passed through `q`.
fn with(&self, q: impl Fn(f32) -> f32) -> Pass {
let (color, alpha) = self.backdrop;
Pass { opacity: q(self.opacity), backdrop: (color.map(&q), q(alpha)), inner: q(self.inner), ..self.clone() }
}
}
impl Backdrop {
/// `c` as the measured object draws it: the picked object of a dynamic symbol instance that a
/// fill stains mixes its solid color towards the stain.
pub fn drawn_color(&self, c: &Color) -> Color {
match self.stain {
Some((stain, amount)) => c.lerp(&stain, amount),
None => *c,
}
}
/// The display sRGB the canvas shows for `c` drawn as the measured object draws it, through
/// `cms` and the Appearance of Black the backdrop was read with.
pub fn shown(&self, cms: &vectorcraft_color::cms::Cms, c: &Color) -> [f32; 3] {
shown_rgb(cms, self.rich_black, &self.drawn_color(c))
}
/// Display sRGB `shown`, drawn as the measured color is drawn, over the background.
pub fn front(&self, shown: [f32; 3]) -> [f32; 3] {
let (color, alpha, _) = self.passes.iter().fold((shown, 1.0f32, 1.0f32), |d, p| p.draw(d));
if alpha >= 1.0 { color } else { wcag::over(color, alpha, self.against) }
}
/// The contrast ratio of display sRGB `shown`, drawn as the measured color is drawn, against
/// the background.
pub fn ratio(&self, shown: [f32; 3]) -> f64 {
wcag::contrast_ratio(self.front(shown), self.against)
}
/// [`Backdrop::ratio`] with every value rounded to 8 bits per channel: the color, the art
/// below each level, the background, the opacities, and the color and alpha each level gives.
fn ratio_at_eight_bits(&self, shown: [f32; 3]) -> f64 {
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
let painted = |c: [f32; 3]| c.map(eight);
let against = painted(self.against);
let (color, alpha, _) = self.passes.iter().fold((painted(shown), 1.0f32, 1.0f32), |d, p| {
let (color, alpha, alone) = p.with(eight).draw(d);
(painted(color), eight(alpha), eight(alone))
});
let front = if alpha >= 1.0 { color } else { wcag::over(color, alpha, against) };
wcag::contrast_ratio(painted(front), against)
}
/// The background as `#rrggbb` in working RGB, the form a color param takes.
pub fn against_hex(&self) -> String {
let [r, g, b] = self.written;
format!("#{r:02x}{g:02x}{b:02x}")
}
}
/// The display sRGB the canvas shows for `c` through `cms`: with a rich black Appearance of Black,
/// 100 % K alone shows as black.
fn shown_rgb(cms: &vectorcraft_color::cms::Cms, rich_black: bool, c: &Color) -> [f32; 3] {
match *c {
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
_ => cms.display_rgb(c),
}
}
/// Display sRGB `srgb` as a color in the model of `like`, as a pick on the Color Wheel stores it:
/// an RGB color in the working RGB space, a CMYK or Lab color converted with the color settings, a
/// Gray color as gray.
fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) -> Color {
let [r, g, b] = cms.srgb_to_rgb(srgb);
let rgb = Color::rgb(r, g, b);
match like {
Color::Rgb { .. } => rgb,
Color::Cmyk { .. } => {
let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent);
Color::cmyk(c, m, y, k)
}
Color::Lab { .. } => {
let l = cms.lab(&rgb);
Color::lab(l.l, l.a, l.b)
}
Color::Gray { .. } => keep_model(*like, rgb),
}
}
/// The closest color in the model of `color` whose contrast against `backdrop` meets `minimum`
/// ([`wcag::closest_passing`]), checked as the canvas shows it once stored (a symbol's stain
/// included). A candidate meets it by [`Backdrop::ratio`] and also with its values rounded to 8
/// bits per channel ([`Backdrop::ratio_at_eight_bits`]). None when `color` already meets it by
/// [`Backdrop::ratio`], or when no lightness of its hue does.
fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option<Color> {
let cms = vectorcraft_color::cms::active();
let ratio = |srgb: [f32; 3]| {
let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color));
backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown))
};
if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum {
return None;
}
let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?;
Some(in_model_of(&cms, fix, color))
}
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
contrast_measure(s, p).map(|(answer, _)| answer)
}
/// `color.contrast`'s answer for params `p`, and what it measured the color against.
pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> {
const C: &str = "color.contrast";
let category = match p.get("for") {
None | Some(Value::Null) => Category::NormalText,
Some(v) => {
let key = "for";
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))?
}
};
let (color, backdrop) = contrast_backdrop(s, p)?;
let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color));
let levels = |c: Category| {
let (aa, aaa) = c.passes(ratio);
match aaa {
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
None => json!({ "aa": aa }),
}
};
let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) {
Some(c) => serde_json::to_value(c).unwrap_or(Value::Null),
None => Value::Null,
};
let fixes = match category.minimums() {
(aa, Some(aaa)) => json!({ "aa": fix(aa), "aaa": fix(aaa) }),
(aa, None) => json!({ "aa": fix(aa) }),
};
let answer = json!({
"ratio": ratio,
"against": backdrop.against_hex(),
"normalText": levels(Category::NormalText),
"largeText": levels(Category::LargeText),
"graphics": levels(Category::Graphics),
"for": category.id(),
"fix": fixes,
});
Ok((answer, backdrop))
}
/// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and
/// what it measures it against.
fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> {
let (color, backdrop) = contrast_reading(s, p, true)?;
let color = color.ok_or_else(|| bad("color.contrast", no_color()))?;
Ok((color, backdrop))
}
/// What a color picked for the active proxy would be measured against by `color.contrast` with
/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the
/// Color Wheel's contrast lines show where a pick would pass.
pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result<Backdrop> {
contrast_reading(s, p, false).map(|(_, backdrop)| backdrop)
}
/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when
/// `need_color`.
fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option<Color>, Backdrop)> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
@@ -1044,23 +1266,28 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
let given = p.get("color").is_some_and(|v| !v.is_null());
let (color, drawn) = match p.get("color") {
None | Some(Value::Null) => proxy_color(s, opacity.is_some(), below).map_err(|e| bad(C, e))?,
Some(v) => (color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?, Drawn::default()),
Some(v) => (Some(color_value(v).ok_or_else(|| bad(C, "invalid `color`"))?), Drawn::default()),
};
if need_color && color.is_none() {
return Err(bad(C, no_color()));
}
let rich_black = s.prefs.black_on_screen == "rich";
let cms = vectorcraft_color::cms::active();
let shown = |c: &Color| match *c {
Color::Cmyk { c, m, y, k } if rich_black && c <= 0.0 && m <= 0.0 && y <= 0.0 && k >= 1.0 => [0.0; 3],
_ => cms.display_rgb(c),
};
let shown = |c: &Color| shown_rgb(&cms, rich_black, c);
let to_8bit = |c: [f32; 3]| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8);
// Whether the background read is one color across its pixels.
let mut uniform = true;
// The background in display sRGB, and as the working RGB `#rrggbb` a given `against` reads as.
let (against, written) = match p.get("against").filter(|_| !below) {
None => {
// The sample in working RGB, rounded to 8 bits: the background the answer writes is the
// one the ratio uses, and giving it back answers the same ratio.
let working = to_8bit(cms.srgb_to_rgb(color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?.0));
let ((sample, _), one) = color_below(s, rich_black, None, &[], None).map_err(|e| bad(C, e))?;
uniform &= one;
let working = to_8bit(cms.srgb_to_rgb(sample));
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
}
Some(v) => {
@@ -1096,60 +1323,51 @@ fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
// then takes that art back out by the alpha of what it holds drawn alone, and blends the rest:
// `alone` is the alpha of what the next level out holds drawn alone. Each level's opacity
// applies to what it holds, and the art beside it in the level around it adds to the alpha once.
// The alphas, the art below each level and `alone` do not depend on the color, so each level
// is read once here and [`Backdrop::front`] draws any color through the levels.
let blends = |a: &Step| a.blend != BlendMode::Normal && !a.isolate;
let mut x = (shown(&color), 1.0f32);
let mut passes = vec![];
let mut alpha = 1.0f32;
let mut alone = 1.0f32;
// Whether a level so far read art that is not one color.
let mut mixed = false;
for (k, step) in steps.iter().enumerate() {
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && x.1 >= 1.0 && alone >= 1.0 {
if step.blend == BlendMode::Normal && step.opacity >= 1.0 && alpha >= 1.0 && alone >= 1.0 {
continue;
}
let above = &steps[k + 1..];
let scope = above.iter().find(|a| a.isolate);
let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::<Vec<_>>();
let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e));
let backdrop = match scope {
Some(_) if !sampled => ([0.0; 3], 0.0),
None if !sampled => (against, 1.0),
let (backdrop, one) = match scope {
Some(_) if !sampled => (([0.0; 3], 0.0), true),
None if !sampled => ((against, 1.0), uniform),
// The background itself, as the answer writes it.
None if step.hide.is_none() && full.is_empty() => (against, 1.0),
None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform),
_ => read(scope.map(|a| &a.within))?,
};
// The alpha of the art below the level inside the level around it, while a blending level
// lies further out (none for a given background).
let inner = match above.first() {
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1,
_ => 0.0,
let (inner, inner_one) = match above.first() {
Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => {
let ((_, a), one) = read(Some(&around.within))?;
(a, one)
}
_ => (0.0, true),
};
let source = if !blends(step) {
x
} else if alone <= 0.0 {
(x.0, 0.0)
} else {
(std::array::from_fn(|i| ((x.0[i] * x.1 - (1.0 - alone) * backdrop.0[i] * backdrop.1) / alone).clamp(0.0, 1.0)), alone)
};
// A level that isolates its blending carries out the alpha of what it holds composited on
// its own.
let drawn = if step.isolate { x.1 } else { alone } * step.opacity.clamp(0.0, 1.0);
x = composite(step.blend, source, step.opacity, backdrop);
alone = drawn + inner * (1.0 - drawn);
}
let front = if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, against) };
let ratio = wcag::contrast_ratio(front, against);
let levels = |c: Category| {
let (aa, aaa) = c.passes(ratio);
match aaa {
Some(aaa) => json!({ "aa": aa, "aaa": aaa }),
None => json!({ "aa": aa }),
// A blend mode mixes the color with the art below it pixel by pixel, which one color read for
// art of several colors does not stand for, also when that art reaches it through the levels
// inside it.
mixed |= !one || !inner_one;
if mixed && step.blend != BlendMode::Normal && step.opacity > 0.0 {
return Err(bad(C, "the art behind the selection is not one color where it is read, and the color blends with it: give `against`"));
}
};
let [r, g, b] = written;
Ok(json!({
"ratio": ratio,
"against": format!("#{r:02x}{g:02x}{b:02x}"),
"normalText": levels(Category::NormalText),
"largeText": levels(Category::LargeText),
"graphics": levels(Category::Graphics),
}))
let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, blends: blends(step), isolate: step.isolate, inner };
(_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone));
passes.push(pass);
}
let stain = if given { None } else { stain_of(s, !need_color) };
Ok((color, Backdrop { against, written, passes, stain, rich_black }))
}
/// An object around the proxy's object: one in the document, or a group of the picked object's
@@ -1232,7 +1450,8 @@ fn composite(mode: BlendMode, x: ([f32; 3], f32), opacity: f32, backdrop: ([f32;
/// levels that change what they draw must be the same objects too, since the art below each one is
/// read with that object hidden, and the object's opacity must be the same apart from its row's,
/// since the row draws over the object's rows below it and the object over the art behind it, and a
/// row that blends or is translucent must lie over the same shown rows.
/// row that blends or is translucent must lie over the same shown rows, and over a lower row that
/// blends, with the same isolation.
fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let counts = |l: &&Level| l.blend != BlendMode::Normal || l.isolate || (!given_opacity && l.opacity < 1.0);
let level = |x: &Level, y: &Level| {
@@ -1248,10 +1467,26 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
let total = |d: &Drawn| d.opacity * d.row.map_or(1.0, |r| r.1);
// A row that blends or lets art through draws over the rows below it, read at one point.
let over_rows = |d: &Drawn| d.row.is_some_and(|(m, o)| m != BlendMode::Normal || o < 1.0);
// A lower row that blends reads the art behind the object unless the object isolates its
// blending, so a row drawn over it reads a backdrop that depends on the isolation. A blending
// row at no opacity does not show, nor does a fill row without effects under an opaque solid
// Normal fill row without effects, which covers the same shape (a stroke reaches outside it).
let plain_fill = |i: &vectorcraft_doc::AppearanceItem| i.is_fill() && i.effects().is_empty();
let covers = |i: &vectorcraft_doc::AppearanceItem| {
plain_fill(i) && i.blend() == BlendMode::Normal && i.opacity() >= 1.0 && matches!(i.paint(), Paint::Solid { .. })
};
let over_blended = |d: &Drawn| {
over_rows(d)
&& d.lower
.iter()
.enumerate()
.any(|(k, i)| i.blend() != BlendMode::Normal && i.opacity() > 0.0 && !(plain_fill(i) && d.lower[k + 1..].iter().any(covers)))
};
row(a) == row(b)
&& (given_opacity || !below || !(over_rows(a) || over_rows(b)) || a.lower == b.lower)
&& a.blend == b.blend
&& (row(a).is_none() || a.isolate == b.isolate)
&& (given_opacity || !below || !(over_blended(a) || over_blended(b)) || a.isolate == b.isolate)
&& (given_opacity || (total(a) - total(b)).abs() < 1e-6)
&& (given_opacity || (row(a).is_none() && !below) || (a.opacity - b.opacity).abs() < 1e-6)
&& la.len() == lb.len()
@@ -1263,8 +1498,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool {
/// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not
/// compared, since the given opacity takes their place; with `below` (the background is sampled),
/// objects in different translucent or blending groups or layers differ, since the art below each
/// such level is read with it hidden.
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> {
/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern),
/// and the drawing is then the one a solid color in its place would have.
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option<Color>, Drawn), String> {
let stroke = !s.fill_active;
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
if if stroke { stroke_mixed } else { fill_mixed } {
@@ -1320,20 +1556,28 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re
} else {
drawing = source()?.unwrap_or_default();
}
let no_color = || "the active fill or stroke has no color: give `color`".to_string();
match if stroke { stroke_paint } else { fill } {
Paint::Solid { color, .. } => Ok((stained(s, color), drawing)),
let found = match if stroke { stroke_paint } else { fill } {
Paint::Solid { color, .. } => Some((color, drawing.clone())),
Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform => {
let f = g.freeform_on(vectorcraft_geom::Rect::new(0.0, 0.0, 1.0, 1.0));
let i = s.selected_freeform_point().filter(|i| *i < f.points.len()).unwrap_or(0);
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity))).ok_or_else(no_color)
f.points.get(i).map(|pt| (pt.color, at(&drawing, pt.opacity)))
}
Paint::Gradient(g) => {
let i = s.selected_stop().unwrap_or(0).min(g.gradient.stops.len().saturating_sub(1));
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity))).ok_or_else(no_color)
g.gradient.stops.get(i).map(|st| (st.color, at(&drawing, st.opacity)))
}
Paint::None | Paint::Pattern { .. } => Err(no_color()),
}
Paint::None | Paint::Pattern { .. } => None,
};
Ok(match found {
Some((color, drawn)) => (Some(color), drawn),
None => (None, drawing),
})
}
/// The message for an active fill or stroke with no color to measure.
fn no_color() -> String {
"the active fill or stroke has no color: give `color`".to_string()
}
/// `drawing` with a stop's or point's `opacity`, which applies where its paint is drawn: in its
@@ -1398,19 +1642,21 @@ fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> s
Ok(Drawn { opacity: n.opacity, row: own.map(|o| (o.1, o.0)), blend: n.blend, isolate: n.isolate, around, lower })
}
/// `color` as the canvas draws the picked object of a dynamic symbol instance that a fill stains
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill);
/// `color` itself otherwise.
fn stained(s: &Session, color: Color) -> Color {
let stain = s.active().and_then(|st| {
let sp = st.selection.symbol_part.as_ref()?;
st.selected_symbol_part()?;
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?)
});
match stain {
Some((c, amount)) => color.lerp(&c, amount.clamp(0.0, 1.0)),
None => color,
/// The color and amount a fill stains the picked object of a dynamic symbol instance with
/// (`symbol_overrides::instance_art` mixes the art's solid paints towards the instance's fill), when
/// such an object is picked and its proxy shows a solid color. For a pick (`pick`), a proxy of None
/// or a pattern counts too, as the pick puts a solid color in its place.
fn stain_of(s: &Session, pick: bool) -> Option<(Color, f32)> {
let (fill, stroke) = s.proxy_paints();
match if s.fill_active { fill } else { stroke } {
Paint::Solid { .. } => {}
Paint::None | Paint::Pattern { .. } if pick => {}
_ => return None,
}
let st = s.active()?;
let sp = st.selection.symbol_part.as_ref()?;
st.selected_symbol_part()?;
vectorcraft_doc::symbol_overrides::stain(st.doc.node(sp.instance)?).map(|(c, amount)| (c, amount.clamp(0.0, 1.0)))
}
/// The objects that draw the proxy's object `id` ([`Level`]), outermost first: its groups and
@@ -1455,14 +1701,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec<Level> {
/// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it;
/// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer
/// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing,
/// without artboards.
/// without artboards. Also whether the square's pixels are all one color.
fn color_below(
s: &Session,
rich_black: bool,
hide: Option<&Part>,
full: &[&Part],
scope: Option<&Part>,
) -> std::result::Result<([f32; 3], f32), String> {
) -> std::result::Result<(([f32; 3], f32), bool), String> {
super::has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let ids = st.selection.objects.clone();
@@ -1591,8 +1837,10 @@ fn color_below(
let img = vectorcraft_render::Renderer::new().render_region_with(copy.as_ref().unwrap_or(&st.doc), region, BELOW_SCALE, &opts);
let px = img.pixels.as_chunks::<4>().0;
if px.is_empty() {
return Ok(if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) });
return Ok((if scope.is_none() { ([1.0; 3], 1.0) } else { ([0.0; 3], 0.0) }, true));
}
// Whether the pixels are one color, to within one step of 255 per channel.
let uniform = px.first().is_none_or(|first| px.iter().all(|p| p.iter().zip(first).all(|(a, b)| a.abs_diff(*b) <= 1)));
// The pixels are premultiplied: the average color is their sum over their alpha's.
let mut sum = [0.0f64; 4];
for p in px {
@@ -1602,10 +1850,10 @@ fn color_below(
}
let alpha = sum[3] / (px.len() as f64 * 255.0);
if alpha <= 0.0 {
return Ok(([0.0; 3], 0.0));
return Ok((([0.0; 3], 0.0), uniform));
}
let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32);
Ok((rgb, alpha as f32))
Ok(((rgb, alpha as f32), uniform))
}
/// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it.
+333
View File
@@ -776,6 +776,33 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
let r = s.execute("color.contrast", &json!({"against": "#000000", "opacity": 100})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((ratio(&r) - want).abs() < 1e-3, "white stained half way to black: {r}");
// The fix is the color to store: the stain mixes it half way to black again, and the result
// just meets AA against white.
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
assert_eq!(r["normalText"]["aa"], false, "{r}");
let fix = fix_color(&r["fix"]["aa"]);
let drawn = fix.lerp(&vectorcraft_color::Color::BLACK, 0.5).to_rgb_uncalibrated();
let got = vectorcraft_color::wcag::contrast_ratio(drawn, [1.0; 3]);
assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}");
}
/// A pick for a picked symbol object with a fill of None puts a solid color there, which the
/// instance's stain mixes like any other, so the Color Wheel's contrast lines measure it stained.
#[test]
fn a_pick_for_a_picked_symbol_object_with_no_fill_is_measured_with_the_stain() {
let mut s = picked_symbol_part();
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
s.active_mut().unwrap().selection.symbol_part = None;
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
s.execute("paint.setFill", &json!({"none": true})).unwrap();
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({"against": "#000000", "opacity": 100})).unwrap();
let cms = vectorcraft_color::cms::active();
let white = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(1.0, 1.0, 1.0)));
let want = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [0.0; 3]);
assert!((white - want).abs() < 1e-3, "a white pick stained half way to black: {white} against {want}");
}
#[test]
@@ -877,3 +904,309 @@ fn a_fill_of_none_has_no_color_to_measure() {
assert!(e.contains("has no color"), "{e}");
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
}
fn fix_color(v: &Value) -> vectorcraft_color::Color {
crate::cmd::color_value(v).unwrap_or_else(|| panic!("not a color: {v}"))
}
fn oklch_hue(c: &vectorcraft_color::Color) -> f64 {
let [_, a, b] = vectorcraft_color::libraries::to_oklab(c);
b.atan2(a).to_degrees()
}
#[test]
fn a_failing_color_answers_the_closest_passing_color_of_its_hue() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
assert_eq!(r["for"], "normalText");
let aa = fix_color(&r["fix"]["aa"]);
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
let want = oklch_hue(&vectorcraft_color::Color::from_hex("#fdc96e").unwrap());
assert!((oklch_hue(&aa) - want).abs() < 1.0, "{} {want}", oklch_hue(&aa));
assert!(matches!(aa, vectorcraft_color::Color::Rgb { .. }), "an RGB color answers RGB: {aa:?}");
// White on #355F78 is 6.87:1 and black 3.05:1, so no color reaches AAA's 7:1.
assert!(r["fix"]["aaa"].is_null(), "{r}");
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
let aaa = s.execute("color.contrast", &json!({"color": large["fix"]["aaa"], "against": "#355f78"})).unwrap();
assert!((4.5..4.57).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}");
}
/// The canvas paints a color with 8 bits per channel, so a fix passes once rounded that way too:
/// #777777 on white is 4.48:1, a gray of about 118.7/255 meets 4.5:1 but paints as #777777 again,
/// and the fix has to paint as #767676 (4.54:1) or darker.
#[test]
fn a_fix_passes_as_the_canvas_paints_it() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
let fix = fix_color(&r["fix"]["aa"]);
let painted = fix.to_rgb_uncalibrated().map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
let got = vectorcraft_color::wcag::contrast_ratio(painted, [1.0; 3]);
assert!(got >= 4.5, "{fix:?} paints as {painted:?}: {got}");
// The fix is the closest one: the gray one 8-bit step lighter fails.
let lighter = painted.map(|v| (v + 1.0 / 255.0).min(1.0));
assert!(vectorcraft_color::wcag::contrast_ratio(lighter, [1.0; 3]) < 4.5, "{fix:?} paints as {painted:?}");
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap();
assert!((4.5..4.57).contains(&ratio(&back)), "{back}");
}
/// The backdrop shows 100 % K alone as `color.contrast` measures it under each Appearance of Black,
/// so the Color Wheel's contrast lines use the same color.
#[test]
fn the_backdrop_shows_black_as_the_appearance_of_black_setting_does() {
let k = vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0);
let cms = vectorcraft_color::cms::active();
let mut s = Session::new();
let p = json!({"color": serde_json::to_value(k).unwrap(), "against": "#ffffff"});
let (accurate, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
assert_ne!(backdrop.shown(&cms, &k), [0.0; 3]);
s.prefs.black_on_screen = "rich".into();
let (rich, backdrop) = crate::cmd::contrast_measure(&s, &p).unwrap();
assert_eq!(backdrop.shown(&cms, &k), [0.0; 3]);
assert!(ratio(&rich) > ratio(&accurate), "{rich} {accurate}");
}
/// A translucent fix also meets the minimum with the color, the opacity, the background and the
/// composited pixel rounded to 8 bits per channel.
#[test]
fn a_translucent_fix_passes_at_eight_bits() {
let eight = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0;
let at_eight_bits = |fix: &vectorcraft_color::Color, opacity: f32, against: f32| {
let (a, b) = (eight(opacity), eight(against));
let pixel = fix.to_rgb_uncalibrated().map(|c| eight(eight(c) * a + b * (1.0 - a)));
vectorcraft_color::wcag::contrast_ratio(pixel, [b; 3])
};
let mut s = Session::new();
// A gray can pass only before rounding: #808080 at 91.1 % over black measures 4.53:1, and at
// 232 / 255 its pixel is #747474 (4.49:1).
let r = s.execute("color.contrast", &json!({"color": "#707070", "against": "#000000", "opacity": 91.1})).unwrap();
let fix = fix_color(&r["fix"]["aa"]);
assert!(at_eight_bits(&fix, 0.911, 0.0) >= 4.5, "{fix:?}");
// #040404 at 195 / 255 over a gray of 137.51 / 255 measures 4.5002:1, and over 138 / 255 it is
// 4.4965:1.
let bg = 137.51 / 255.0;
let p = json!({"color": "#303030", "against": [bg, bg, bg], "opacity": 19500.0 / 255.0});
let r = s.execute("color.contrast", &p).unwrap();
let fix = fix_color(&r["fix"]["aa"]);
assert!(at_eight_bits(&fix, 195.0 / 255.0, bg) >= 4.5, "{fix:?}");
// Black at 41.7 % over white measures 3.008:1, and its pixel at 8 bits is 2.995:1, so no gray
// at that opacity gets a fix.
let p = json!({"color": "#202020", "against": "#ffffff", "opacity": 41.7, "for": "graphics"});
let r = s.execute("color.contrast", &p).unwrap();
assert_eq!(r["graphics"]["aa"], false, "{r}");
assert!(r["fix"]["aa"].is_null(), "{r}");
}
#[test]
fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert_eq!(r["fix"], json!({"aa": null, "aaa": null}));
let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap();
assert_eq!(g["for"], "graphics");
let fix = g["fix"].as_object().unwrap();
assert_eq!(fix.keys().collect::<Vec<_>>(), ["aa"], "{g}");
let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap();
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
let large = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78", "for": "largeText"})).unwrap();
assert!(large["fix"]["aa"].is_null(), "4.49:1 meets large text AA: {large}");
assert!(!large["fix"]["aaa"].is_null(), "{large}");
}
#[test]
fn a_cmyk_color_answers_a_cmyk_fix() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": {"c": 0, "m": 40, "y": 70, "k": 20}, "against": "#355f78"})).unwrap();
assert_eq!(r["normalText"]["aa"], false, "{r}");
let fix = fix_color(&r["fix"]["aa"]);
assert!(matches!(fix, vectorcraft_color::Color::Cmyk { .. }), "{fix:?}");
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#355f78"})).unwrap();
assert!(ratio(&back) >= 4.5, "{back}");
}
#[test]
fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() {
let mut s = Session::new();
// #808080 at 50 % over white draws as a light gray: black at 50 % draws 0.5 gray, 3.98:1, which
// meets large text AA (3:1) but not AAA (4.5:1).
let p = json!({"color": "#808080", "against": "#ffffff", "opacity": 50, "for": "largeText"});
let r = s.execute("color.contrast", &p).unwrap();
assert_eq!(r["largeText"]["aa"], false, "{r}");
assert!(r["fix"]["aaa"].is_null(), "no gray at 50 % reaches 4.5:1: {r}");
let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff", "opacity": 50})).unwrap();
assert!((3.0..3.04).contains(&ratio(&back)), "{back}");
}
/// A square with a 50 % top fill row over locked orange, with and without a lower fill row and in a
/// Screen group or not: isolating the object's blending leaves what a translucent Normal row draws
/// as it is, on the canvas and in the answer, for each blend mode of the object.
#[test]
fn isolation_leaves_a_translucent_normal_row_as_it_draws() {
let id = |v: Value| v["id"].as_u64().unwrap();
for blend in ["normal", "multiply", "screen", "difference", "overlay"] {
for fill in ["#808080", "#ffffff", "#2040a0"] {
for lower in [false, true] {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let n = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
if lower {
s.execute("appearance.addFill", &json!({})).unwrap();
}
let st = s.active().unwrap();
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
let top = items.iter().rposition(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": fill, "opacity": 50})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("transparency.set", &json!({"item": null, "blend": blend})).unwrap();
if lower {
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "screen"})).unwrap();
s.execute("select.set", &json!({"ids": [n]})).unwrap();
}
let plain = s.execute("color.contrast", &json!({})).unwrap();
let (p, drawn) = canvas_ratio(&s, &plain);
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
let isolated = s.execute("color.contrast", &json!({})).unwrap();
let (q, _) = canvas_ratio(&s, &isolated);
let case = format!("{blend} {fill} lower row and group: {lower}");
assert_eq!(p, q, "the canvas draws the same: {case}");
assert!((ratio(&plain) - ratio(&isolated)).abs() < 1e-6, "{case}: {plain} {isolated}");
assert!((ratio(&plain) - drawn).abs() < 0.02, "{case}: {plain} against {drawn}");
}
}
}
}
/// Two squares over locked orange, each with a 50 % white top fill over a blue Multiply fill, one
/// isolating its blending: the blue multiplies with the orange in one and draws over nothing in the
/// other, so the white draws over different rows and there is no one answer. A given background
/// stands for the rows below and answers.
#[test]
fn a_translucent_row_over_a_blending_row_in_objects_of_different_isolation_has_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 180, "height": 180})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff8000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let square = |s: &mut Session, x: i32, isolate: bool| {
let n = id(s.execute("shape.rectangle", &json!({"x": x, "y": 50, "width": 50, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let st = s.active().unwrap();
let items = &st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items;
let top = items.iter().rposition(|i| i.is_fill()).unwrap();
let lower = items.iter().position(|i| i.is_fill()).unwrap();
s.execute("appearance.setItem", &json!({"index": top, "color": "#ffffff", "opacity": 50})).unwrap();
s.execute("appearance.setItem", &json!({"index": lower, "blend": "multiply"})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
if isolate {
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
}
n
};
let a = square(&mut s, 30, false);
let b = square(&mut s, 120, true);
s.execute("select.set", &json!({"ids": [a]})).unwrap();
let ra = ratio(&s.execute("color.contrast", &json!({})).unwrap());
s.execute("select.set", &json!({"ids": [b]})).unwrap();
let rb = ratio(&s.execute("color.contrast", &json!({})).unwrap());
assert!((ra - rb).abs() > 0.1, "the white draws over different rows: {ra} {rb}");
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ"), "{e}");
s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
// A blending row at no opacity does not show, so the isolation no longer changes the answer.
for n in [a, b] {
let st = s.active().unwrap();
let lower = st.doc.node(vectorcraft_doc::NodeId(n)).unwrap().appearance.items.iter().position(|i| i.is_fill()).unwrap();
s.execute("appearance.setItem", &json!({"ids": [n], "index": lower, "opacity": 0})).unwrap();
}
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
}
/// A Difference square centered on the edge between locked black and white art: the art behind it
/// is not one color where it is read, so no one color stands for it; a given background answers,
/// and over one color the background is read as before.
#[test]
fn a_blend_mode_over_art_of_several_colors_has_no_one_answer() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("select.all", &json!({})).unwrap();
// Without the default stroke, which would cover the edge.
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("is not one color where it is read") && e.contains("give `against`"), "{e}");
let given = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-6, "white minus white is black: {given}");
// In Normal mode the color is drawn as it is, over the background read as one color.
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
// Moved over the white art alone, the square blends with one color again.
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
s.execute("object.move", &json!({"dx": 40, "dy": 0})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-3, "white minus white is black: {r}");
}
/// A Difference square over a white square in a 50 % group that isolates its blending, over the
/// edge between black and white art: the square blends only with the white inside the group, so
/// the art of two colors outside it, which the group draws over in Normal mode, leaves one answer.
#[test]
fn a_blend_mode_inside_an_isolating_group_answers_over_art_of_several_colors() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("shape.rectangle", &json!({"x": 100, "y": 20, "width": 80, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("select.all", &json!({})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let back = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
let square = id(s.execute("shape.rectangle", &json!({"x": 70, "y": 70, "width": 60, "height": 60})).unwrap());
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
s.execute("object.group", &json!({"ids": [back, square]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50, "isolate": true})).unwrap();
s.execute("select.set", &json!({"ids": [square]})).unwrap();
s.execute("color.contrast", &json!({})).unwrap();
}
/// With a fill of None, what a pick would be measured against is still read: the Color Wheel's
/// contrast lines show where a solid color in its place passes.
#[test]
fn a_pick_for_a_fill_of_none_is_measured_against_the_background() {
let mut s = blended_over_red("normal");
s.execute("paint.setFill", &json!({"none": true})).unwrap();
assert!(s.execute("color.contrast", &json!({})).is_err(), "no color to measure");
let backdrop = crate::cmd::contrast_pick_backdrop(&s, &json!({})).unwrap();
let cms = vectorcraft_color::cms::active();
let black = backdrop.ratio(backdrop.shown(&cms, &vectorcraft_color::Color::rgb(0.0, 0.0, 0.0)));
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 0.0, 0.0]);
assert!((black - want).abs() < 1e-3, "black over the red art: {black} against {want}");
assert_eq!(backdrop.against_hex(), "#ff0000");
}
#[test]
fn for_takes_only_the_three_categories() {
let mut s = Session::new();
for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] {
let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string();
assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}");
}
}
+1 -3
View File
@@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
/// behind the selection, given back, answers the same ratio.
#[test]
fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() {
let _g = settings();
let before = cms::active_settings();
let _g = restored_settings();
let mut s = session();
exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB}));
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"}));
@@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space
exec(&mut s, "paint.setFill", json!({"color": "#808080"}));
let below = s.execute("color.contrast", &json!({}));
let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok());
cms::set_active(&before).unwrap();
let given = given.unwrap();
assert_eq!(given["against"], "#806040", "{given}");
let (below, again) = (below.unwrap(), again.unwrap());
+1 -1
View File
@@ -1615,7 +1615,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, Line truncated
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Opacity, Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; Line truncated
),
(
"ui.savePdfDialog",
+1
View File
@@ -1752,6 +1752,7 @@ font-technology Variable Променливи
Fail Не покрива
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11).
The background is read at the center of the selection. Фонът се отчита в центъра на селекцията.
The closest color that passes {level}: click to apply it. Най-близкият цвят, който покрива {level}: щракнете, за да го приложите.
Graphics Processor Графичен процесор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
Can't render this file because it is too large.
+1
View File
@@ -2121,6 +2121,7 @@ digits Malayalam Malajalam
Fail Ne prolazi
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadina se očitava u sredini odabira.
The closest color that passes {level}: click to apply it. Najbliža boja koja zadovoljava {level}: kliknite da je primijenite.
Local Libraries Lokalne biblioteke
Add Content Dodaj sadržaj
Click to apply to the selected type Kliknite da primijenite na odabrani tekst
Can't render this file because it contains an unexpected character in line 2 and column 73.
+1
View File
@@ -2155,6 +2155,7 @@ digits Malayalam Malaiàlam
Fail No supera
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11).
The background is read at the center of the selection. El fons es llegeix al centre de la selecció.
The closest color that passes {level}: click to apply it. El color més proper que compleix {level}: feu clic per aplicar-lo.
Graphics Processor Processador gràfic
Graphics: {adapter} Gràfics: {adapter}
Gravity Gravetat
Can't render this file because it is too large.
+1
View File
@@ -2193,6 +2193,7 @@ digits Malayalam Malajálamské
Fail Nevyhovuje
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11).
The background is read at the center of the selection. Pozadí se čte uprostřed výběru.
The closest color that passes {level}: click to apply it. Nejbližší barva, která splňuje {level}: kliknutím ji použijete.
Local Libraries Místní knihovny
Add Content Přidat obsah
Click to apply to the selected type Kliknutím použijete na vybraný text
Can't render this file because it is too large.
+1
View File
@@ -4860,6 +4860,7 @@ digits Malayalam Malayalam
Fail Ikke bestået
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11).
The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen.
The closest color that passes {level}: click to apply it. Den nærmeste farve, der består {level}: klik for at anvende den.
Local Libraries Lokale biblioteker
Add Content Tilføj indhold
Click to apply to the selected type Klik for at anvende på den markerede tekst
Can't render this file because it is too large.
+1
View File
@@ -1679,6 +1679,7 @@ file-filter Templates Vorlagen
Fail Nicht bestanden
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11).
The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen.
The closest color that passes {level}: click to apply it. Die nächste Farbe, die {level} besteht: Klicken Sie, um sie anzuwenden.
Graphics Processor Grafikprozessor
Graphics: {adapter} Grafik: {adapter}
Gravity Schwerkraft
Can't render this file because it is too large.
+1
View File
@@ -1598,6 +1598,7 @@ font-technology Variable Μεταβλητές
Fail Αποτυχία
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11).
The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής.
The closest color that passes {level}: click to apply it. Το πλησιέστερο χρώμα που περνά το {level}: κάντε κλικ για να το εφαρμόσετε.
Graphics Processor Επεξεργαστής γραφικών
Graphics: {adapter} Γραφικά: {adapter}
Gravity Βαρύτητα
Can't render this file because it is too large.
+1
View File
@@ -1688,6 +1688,7 @@ font-technology Variable Variables
Fail No cumple
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11).
The background is read at the center of the selection. El fondo se lee en el centro de la selección.
The closest color that passes {level}: click to apply it. El color más cercano que cumple {level}: haga clic para aplicarlo.
Graphics Processor Procesador gráfico
Graphics: {adapter} Gráficos: {adapter}
Gravity Gravedad
Can't render this file because it is too large.
+1
View File
@@ -2152,6 +2152,7 @@ digits Malayalam Malajalam
Fail Ei läpäise
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11).
The background is read at the center of the selection. Tausta luetaan valinnan keskeltä.
The closest color that passes {level}: click to apply it. Lähin väri, joka läpäisee tason {level}: käytä sitä napsauttamalla.
Local Libraries Paikalliset kirjastot
Add Content Lisää sisältöä
Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla
Can't render this file because it is too large.
+1
View File
@@ -1678,6 +1678,7 @@ font-technology Variable Variables
Fail Échec
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11).
The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection.
The closest color that passes {level}: click to apply it. La couleur la plus proche qui satisfait {level}. Cliquez pour l’appliquer.
Graphics Processor Processeur graphique
Graphics: {adapter} Carte graphique : {adapter}
Gravity Gravité
Can't render this file because it is too large.
+1
View File
@@ -1742,6 +1742,7 @@
Fail નાપાસ
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11).
The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે.
The closest color that passes {level}: click to apply it. {level} પાસ કરતો સૌથી નજીકનો રંગ: તેને લાગુ કરવા ક્લિક કરો.
Graphics Processor ગ્રાફિક્સ પ્રોસેસર
Graphics: {adapter} ગ્રાફિક્સ: {adapter}
Gravity ગ્રેવિટી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+1
View File
@@ -2629,6 +2629,7 @@ arrowhead Feather पंख
Fail फ़ेल
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)।
The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है।
The closest color that passes {level}: click to apply it. {level} पास करने वाला सबसे नज़दीकी रंग: लागू करने के लिए क्लिक करें।
Graphics Processor ग्राफिक्स प्रोसेसर
Graphics: {adapter} ग्राफिक्स: {adapter}
Gravity ग्रेविटी
Can't render this file because it is too large.
+1
View File
@@ -2082,6 +2082,7 @@ file-filter Templates Sablonok
Fail Nem felel meg
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11).
The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program.
The closest color that passes {level}: click to apply it. A legközelebbi szín, amely megfelel a(z) {level} szintnek: kattintson az alkalmazásához.
Graphics Processor Grafikus processzor
Graphics: {adapter} Grafika: {adapter}
Gravity Gravitáció
Can't render this file because it is too large.
+1
View File
@@ -2736,6 +2736,7 @@ digits Malayalam Malayalam
Fail Gagal
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11).
The background is read at the center of the selection. Latar dibaca di tengah seleksi.
The closest color that passes {level}: click to apply it. Warna terdekat yang lolos {level}: klik untuk menerapkannya.
Local Libraries Pustaka lokal
Add Content Tambahkan konten
Click to apply to the selected type Klik untuk menerapkan ke teks terpilih
Can't render this file because it is too large.
+1
View File
@@ -1716,6 +1716,7 @@ file-filter Templates Modelli
Fail Non superato
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11).
The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione.
The closest color that passes {level}: click to apply it. Il colore più vicino che soddisfa {level}: fai clic per applicarlo.
Graphics Processor Processore grafico
Graphics: {adapter} Scheda grafica: {adapter}
Gravity Gravità
Can't render this file because it is too large.
+1
View File
@@ -4457,6 +4457,7 @@ file-filter Templates テンプレート
Fail 不合格
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。
The closest color that passes {level}: click to apply it. {level} を満たす最も近いカラー:クリックで適用します。
Greek & Cyrillic ギリシャ文字とキリル文字
Hex by Column 六角形 (列)
Hex by Row 六角形 (行)
Can't render this file because it is too large.
+1
View File
@@ -4135,6 +4135,7 @@ digits Malayalam მალაიალამური
Fail არ აკმაყოფილებს
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11).
The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში.
The closest color that passes {level}: click to apply it. უახლოესი ფერი, რომელიც აკმაყოფილებს {level}-ს: დააწკაპუნეთ მის გამოსაყენებლად.
Local Libraries ლოკალური ბიბლიოთეკები
Add Content შიგთავსის დამატება
Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
Can't render this file because it is too large.
+1
View File
@@ -4447,6 +4447,7 @@ file-filter Templates 템플릿
Fail 실패
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11).
The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다.
The closest color that passes {level}: click to apply it. {level}을(를) 충족하는 가장 가까운 색상: 클릭하여 적용합니다.
Greek & Cyrillic 그리스어 및 키릴 문자
Hex by Column 열 기준 육각형
Hex by Row 행 기준 육각형
Can't render this file because it is too large.
+1
View File
@@ -2721,6 +2721,7 @@ digits Malayalam Malayalam
Fail Niet geslaagd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11).
The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten.
The closest color that passes {level}: click to apply it. De dichtstbijzijnde kleur die aan {level} voldoet: klik om deze toe te passen.
Local Libraries Lokale bibliotheken
Add Content Inhoud toevoegen
Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst
Can't render this file because it is too large.
+1
View File
@@ -2109,6 +2109,7 @@ digits Malayalam Malajalam
Fail Nie spełnia
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11).
The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia.
The closest color that passes {level}: click to apply it. Najbliższy kolor spełniający {level}: kliknij, aby go zastosować.
Local Libraries Biblioteki lokalne
Add Content Dodaj zawartość
Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu
Can't render this file because it is too large.
+1
View File
@@ -4139,6 +4139,7 @@ font-technology Variable Variáveis
Fail Reprovado
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11).
The background is read at the center of the selection. O fundo é lido no centro da seleção.
The closest color that passes {level}: click to apply it. A cor mais próxima que atende a {level}: clique para aplicá-la.
Highlight Rows Destacar linhas
Highlight Variable Destacar variável
Sort Variables Ordenar variáveis
Can't render this file because it is too large.
+1
View File
@@ -1701,6 +1701,7 @@ file-filter Templates Шаблоны
Fail Не соответствует
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон определяется в центре выделения.
The closest color that passes {level}: click to apply it. Ближайший цвет, соответствующий {level}: щёлкните, чтобы применить его.
Graphics Processor Графический процессор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
Can't render this file because it is too large.
+1
View File
@@ -1635,6 +1635,7 @@ font-technology Variable Variabla
Fail Underkänd
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11).
The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen.
The closest color that passes {level}: click to apply it. Den närmaste färgen som klarar {level}: klicka för att använda den.
Graphics Processor Grafikprocessor
Graphics: {adapter} Grafik: {adapter}
Gravity Gravitation
Can't render this file because it is too large.
+1
View File
@@ -1599,6 +1599,7 @@ font-technology Variable Değişken
Fail Kaldı
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11).
The background is read at the center of the selection. Arka plan seçimin ortasında okunur.
The closest color that passes {level}: click to apply it. {level} düzeyini karşılayan en yakın renk: uygulamak için tıklayın.
Graphics Processor Grafik İşlemcisi
Graphics: {adapter} Grafik: {adapter}
Gravity Yerçekimi
Can't render this file because it is too large.
+1
View File
@@ -1710,6 +1710,7 @@ file-filter Templates Шаблони
Fail Не відповідає
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11).
The background is read at the center of the selection. Фон визначається в центрі виділення.
The closest color that passes {level}: click to apply it. Найближчий колір, що відповідає {level}: клацніть, щоб застосувати його.
Graphics Processor Графічний процесор
Graphics: {adapter} Графіка: {adapter}
Gravity Гравітація
Can't render this file because it is too large.
+1
View File
@@ -1944,6 +1944,7 @@ file-filter Templates Mẫu
Fail Không đạt
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11).
The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn.
The closest color that passes {level}: click to apply it. Màu gần nhất đạt {level}: bấm để áp dụng.
Graphics Processor Bộ xử lý đồ họa
Graphics: {adapter} Đồ họa: {adapter}
Gravity Trọng lực
Can't render this file because it is too large.
+1
View File
@@ -1644,6 +1644,7 @@ file-filter Templates 模板
Fail 未通过
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在所选对象的中心读取。
The closest color that passes {level}: click to apply it. 符合 {level} 的最接近颜色:单击即可应用。
Gravity 重力
Grays 灰度级数
Grays and Neutrals 灰色和中性色
Can't render this file because it is too large.
+1
View File
@@ -1680,6 +1680,7 @@ file-filter Templates 範本
Fail 未通過
WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。
The background is read at the center of the selection. 背景在選取範圍的中心讀取。
The closest color that passes {level}: click to apply it. 符合 {level} 的最接近顏色:按一下即可套用。
Graphics Processor 圖形處理器
Graphics: {adapter} 圖形:{adapter}
Gravity 重力
Can't render this file because it is too large.
+1 -1
View File
@@ -1616,7 +1616,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, Line truncated
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, opacity?: bool, hexField?: bool, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do, and set Show Opacity, Show Contrast, Contrast For, Contrast Background, Show Color Vision Preview and Show Document Colors: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits at or below the one asked for; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; Line truncated
),
(
"ui.savePdfDialog",
+2
View File
@@ -1227,6 +1227,8 @@ mod tests_color_wheel_box;
#[cfg(test)]
mod tests_color_wheel_contrast;
#[cfg(test)]
mod tests_color_wheel_contrast_lines;
#[cfg(test)]
mod tests_color_wheel_document_colors;
#[cfg(test)]
mod tests_color_wheel_gamut;
+428 -78
View File
@@ -38,6 +38,9 @@
//! (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>) of the color against the color drawn
//! behind the selection, or against a color pinned with Contrast Background › Current Color, and
//! whether it meets AA and AAA for the category picked under Contrast For (`color.contrast`).
//! The wheel's square and the box's field then draw lines where the color picked there would meet
//! AA and AAA (AAA dashed), and when the color fails, a chip in the row offers the closest color
//! that passes, the one `color.contrast` answers as `fix`.
//!
//! Panel menu › Show Color Vision Preview adds a row under the wheel or the box with the color as
//! simulated for protanopia, deuteranopia and tritanopia, through the simulations View › Proof
@@ -62,6 +65,7 @@
//! Show Opacity, Show Hex Field, the contrast settings, Show Color Vision Preview and Show Document
//! Colors are kept with the preferences (`ui.colorWheel`).
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
@@ -74,7 +78,7 @@ use craft::color_ui::AreaMode;
use craft::color_ui::ui::{ChannelRow, ChannelUnit, ColorArea, ColorStrip, ColorWheel, WheelInner};
use craft::keymap::CommandRef;
use craft::theme::{ColorModel, HsbModel, ModelValues, RgbModel, Srgba};
use craft::ui::choice::{Swatch, SwatchSpacing, SwatchTable};
use craft::ui::choice::{SwatchSpacing, SwatchTable};
use craft::ui::contract::{ActivateOn, Bind, EditResponse, Props as _, Show as _, ShowContainer as _, Sizing};
use craft::ui::display::{Shade, Text};
use craft::ui::layout::CellAlign;
@@ -83,7 +87,7 @@ use craft::ui::menu::PanelRow;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::runtime::env::Label;
use craft::ui::text::TextField;
use egui::Ui;
use egui::{Color32, Rect, Stroke, Ui};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget};
@@ -92,10 +96,11 @@ use vectorcraft_color::oklab::{self, CHROMA_FULL};
use vectorcraft_color::wcag::{self, Category};
use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl};
use vectorcraft_doc::{ColorMode, NodeId};
use vectorcraft_engine::cmd::{Backdrop, contrast_measure, contrast_pick_backdrop};
// PLAN: assumed `crate::edits::{apply_edits, EditPath}` (wg.A16, widgets-w13) and `crate::panels::Live` (co.A2, hub-w2).
use super::color::{Target, apply, gamut, wheel_target};
use super::{Live, alt_held};
use super::color::{Target, apply, gamut, target_now, wheel_target};
use super::{Live, alt_held, color_json};
use crate::VectorcraftApp;
use crate::edits::{EditPath, apply_edits};
@@ -428,28 +433,24 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S
if let Some(on) = crate::menus::opt_bool(p, "hexField")? {
set.hex_field = on;
}
match p.get("contrast") {
if let Some(on) = crate::menus::opt_bool(p, "contrast")? {
set.contrast = on;
}
let key = "contrastFor";
match p.get(key) {
None | Some(Value::Null) => {}
Some(v) => {
let key = "contrast";
set.contrast = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?;
set.contrast_for = v.as_str().and_then(Category::parse).ok_or_else(|| {
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
format!("`{key}` must be one of {}", ids.join(", "))
})?
}
}
match p.get("contrastFor") {
None | Some(Value::Null) => {}
Some(v) => {
let key = "contrastFor";
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
set.contrast_for = v.as_str().and_then(Category::parse).ok_or_else(|| format!("`{key}` must be one of {}", ids.join(", ")))?;
}
}
match p.get("contrastBackground") {
let key = "contrastBackground";
match p.get(key) {
None => {}
Some(Value::Null) => set.contrast_background = None,
Some(v) => {
let key = "contrastBackground";
set.contrast_background = Some(background_value(v).ok_or_else(|| format!("`{key}` must be a color or {}", "null"))?);
}
Some(v) => set.contrast_background = Some(background_value(v).ok_or_else(|| format!("`{key}` must be a color or {}", "null"))?),
}
if let Some(on) = crate::menus::opt_bool(p, "vision")? {
set.vision = on;
@@ -495,8 +496,8 @@ pub(super) fn category_name(c: Category) -> &'static str {
}
/// Every row of the panel menu with its state for `set`, `srgb` telling whether the active
/// document's RGB space is sRGB and `current` the color the panel edits, which Contrast Background
/// › Current Color pins.
/// document's RGB space is sRGB and `current` the color the panel edits, which Contrast
/// Background › Current Color pins.
fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
let item = |id: String, label: &str, checked: bool, enabled: bool, params: Value| Item {
id,
@@ -539,10 +540,20 @@ fn items(set: &Settings, srgb: bool, current: Option<Color>) -> Vec<Item> {
for c in Category::ALL {
out.push(item(category_row_id(c), category_name(c), set.contrast_for == c, true, json!({ "contrastFor": c.id() })));
}
let pinned = set.contrast_background.is_some();
out.push(item("contrastBackground.below".into(), tl!("Behind Selection"), !pinned, true, json!({ "contrastBackground": null })));
let params = current.map_or(Value::Null, |c| json!({ "contrastBackground": crate::panels::color_json(&c) }));
out.push(item("contrastBackground.current".into(), tl!("Current Color"), pinned, current.is_some(), params));
out.push(item(
"contrastBackground.below".into(),
tl!("Behind Selection"),
set.contrast_background.is_none(),
true,
json!({ "contrastBackground": null }),
));
out.push(item(
"contrastBackground.current".into(),
tl!("Current Color"),
set.contrast_background.is_some(),
current.is_some(),
json!({ "contrastBackground": current.as_ref().map(color_json) }),
));
out.push(item("vision".into(), tl!("Show Color Vision Preview"), set.vision, true, json!({ "vision": !set.vision })));
out.push(item(
"documentColors".into(),
@@ -575,20 +586,15 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
));
rows.push(PanelRow::Submenu(
Label::from(tl!("Contrast Background").to_string()),
["contrastBackground.below", "contrastBackground.current"].into_iter().map(|row| command(row.into())).collect(),
vec![command("contrastBackground.below".into()), command("contrastBackground.current".into())],
));
rows.extend(["vision", "documentColors"].map(|row| command(row.into())));
rows
}
/// The menu rows of `app`'s settings, with the color the panel edits for Current Color.
fn app_items(app: &VectorcraftApp) -> Vec<Item> {
items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), super::color::target_now(app).color())
}
/// The labels, checks and enabled states of [`menu_rows`].
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
for item in app_items(app) {
for item in items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), target_now(app).color()) {
let mut state = CommandState::new().title(item.label).enabled(item.enabled).checked(item.checked);
if let Some(hint) = item.hint {
state = state.hint(hint);
@@ -600,10 +606,11 @@ pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
/// Run the menu row `id` (`ui.colorWheel.<row>`); `None` when it is not one of this panel's.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option<Result<Value, String>> {
let row = id.strip_prefix("ui.colorWheel.")?;
if row == "contrastBackground.current" && super::color::target_now(app).color().is_none() {
let current = target_now(app).color();
if row == "contrastBackground.current" && current.is_none() {
return Some(Err("Current Color needs a solid color in the active proxy".to_string()));
}
let params = app_items(app).into_iter().find(|item| item.id == row)?.params;
let params = items(&app.ui.color_wheel, cms::active().rgb_is_srgb(), current).into_iter().find(|item| item.id == row)?.params;
Some(command(app, &params))
}
@@ -673,10 +680,14 @@ pub struct WheelUi {
rows_live: Option<Sliders>,
/// Whether a drag of the Show Opacity row previews on an open interaction, until it is released.
opacity_live: bool,
/// The color behind the selection, as `#rrggbb`, with the [`BehindKey`] it was read for.
/// The color behind the selection as `#rrggbb`, with the [`BehindKey`] it was read for.
pub(super) behind: Option<(BehindKey, Option<String>)>,
/// The contrast row's `color.contrast` answer, with the [`RatioKey`] it was asked for.
pub(super) ratio: Option<(RatioKey, Option<Value>)>,
/// What the contrast row's answer was measured against, with the [`RatioKey`] it was asked for.
backdrop: Option<(RatioKey, Option<Backdrop>)>,
/// The contrast lines of the square or the field, with the [`LinesKey`] they were found for.
pub(super) lines: Option<(LinesKey, Lines)>,
}
/// The colors the row shows and whether they are the selection's, read with `color.used` once per
@@ -810,6 +821,27 @@ fn picked_hsb(v: &ModelValues, shown: [f32; 3]) -> [f32; 3] {
if hsb[1] <= 0.0 || hsb[2] <= 0.0 { [shown[0], hsb[1], hsb[2]] } else { hsb }
}
/// The HSB the field of channel `ch`'s box picks at field point (`x`, `y`) (0 to 1 each, across from
/// the left and down from the top) around HSB `shown`, as the widget's field maps a point to its two
/// components. The wheel's square is the field of [`Channel::Hue`].
pub(super) fn field_pick(ch: Channel, x: f32, y: f32, shown: [f32; 3]) -> [f32; 3] {
let mode = area_mode(ch);
let channels = mode.model().channels();
let mut v = box_values(ch, shown);
for (c, t) in mode.area().into_iter().zip([x, 1.0 - y]) {
if let (Some(range), Some(value)) = (channels.get(c), v.values.get_mut(c)) {
*value = range.min + (range.max - range.min) * t.clamp(0.0, 1.0);
}
}
picked_hsb(&v, shown)
}
/// The component the field of channel `ch`'s box holds fixed around HSB `shown`: the strip's value.
pub(super) fn field_fixed(ch: Channel, shown: [f32; 3]) -> f32 {
let mode = area_mode(ch);
box_values(ch, shown).values.get(mode.strip()).copied().unwrap_or(0.0)
}
/// The widgets' color of display sRGB `rgb`.
fn srgb([r, g, b]: [f32; 3]) -> Srgba {
Srgba::rgb(r.clamp(0.0, 1.0), g.clamp(0.0, 1.0), b.clamp(0.0, 1.0))
@@ -889,6 +921,256 @@ pub(super) struct RatioKey {
pub(super) mesh_points: Vec<(NodeId, Vec<usize>)>,
/// Whether the Live Paint Bucket paints, which gives the proxies its paints without a revision.
pub(super) bucket: bool,
/// The Contrast For category, which the closest passing colors are for.
pub(super) category: Category,
}
/// What the contrast lines depend on: what the color is measured against, the category, the field
/// (the view, the channel and the component the field holds fixed) with the model a pick there
/// stores, the color settings, and whether they were found coarsely during a drag.
pub(super) type LinesKey = (Backdrop, Category, String, Under, bool);
/// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates.
pub(super) type Lines = Vec<Vec<Vec<(f32, f32)>>>;
/// The columns and rows at which [`contrast_lines`] samples a field.
const LINE_SAMPLES: usize = 32;
/// The columns and rows at which [`contrast_lines`] samples a field, without the narrow-band
/// search, while a drag changes the field (the hue ring, the box's strip).
const COARSE_LINE_SAMPLES: usize = 8;
/// The halvings that place a line on the edge between two samples.
const LINE_STEPS: usize = 10;
/// A point of a field: x across, y down, 0 to 1 each.
type FieldPoint = (f32, f32);
/// The passing bands found between the samples of one column or row: where each peaks along it, and
/// its two crossings.
type Bands = Vec<(f32, FieldPoint, FieldPoint)>;
/// The edge from sample (i, j) across (true) or down (false).
type EdgeKey = (usize, usize, bool);
/// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in
/// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell
/// whose edges are crossed gets segments between the crossings on its edges, placed by bisection
/// (marching squares; a cell crossed more than twice, as one with two opposite corners passing, is
/// split by its center).
/// With `narrow`, around a failing sample higher than its neighbors in a column or a row, the highest
/// ratio is looked for, so a passing band narrower than the samples gets its two edges too, joined
/// from column to column or from row to row. Where no band on the next or the previous line joins
/// one, its two crossings count among the crossings of the cell on that side, so a band that widens
/// past the samples or ends there is joined to the cell's other crossings instead of being cut
/// across. Segments that share an end are joined into one polyline.
pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64], n: usize, narrow: bool) -> Lines {
let n = n.max(1);
let at = |i: usize| i as f32 / n as f32;
// `grid[i][j]` is column i (x) and row j (y).
let grid: Vec<Vec<f64>> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect();
let r = |i: usize, j: usize| grid.get(i).and_then(|c| c.get(j)).copied().unwrap_or(f64::NAN);
minimums
.iter()
.map(|&min| {
let pass = |p: FieldPoint| ratio_at(p.0, p.1) >= min;
// The crossing between `p`, on the side `above` says, and `q`.
let cross = |p: FieldPoint, q: FieldPoint, above: bool| {
let lerp = |t: f32| (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t);
let (mut lo, mut hi) = (0.0, 1.0);
for _ in 0..LINE_STEPS {
let mid = (lo + hi) / 2.0;
if pass(lerp(mid)) == above { lo = mid } else { hi = mid }
}
lerp((lo + hi) / 2.0)
};
let mut edges: HashMap<(usize, usize, bool), Option<FieldPoint>> = HashMap::new();
// The crossing on the edge from sample (i, j) across (`across`) or down.
let mut edge = |i: usize, j: usize, across: bool| {
*edges.entry((i, j, across)).or_insert_with(|| {
let (i2, j2) = if across { (i + 1, j) } else { (i, j + 1) };
let (a, b) = (r(i, j) >= min, r(i2, j2) >= min);
(a != b).then(|| cross((at(i), at(j)), (at(i2), at(j2)), a))
})
};
let mut segments: Vec<[FieldPoint; 2]> = vec![];
// The crossings of the bands narrower than the samples on each edge between samples, with
// whether no band on the next line (the column to the right, the row below) and no band on
// the line before joins the band on that side.
let mut loose: HashMap<EdgeKey, Vec<(FieldPoint, [bool; 2])>> = HashMap::new();
// Bands narrower than the samples, along each column and then each row.
for across in [false, true].into_iter().filter(|_| narrow) {
let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) };
let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) };
let bands: Vec<Bands> = (0..=n)
.map(|k| {
let mut found = vec![];
for s in 0..=n {
let (before, after) = (s.saturating_sub(1), (s + 1).min(n));
let v = value(k, s);
if v >= min || v < value(k, before) || (after != s && v <= value(k, after)) {
continue;
}
let peak = wcag::peak_between(f64::from(at(before)), f64::from(at(after)), &|t| {
let p = point(k, t as f32);
ratio_at(p.0, p.1)
}) as f32;
if pass(point(k, peak)) {
found.push((
peak,
cross(point(k, at(before)), point(k, peak), false),
cross(point(k, peak), point(k, at(after)), true),
));
}
}
found
})
.collect();
// The band of `next` that the band peaking at `peak` joins.
let joins = |next: &Bands, peak: f32| next.iter().position(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32);
for (k, this) in bands.iter().enumerate() {
let next = bands.get(k + 1);
let before = k.checked_sub(1).and_then(|k| bands.get(k));
for (b, &(peak, p, q)) in this.iter().enumerate() {
let joined = next.and_then(|next| joins(next, peak).and_then(|m| next.get(m)));
if let Some(&(_, c, d)) = joined {
segments.extend([[p, c], [q, d]]);
}
let joined_before = before.is_some_and(|before| before.iter().any(|(bp, ..)| joins(this, *bp) == Some(b)));
let e = ((peak * n as f32).floor() as usize).min(n - 1);
let key = if across { (e, k, true) } else { (k, e, false) };
let open = [joined.is_none(), !joined_before];
loose.entry(key).or_default().extend([(p, open), (q, open)]);
}
}
}
for i in 0..n {
for j in 0..n {
let (x0, y0, w) = (at(i), at(j), 1.0 / n as f32);
// Where point `p` on edge `s` (0 to 3: top, right, bottom, left) lies going around
// the cell clockwise from its top left corner.
let place = |s: usize, p: FieldPoint| match s {
0 => (p.0 - x0) / w,
1 => 1.0 + (p.1 - y0) / w,
2 => 2.0 + (x0 + w - p.0) / w,
_ => 3.0 + (y0 + w - p.1) / w,
};
// The cell's edges, each with the side of the edge's line the cell is on: after
// its top and left edges' lines (0) and before its right and bottom edges' (1).
let sides = [((i, j, true), 0), ((i + 1, j, false), 1), ((i, j + 1, true), 1), ((i, j, false), 0)];
let mut around: Vec<(f32, FieldPoint)> = vec![];
for (s, (key, side)) in sides.into_iter().enumerate() {
let (ei, ej, across) = key;
around.extend(edge(ei, ej, across).map(|p| (place(s, p), p)));
let band = loose.get(&key).into_iter().flatten().filter(|(_, open)| open.get(side).copied().unwrap_or(false));
around.extend(band.map(|&(p, _)| (place(s, p), p)));
}
around.sort_by(|a, b| a.0.total_cmp(&b.0));
let m = around.len();
if m < 2 {
continue;
}
// Going around from the top left corner, the side changes at each crossing. Where
// the crossings leave more than one passing stretch of the edges, the center says
// whether those stretches join inside the cell (the segments cut off the failing
// stretches) or not (they cut off the passing ones).
let corner = r(i, j) >= min;
let half = 0.5 / n as f32;
let cut = if m == 2 { !corner } else { !pass((x0 + half, y0 + half)) };
// The stretch between crossings 0 and 1 is on the side the corner is not.
let start = usize::from(corner == cut);
for k in (start..m).step_by(2) {
if let (Some(&(_, p)), Some(&(_, q))) = (around.get(k), around.get((k + 1) % m)) {
segments.push([p, q]);
}
}
}
}
chain(segments)
})
.collect()
}
/// `segments` joined end to end into polylines where they share an end.
fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec<Vec<FieldPoint>> {
let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits());
let mut ends: HashMap<(u32, u32), Vec<usize>> = HashMap::new();
for (s, seg) in segments.iter().enumerate() {
for p in seg {
ends.entry(key(*p)).or_default().push(s);
}
}
let mut used = vec![false; segments.len()];
let mut lines = vec![];
for (start, [a, b]) in segments.iter().enumerate() {
if used.get(start).copied().unwrap_or(true) {
continue;
}
if let Some(u) = used.get_mut(start) {
*u = true;
}
let mut line = std::collections::VecDeque::from([*a, *b]);
for back in [true, false] {
loop {
let end = if back { line.back() } else { line.front() };
let Some(end) = end.copied() else { break };
let next = ends.get(&key(end)).and_then(|ss| ss.iter().copied().find(|s| !used.get(*s).copied().unwrap_or(true)));
let Some((s, [p, q])) = next.and_then(|s| segments.get(s).map(|seg| (s, *seg))) else { break };
if let Some(u) = used.get_mut(s) {
*u = true;
}
let other = if key(p) == key(end) { q } else { p };
if back { line.push_back(other) } else { line.push_front(other) }
}
}
lines.push(line.into_iter().collect());
}
lines
}
/// The contrast lines of the wheel's square or the box's field on HSB `hsb`, kept per [`LinesKey`]:
/// where a pick there, stored as the wheel stores it in place of `tgt`'s color, meets each minimum
/// of the chosen category against `backdrop`. While a drag is live and the field differs from the
/// one the kept lines were found for, the lines are found coarsely ([`COARSE_LINE_SAMPLES`]), and
/// in full once the drag ends.
fn lines_for(app: &VectorcraftApp, panel: &mut WheelUi, backdrop: &Backdrop, cx: &Pick) -> Lines {
let set = &app.ui.color_wheel;
let (category, view) = (set.contrast_for, set.view);
// The wheel's square is the field of the hue box.
let ch = if view == View::Box { set.channel } else { Channel::Hue };
let was = replaced(app, cx.tgt, false);
let hsb = cx.shown;
let field = format!("{view:?} {ch:?} {} {:?} {}", field_fixed(ch, hsb), was.map(|c| c.model()), cx.cmyk_doc);
let dragging = app.session.in_interaction();
let key = |coarse: bool| -> LinesKey { (backdrop.clone(), category, field.clone(), under(), coarse) };
if let Some((k, lines)) = &panel.lines
&& (*k == key(false) || (dragging && *k == key(true)))
{
return lines.clone();
}
let ratio_at = |x: f32, y: f32| backdrop.ratio(backdrop.shown(cx.cms, &stored(cx.cms, field_pick(ch, x, y, hsb), was.as_ref(), cx.cmyk_doc)));
let (aa, aaa) = category.minimums();
let minimums: Vec<f64> = std::iter::once(aa).chain(aaa).collect();
let samples = if dragging { COARSE_LINE_SAMPLES } else { LINE_SAMPLES };
let lines = contrast_lines(&ratio_at, &minimums, samples, !dragging);
panel.lines = Some((key(dragging), lines.clone()));
lines
}
/// Draw `lines` (from [`contrast_lines`]) over the field in `rect`: AA solid and AAA dashed, each
/// a light line over a dark one, as the field's marker is drawn.
fn draw_contrast_lines(ui: &Ui, rect: Rect, lines: &Lines) {
let painter = ui.painter().with_clip_rect(rect);
let at = |(x, y): &(f32, f32)| egui::pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height());
for (level, polylines) in lines.iter().enumerate() {
for line in polylines {
let points: Vec<egui::Pos2> = line.iter().map(at).collect();
for stroke in [Stroke::new(3.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] {
if level == 0 {
painter.add(egui::Shape::line(points.clone(), stroke));
} else {
painter.extend(egui::Shape::dashed_line(&points, stroke, 4.0, 3.0));
}
}
}
}
}
/// The active color settings and profiles generation, which change how a color displays without
@@ -927,9 +1209,19 @@ fn background(app: &mut VectorcraftApp, panel: &mut WheelUi) -> Option<Color> {
Color::from_hex(&hex?)
}
/// The `color.contrast` answer against `pinned`, else against the color behind the selection
/// (`against: "below"`), kept per [`RatioKey`].
fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option<Color>) -> Option<Value> {
/// The contrast row's measurement: `color.contrast`'s answer for the chosen category, and what the
/// lines measure picks against.
struct Measured {
answer: Option<Value>,
backdrop: Option<Backdrop>,
}
/// The `color.contrast` answer for the chosen category against the pinned background, else
/// against the color behind the selection (`against: "below"`), with what it measured the color
/// against, kept per [`RatioKey`].
fn measure(app: &VectorcraftApp, panel: &mut WheelUi) -> Measured {
let category = app.ui.color_wheel.contrast_for;
let pinned = app.ui.color_wheel.contrast_background;
let st = app.session.active();
let key = RatioKey {
background: pinned.map_or_else(|| "below".to_string(), |bg| format!("{bg:?}")),
@@ -945,33 +1237,43 @@ fn ratio_answer(app: &mut VectorcraftApp, panel: &mut WheelUi, pinned: Option<Co
under: under(),
mesh_points: app.session.fill_mesh_points(),
bucket: app.session.tool_paints(!app.session.fill_active),
category,
};
match &panel.ratio {
Some((k, r)) if *k == key => r.clone(),
match (&panel.ratio, &panel.backdrop) {
(Some((k, answer)), Some((kb, backdrop))) if *k == key && *kb == key => Measured { answer: answer.clone(), backdrop: backdrop.clone() },
_ => {
let against = pinned.as_ref().map_or_else(|| json!("below"), crate::panels::color_json);
let r = app.session.execute("color.contrast", &json!({ "against": against })).ok();
panel.ratio = Some((key, r.clone()));
r
let against = pinned.as_ref().map_or_else(|| json!("below"), color_json);
let p = json!({ "against": against, "for": category.id() });
// With no color to measure (a fill of None, a pattern), a pick there is still measured.
let (answer, backdrop) = match contrast_measure(&app.session, &p) {
Ok((r, b)) => (Some(r), Some(b)),
Err(_) => (None, contrast_pick_backdrop(&app.session, &p).ok()),
};
panel.ratio = Some((key.clone(), answer.clone()));
panel.backdrop = Some((key, backdrop.clone()));
Measured { answer, backdrop }
}
}
}
/// The contrast row: the background's chip, the ratio cut off at two decimals and the AA and AAA
/// results for the chosen category; a dash when there is no background or no color to measure.
/// Without a pinned background the row asks `color.contrast` for the color behind the selection
/// (`against: "below"`), also during an interaction, so translucent groups and layers count as the
/// command counts them; the chip then shows the background in the answer. Only when there is no
/// answer is the background read on its own ([`background`]), so the chip still shows it. The chip
/// is a color well named Background whose value is the background's hex value, as the color vision
/// chips are; a click on it does nothing.
fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms) {
/// The contrast row: the background's chip, the ratio cut off at two decimals, the AA and AAA
/// results for the chosen category, and a chip of the closest color that passes the first level the
/// color fails, when `color.contrast` finds one for that level; a dash when there is no background
/// or no color to measure. Without a pinned background the row asks `color.contrast` for the color
/// behind the selection (`against: "below"`), also during an interaction, so translucent groups and
/// layers count as the command counts them. The first chip shows the background the answer
/// measured against, pinned or not, else the one a pick would be measured against (a pinned 100 %
/// K shows as black with a rich black Appearance of Black). Only when there is neither is the
/// background read on its own ([`background`]), so the chip still shows it. The chip is named
/// Background, with the background's hex value as its value, as the color vision chips are.
/// Returns the fix color when its chip is clicked or activated.
fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms: &Cms, m: &Measured) -> Option<Color> {
let category = app.ui.color_wheel.contrast_for;
let pinned = app.ui.color_wheel.contrast_background;
let answer = ratio_answer(app, panel, pinned);
// The background the ratio was measured against.
let measured = answer.as_ref().filter(|_| pinned.is_none()).and_then(|r| r["against"].as_str()).and_then(Color::from_hex);
let chip = match pinned.or(measured) {
let answer = m.answer.as_ref();
let against = answer.and_then(|r| r["against"].as_str().map(str::to_string)).or_else(|| m.backdrop.as_ref().map(Backdrop::against_hex));
let measured = against.as_deref().and_then(Color::from_hex);
let chip = match measured.or(pinned) {
Some(c) => Some(c),
None => background(app, panel),
};
@@ -983,22 +1285,55 @@ fn contrast_row(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cms:
tip.push(' ');
tip.push_str(tl!("The background is read at the center of the selection."));
}
let ratio = answer.as_ref().and_then(|r| r["ratio"].as_f64());
Row::new().show(ui, |ui, _| {
let well = Mixed::Same(chip.map(|c| srgb(cms.display_rgb(&c))));
let _ = Swatch::optional(tl!("Background").to_string(), well).tooltip(tip.clone()).show(ui);
let Some(ratio) = ratio else {
Text::new("—").tooltip(tip.clone()).show(ui);
return;
let entries = [(Label::from(tl!("Background").to_string()), chip.map_or(Srgba::new(0.0, 0.0, 0.0, 0.0), |c| srgb(cms.display_rgb(&c))))];
ui.horizontal(|ui| {
// The chip holds no selection: a click reports one the row ignores.
let _ = SwatchTable::new(tl!("Contrast Background").to_string(), &entries)
.per_row(1)
.tips(true)
.selection(Bind::given(Selection::default()))
.show_all(ui);
let Some(ratio) = answer.and_then(|r| r["ratio"].as_f64()) else {
Text::new("—").tooltip(tip).show(ui);
return None;
};
Text::new(wcag::ratio_text(ratio)).tooltip(tip.clone()).show(ui);
let (aa, aaa) = category.passes(ratio);
let result = |pass: bool| if pass { tl!("Pass") } else { tl!("Fail") };
Text::new(format!("AA {}", result(aa))).tooltip(tip.clone()).show(ui);
if let Some(aaa) = aaa {
Text::new(format!("AAA {}", result(aaa))).tooltip(tip.clone()).show(ui);
Text::new(format!("AAA {}", result(aaa))).tooltip(tip).show(ui);
}
});
fix_chip(ui, cms, answer, aa, aaa)
})
.inner
}
/// The fix chip at the end of the contrast row: the closest color that passes AA when the color
/// fails AA (`aa`), else AAA when it fails AAA (`aaa`), from `color.contrast`'s `fix`. Nothing is
/// shown when there is none. Returns the color when the chip is clicked or activated.
fn fix_chip(ui: &mut Ui, cms: &Cms, answer: Option<&Value>, aa: bool, aaa: Option<bool>) -> Option<Color> {
let level = if !aa {
Some(("aa", "AA"))
} else if aaa == Some(false) {
Some(("aaa", "AAA"))
} else {
None
};
let (color, name) = level.and_then(|(key, name)| {
let v = answer?.get("fix")?.get(key)?;
serde_json::from_value::<Color>(v.clone()).ok().map(|c| (c, name))
})?;
let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]);
let entries = [(Label::from(label), srgb(cms.display_rgb(&color)))];
let out = SwatchTable::new(tl!("Closest Passing Color").to_string(), &entries)
.per_row(1)
.tips(true)
.activate(ActivateOn::Click)
// The chip applies by click and holds no selection of its own.
.selection(Bind::given(Selection::default()))
.show_all(ui);
out.open.map(|_| color)
}
/// What the HSB picked last belongs to: the document, the selected objects or text characters,
@@ -1626,8 +1961,8 @@ fn apply_text(app: &mut VectorcraftApp, ui: &Ui, text: &str, opacity_set: bool,
/// The wheel: the hue ring around the saturation and brightness square, with Show Harmony's markers
/// on the ring. A click on a marker applies its color; a press held on one keeps the ring from
/// picking.
fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Picked {
/// picking. Returns the picks and the square's rect.
fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> (Picked, Option<Rect>) {
let marked = cx.color.is_some();
let others: Vec<[f32; 3]> = if set.harmony && marked { set.harmony_rule.apply_hsb(cx.shown).into_iter().skip(1).collect() } else { Vec::new() };
let markers: Vec<Srgba> = others.iter().map(|&hsb| srgb(hsb_to_rgb(hsb))).collect();
@@ -1640,14 +1975,18 @@ fn show_wheel(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> P
wheel = wheel.gamut(gamut(app));
}
let out = wheel.show(ui);
match out.picked.and_then(|i| others.get(i)) {
// The square is the wheel's child named `square`.
let square = ui.ctx().read_response(out.edit.response.id.with("square")).map(|r| r.rect);
let picked = match out.picked.and_then(|i| others.get(i)) {
Some(&hsb) => Picked { marker: Some(hsb), edits: Vec::new() },
None => Picked { marker: None, edits: vec![out.edit] },
}
};
(picked, square)
}
/// The box: the field of channel `set.channel` and its strip.
fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Picked {
/// The box: the field of channel `set.channel` and its strip. Returns the picks and the field's
/// rect.
fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> (Picked, Option<Rect>) {
let ch = set.channel;
let mode = area_mode(ch);
let values = cx.color.map(|_| box_values(ch, cx.shown));
@@ -1656,8 +1995,9 @@ fn show_box(app: &VectorcraftApp, ui: &mut Ui, cx: &Pick, set: &Settings) -> Pic
area = area.gamut(gamut(app));
}
let field = area.show(ui);
let rect = field.response.rect;
let strip = ColorStrip::new(ch.name().to_string(), mode, bind(values)).show(ui);
Picked { marker: None, edits: vec![field, strip] }
(Picked { marker: None, edits: vec![field, strip] }, Some(rect))
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
@@ -1696,13 +2036,16 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) {
fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pick, set: &Settings, now: f64) {
let (cms, behind, cmyk_doc, hsb) = (cx.cms, cx.behind, cx.cmyk_doc, cx.shown);
let mut picked = Picked::default();
let measured = set.contrast.then(|| measure(app, panel));
// The rect of the box's field or the wheel's square, which the contrast lines are drawn over.
let mut field = None;
Grid::new(&BESIDE).cells(CellAlign::Top).show(ui, |ui, _| {
super::proxy(app, ui);
match set.view {
View::Box => {
Row::new().fill_width().show(ui, |ui, _| picked = show_box(app, ui, cx, set));
Row::new().fill_width().show(ui, |ui, _| (picked, field) = show_box(app, ui, cx, set));
}
View::Wheel => picked = show_wheel(app, ui, cx, set),
View::Wheel => (picked, field) = show_wheel(app, ui, cx, set),
}
});
// The hex field shows the text of the frame's start, so a text committed when a press on the
@@ -1792,8 +2135,15 @@ fn show_rows(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui, cx: &Pi
app.sync_views();
panel.rows_live = None;
}
if set.contrast {
contrast_row(app, panel, ui, cx.cms);
if let Some(m) = &measured {
// With Alt held a pick goes to the other proxy, which the lines do not measure.
if let (Some(backdrop), Some(rect)) = (m.backdrop.as_ref().filter(|_| !cx.behind), field) {
let lines = lines_for(app, panel, backdrop, cx);
draw_contrast_lines(ui, rect, &lines);
}
if let Some(c) = contrast_row(app, panel, ui, cx.cms, m) {
apply(app, cx.tgt, c, Live::Released, false);
}
}
if set.vision {
vision_row(ui, cx.cms, cx.color.as_ref());
@@ -1,13 +1,11 @@
//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and
//! the AA and AAA results, the color behind the selection, a pinned background, a drag on the
//! wheel, the panel menu and `ui.colorWheel`.
//! The Color Wheel panel's Show Contrast row drawn headless through the `Fixture`: the ratio and the
//! AA and AAA results, the color behind the selection, a pinned background, the panel menu, a drag
//! on the wheel, and `ui.colorWheel`.
use craft::ui::runtime::access::Role;
use serde_json::{Value, json};
use vectorcraft_color::wcag;
use vectorcraft_engine::Session;
use super::color_wheel::{BehindKey, RatioKey};
use super::tests_color_wheel::Panel;
use crate::VectorcraftApp;
use crate::i18n::LangExt as _;
@@ -26,6 +24,18 @@ fn shows(p: &Panel, text: &str) -> bool {
p.fx.by_label(text).is_some()
}
/// The background read on its own, as `#rrggbb`, if the row read one.
fn behind(p: &Panel) -> Option<Option<String>> {
p.app().ui.color_wheel_panel.behind.as_ref().map(|(_, hex)| hex.clone())
}
/// The background in the row's kept answer.
fn measured(p: &Panel) -> Option<String> {
let app = p.app();
let answer = app.ui.color_wheel_panel.ratio.as_ref().and_then(|(_, r)| r.as_ref());
answer.and_then(|r| r["against"].as_str().map(str::to_string))
}
#[test]
fn the_row_cuts_the_ratio_off_and_fails_aa_just_under_it() {
let mut app = app("#fdc96e");
@@ -45,25 +55,24 @@ fn the_contrast_for_menu_shows_the_categories_in_the_interface_language() {
assert_ne!(names[0], Category::NormalText.label());
}
/// The panel menu's Show Contrast, Contrast For and Contrast Background rows set the settings, and
/// The panel menu's Show Contrast, Contrast For and Contrast Background rows set the row, and
/// Current Color pins the color the panel edits.
#[test]
fn the_panel_menu_sets_the_contrast_settings() {
fn the_panel_menu_sets_the_row_its_category_and_its_background() {
let mut app = app("#336699");
app.run("ui.colorWheel", json!({"contrast": false})).unwrap();
let run = |app: &mut VectorcraftApp, row: &str| super::color_wheel::run(app, &format!("ui.colorWheel.{row}"), &json!({})).unwrap().unwrap();
assert_eq!(run(&mut app, "contrast")["contrast"], true);
assert_eq!(run(&mut app, "contrastFor.graphics")["contrastFor"], "graphics");
run(&mut app, "contrastBackground.current");
let run = |app: &mut VectorcraftApp, row: &str| super::color_wheel::run(app, &format!("ui.colorWheel.{row}"), &Value::Null).expect("a menu row");
run(&mut app, "contrast").unwrap();
assert!(app.ui.color_wheel.contrast);
run(&mut app, "contrastFor.largeText").unwrap();
assert_eq!(app.ui.color_wheel.contrast_for, wcag::Category::LargeText);
run(&mut app, "contrastBackground.current").unwrap();
assert_eq!(app.ui.color_wheel.contrast_background.map(|c| c.to_hex()).as_deref(), Some("#336699"));
assert_eq!(run(&mut app, "contrastBackground.below")["contrastBackground"], Value::Null);
let mut states = craft::ui::runtime::commands::CommandStates::new();
run(&mut app, "contrastBackground.below").unwrap();
assert_eq!(app.ui.color_wheel.contrast_background, None);
// With no solid color in the active proxy there is no color to pin.
app.run("paint.setFill", json!({"none": true})).unwrap();
super::color_wheel::menu_states(&app, &mut states);
let current = states.get(&craft::keymap::CommandRef::new("ui.colorWheel.contrastBackground.current")).expect("a state");
assert!(!current.is_enabled(), "Current Color needs a color to pin");
let e = super::color_wheel::run(&mut app, "ui.colorWheel.contrastBackground.current", &json!({})).unwrap().unwrap_err();
assert_eq!(e, "Current Color needs a solid color in the active proxy");
assert!(run(&mut app, "contrastBackground.current").is_err());
assert_eq!(app.ui.color_wheel.contrast_background, None, "the error pins nothing");
}
@@ -75,11 +84,13 @@ fn an_answer_kept_under_other_color_settings_is_asked_again() {
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "21.00:1"));
let (mut key, answer) = p.app().ui.color_wheel_panel.ratio.clone().expect("the row keeps its answer");
let mut stale = answer.expect("an answer");
stale["ratio"] = json!(1.0);
key.under.1 = u64::MAX;
p.app_mut().ui.color_wheel_panel.ratio = Some((key, Some(stale)));
{
let mut app = p.app_mut();
let (key, answer) = app.ui.color_wheel_panel.ratio.as_mut().expect("the row keeps its answer");
let stale = answer.as_mut().expect("an answer");
stale["ratio"] = json!(1.0);
key.under.1 = u64::MAX;
}
p.fx.idle(2);
assert!(shows(&p, "21.00:1"), "the answer is asked again under the current settings");
}
@@ -127,11 +138,21 @@ fn the_background_is_the_art_behind_the_selection() {
let want = wcag::ratio_text(wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]));
assert!(shows(&p, &want), "black on the locked yellow: {want}");
// Screen readers find the chip by its name, with the background's hex value as its value.
let chip = p.node("Background");
assert_eq!(p.fx.tree().role_of(chip.node), Some(Role::COLOR_WELL));
assert_eq!(p.value("Background").as_deref(), Some("#ffff00"));
}
/// A pinned 100 % K is measured as black with a rich black Appearance of Black, and the Background
/// chip names the black the ratio uses.
#[test]
fn the_background_chip_shows_the_black_a_pinned_k_is_measured_as() {
let mut app = app("#ffffff");
app.run("ui.colorWheel", json!({"contrastBackground": {"c": 0, "m": 0, "y": 0, "k": 1}})).unwrap();
app.session.prefs.black_on_screen = "rich".into();
let p = Panel::new(app);
assert!(shows(&p, "21.00:1"), "white on black");
assert_eq!(p.value("Background").as_deref(), Some("#000000"));
}
#[test]
fn nothing_selected_and_nothing_pinned_shows_no_ratio() {
let mut app = app("#000000");
@@ -157,39 +178,30 @@ fn the_row_follows_the_default_fill_with_nothing_selected() {
assert!(shows(&p, "1.00:1"), "white on the pinned white");
}
/// The background read on its own, with what it was read for.
fn behind(p: &Panel) -> Option<(BehindKey, Option<String>)> {
p.app().ui.color_wheel_panel.behind.clone()
}
/// The background in the row's kept answer.
fn measured(p: &Panel) -> Option<String> {
let kept: Option<(RatioKey, Option<Value>)> = p.app().ui.color_wheel_panel.ratio.clone();
kept.and_then(|(_, r)| r).and_then(|r| r["against"].as_str().map(str::to_string))
}
/// During a drag on the wheel every preview raises the document's revision, and the row asks again
/// for the ratio, whose answer gives the chip: the background is not read on its own as well. The
/// drag is an interaction whose previews set the fill, as the Show Document Colors row's drag test
/// runs it.
/// for the ratio, whose answer gives the chip: the background is not read on its own as well.
#[test]
fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() {
let mut p = Panel::new(app("#336699"));
assert_eq!(measured(&p).as_deref(), Some("#ffffff"));
assert!(behind(&p).is_none(), "the answer gave the background");
p.app_mut().session.begin_interaction("test").unwrap();
for fill in ["#3a6a9a", "#406f9f", "#4675a5"] {
p.run("paint.setFill", json!({"color": fill}));
}
let ratio = |p: &Panel| p.app().ui.color_wheel_panel.ratio.as_ref().and_then(|(_, r)| r.as_ref()).and_then(|r| r["ratio"].as_f64());
let first = ratio(&p);
// A drag on the hue ring, near its right edge.
let wheel = p.node("Color wheel").rect;
let at = wheel.center() + egui::vec2(wheel.width() * 0.45, 0.0);
let by = egui::vec2(0.0, 24.0);
p.fx.drag_hold_at(at, by);
assert!(p.app().session.in_interaction(), "the drag previews on an interaction");
p.app_mut().session.commit_interaction().unwrap();
p.fx.idle(2);
assert_ne!(ratio(&p), first, "the row asked again for the previewed color");
p.fx.release_at(at + by).idle(2);
assert!(!p.app().session.in_interaction(), "the release ends the drag");
assert!(behind(&p).is_none(), "the background was not read on its own during or after the drag");
assert_eq!(measured(&p).as_deref(), Some("#ffffff"));
}
/// With no color to measure the row has no ratio, and the chip still shows the background, read on
/// its own, and read again for another selection during an interaction.
/// With no color to measure the row has no ratio, and the chip still shows the background a pick
/// would be measured against, read again for another selection during an interaction.
#[test]
fn a_paint_with_no_color_still_shows_the_background() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
@@ -205,13 +217,12 @@ fn a_paint_with_no_color_still_shows_the_background() {
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut p = Panel::new(app);
assert!(shows(&p, "—"), "a fill of None has no ratio");
let hex = |p: &Panel| behind(p).and_then(|(_, hex)| hex);
assert_eq!(hex(&p).as_deref(), Some("#ffff00"));
assert_eq!(p.value("Background").as_deref(), Some("#ffff00"), "the chip shows it");
assert_eq!(p.value("Background").as_deref(), Some("#ffff00"));
assert!(behind(&p).is_none(), "the background a pick is measured against was not read again on its own");
p.app_mut().run("select.set", json!({"ids": [b]})).unwrap();
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert_eq!(hex(&p).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction");
assert_eq!(p.value("Background").as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction");
}
/// With no color to measure, a move during an interaction reads the background again at the
@@ -227,14 +238,13 @@ fn a_move_during_an_interaction_reads_the_background_again() {
app.run("paint.setFill", json!({"none": true})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut p = Panel::new(app);
let hex = |p: &Panel| behind(p).and_then(|(_, hex)| hex);
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert_eq!(hex(&p).as_deref(), Some("#ffff00"));
assert_eq!(p.value("Background").as_deref(), Some("#ffff00"));
p.app_mut().run("object.move", json!({"dx": 110, "dy": 0})).unwrap();
assert!(p.app().session.in_interaction(), "the move is part of the interaction");
p.fx.idle(2);
assert_eq!(hex(&p).as_deref(), Some("#ffffff"), "the background at the new place");
assert_eq!(p.value("Background").as_deref(), Some("#ffffff"), "the background at the new place");
}
/// An interaction keeps no answer for another selection: the row asks again, and the chip shows
@@ -257,7 +267,7 @@ fn an_interaction_reads_the_background_again_for_another_selection() {
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert_eq!(measured(&p).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction");
assert_eq!(p.value("Background").as_deref(), Some("#ffffff"), "the chip shows it");
assert_eq!(p.value("Background").as_deref(), Some("#ffffff"));
}
/// Without a pin the row asks for the color behind the selection, so a translucent group holding
@@ -280,10 +290,13 @@ fn the_row_answers_as_color_contrast_does_inside_a_translucent_group() {
app.run("select.set", json!({"ids": [front]})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let p = Panel::new(app);
let want = p.app_mut().session.execute("color.contrast", &json!({})).unwrap();
let against = want["against"].clone();
let given = p.app_mut().session.execute("color.contrast", &json!({"against": against})).unwrap();
let (want, given) = (wcag::ratio_text(want["ratio"].as_f64().unwrap()), wcag::ratio_text(given["ratio"].as_f64().unwrap()));
let (want, given) = {
let mut app = p.app_mut();
let want = app.session.execute("color.contrast", &json!({})).unwrap();
let against = want["against"].clone();
let given = app.session.execute("color.contrast", &json!({"against": against})).unwrap();
(wcag::ratio_text(want["ratio"].as_f64().unwrap()), wcag::ratio_text(given["ratio"].as_f64().unwrap()))
};
assert_ne!(want, given, "the group's other art makes the two answers differ");
assert!(shows(&p, &want), "the row shows {want}, not {given}");
}
@@ -0,0 +1,260 @@
//! The Color Wheel panel's contrast lines on the box's field and the wheel's square, and the chip of
//! the closest passing color in the contrast row, drawn headless through the `Fixture`.
use egui::{Color32, Modifiers};
use serde_json::json;
use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb};
use vectorcraft_engine::Session;
use super::color_wheel::{Channel, Lines, contrast_lines, field_pick};
use super::tests_color_wheel::Panel;
use crate::VectorcraftApp;
/// An app with a selected rectangle filled with #FDC96E, the contrast row shown against a pinned
/// #355F78 (4.4963:1, just under AA for normal text), and `view` with `channel`.
fn app(view: &str, channel: &str) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": "#fdc96e"})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true, "contrastBackground": "#355f78", "view": view, "channel": channel})).unwrap();
app
}
fn lines(p: &Panel) -> Lines {
p.app().ui.color_wheel_panel.lines.clone().expect("the field's contrast lines were found").1
}
/// Whether the lines were found coarsely, during a drag that changes the field.
fn coarse(p: &Panel) -> bool {
p.app().ui.color_wheel_panel.lines.as_ref().expect("lines were found").0.4
}
/// Whether the color picked at field point (x, y) meets AA for normal text against #355F78, as
/// `color.contrast` answers it; `hsb_at` maps the point to the HSB the field picks there.
fn passes_aa(p: &Panel, hsb_at: &dyn Fn(f32, f32) -> [f32; 3], (x, y): (f32, f32)) -> bool {
let [r, g, b] = hsb_to_rgb(hsb_at(x, y));
let r = p.app_mut().session.execute("color.contrast", &json!({"color": [r, g, b], "against": "#355f78"})).unwrap();
r["normalText"]["aa"].as_bool().unwrap()
}
/// The middle point of the longest AA line, and the points a little above and below it.
fn either_side(lines: &Lines) -> [(f32, f32); 2] {
let aa = lines.first().expect("an AA level");
let line = aa.iter().max_by_key(|l| l.len()).expect("an AA line");
let (x, y) = line[line.len() / 2];
[(x, (y - 0.04).max(0.0)), (x, (y + 0.04).min(1.0))]
}
/// The display HSB of #FDC96E.
fn shown_hsb() -> [f32; 3] {
vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap()))
}
/// The clip rects of the dark strokes of the solid (AA) lines the panel draws, in a fresh frame.
fn dark_line_clips(p: &mut Panel) -> Vec<egui::Rect> {
p.fx.frame_clipped_shapes()
.into_iter()
.filter(|(_, shape)| matches!(shape, egui::Shape::Path(path) if path.stroke.width == 3.0 && matches!(path.stroke.color, egui::epaint::ColorMode::Solid(c) if c == Color32::BLACK)))
.map(|(clip, _)| clip)
.collect()
}
#[test]
fn the_box_marks_where_its_colors_meet_aa() {
let mut p = Panel::new(app("box", "hue"));
let lines = lines(&p);
assert_eq!(lines.len(), 2, "AA and AAA for normal text");
let hsb = shown_hsb();
let at = move |x: f32, y: f32| field_pick(Channel::Hue, x, y, hsb);
let [above, below] = either_side(&lines);
let (a, b) = (passes_aa(&p, &at, above), passes_aa(&p, &at, below));
assert_ne!(a, b, "the points either side of the line fall on either side of AA");
// Against a dark background the lighter colors, at the top, pass.
assert!(a && !b);
let field = p.node("Color box").rect;
let clips = dark_line_clips(&mut p);
assert!(!clips.is_empty() && clips.iter().all(|c| *c == field), "the lines are drawn over the field: {clips:?} {field:?}");
}
#[test]
fn the_wheels_square_marks_where_its_colors_meet_aa() {
let mut p = Panel::new(app("wheel", "hue"));
let lines = lines(&p);
let hsb = shown_hsb();
let at = move |x: f32, y: f32| [hsb[0], x, 1.0 - y];
let [above, below] = either_side(&lines);
assert!(passes_aa(&p, &at, above) && !passes_aa(&p, &at, below));
let square = p.node("Saturation and brightness").rect;
let clips = dark_line_clips(&mut p);
assert!(!clips.is_empty() && clips.iter().all(|c| *c == square), "the lines are drawn over the square: {clips:?} {square:?}");
}
/// White with Difference over a pinned #757575: in the gray box (saturation 0) only grays within a
/// few hundredths of #757575 draw dark enough for AA, a band narrower than the samples.
#[test]
fn a_band_narrower_than_the_samples_gets_its_lines() {
let mut app = app("box", "saturation");
app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap();
app.run("transparency.set", json!({"blend": "difference"})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#757575"})).unwrap();
let p = Panel::new(app);
let lines = lines(&p);
let aa = lines.first().expect("an AA level");
assert!(aa.len() >= 2, "a line on each side of the band: {aa:?}");
p.app_mut().run("paint.setFill", json!({"color": "#757575"})).unwrap();
let r = p.app_mut().session.execute("color.contrast", &json!({"against": "#757575"})).unwrap();
assert!(r["normalText"]["aa"] == true, "#757575 draws black and passes: {r}");
}
/// Multiply over a pinned #FF0000 keeps only the red of a pick, so in the blue box (red across)
/// the contrast changes across and not up: the AA line runs top to bottom.
#[test]
fn a_line_that_runs_up_the_field_is_found() {
let mut app = app("box", "blue");
app.run("transparency.set", json!({"blend": "multiply"})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#ff0000"})).unwrap();
let p = Panel::new(app);
let lines = lines(&p);
let line = lines.first().and_then(|aa| aa.iter().max_by_key(|l| l.len())).expect("an AA line");
let (xs, ys): (Vec<f32>, Vec<f32>) = line.iter().copied().unzip();
let spread = |v: &[f32]| v.iter().copied().fold(f32::NEG_INFINITY, f32::max) - v.iter().copied().fold(f32::INFINITY, f32::min);
assert!(spread(&ys) > 0.9 && spread(&xs) < 0.05, "{line:?}");
}
/// A passing band around x = 0.515625 that is narrower than the samples near the top and wider
/// below: every point of its center passes, so no line crosses it, and its two edges run on either
/// side of it from the top to the bottom.
#[test]
fn a_band_that_widens_past_the_samples_is_not_cut_across() {
let center = 0.515625;
let ratio = |x: f32, y: f32| 4.5 + 0.009 + 0.013 * f64::from(y) - f64::from((x - center).abs());
let lines = contrast_lines(&ratio, &[4.5], 32, true);
let aa = lines.first().expect("one level");
for line in aa {
for pair in line.windows(2) {
let [p, q] = pair else { continue };
assert!((p.0 - center) * (q.0 - center) > 0.0, "{p:?} to {q:?} crosses the passing center");
}
}
let side = |left: bool| aa.iter().flatten().filter(|p| (p.0 < center) == left).map(|p| p.1).collect::<Vec<_>>();
for points in [side(true), side(false)] {
let low = points.iter().copied().fold(f32::INFINITY, f32::min);
let high = points.iter().copied().fold(f32::NEG_INFINITY, f32::max);
assert!(low < 0.05 && high > 0.95, "an edge runs from the top to the bottom: {low} to {high}");
}
}
/// With a fill of None the row shows a dash, and the field still marks where a pick there passes.
#[test]
fn a_fill_of_none_keeps_its_lines() {
let mut app = app("box", "hue");
app.run("paint.setFill", json!({"none": true})).unwrap();
let p = Panel::new(app);
assert!(p.fx.by_label("—").is_some(), "no color to measure");
let lines = lines(&p);
assert!(lines.first().is_some_and(|aa| !aa.is_empty()), "an AA line: {lines:?}");
}
/// While Alt is held a pick goes to the other proxy, so the field's lines, which measure the active
/// one, are not drawn; they come back once Alt is let go.
#[test]
fn the_lines_are_hidden_while_alt_is_held() {
let mut p = Panel::new(app("box", "hue"));
p.app_mut().ui.color_wheel_panel.lines = None;
p.fx.hold(Modifiers::ALT).idle(2);
assert!(p.app().ui.color_wheel_panel.lines.is_none(), "no lines with Alt held");
assert!(dark_line_clips(&mut p).is_empty(), "none drawn with Alt held");
p.fx.hold(Modifiers::NONE).idle(2);
assert!(p.app().ui.color_wheel_panel.lines.is_some(), "the lines are back");
}
#[test]
fn graphics_have_one_line() {
let mut app = app("box", "saturation");
app.run("ui.colorWheel", json!({"contrastFor": "graphics"})).unwrap();
let p = Panel::new(app);
assert_eq!(lines(&p).len(), 1, "graphics have AA only");
}
const CHIP: &str = "The closest color that passes AA: click to apply it.";
/// The fix `color.contrast` answers for AA against the pinned #355F78.
fn aa_fix(p: &Panel) -> Color {
let want = p.app_mut().session.execute("color.contrast", &json!({"against": "#355f78"})).unwrap();
serde_json::from_value(want["fix"]["aa"].clone()).unwrap()
}
fn fill(p: &Panel) -> Paint {
p.app().session.proxy_paints().0
}
#[test]
fn the_chip_applies_the_fix_color_answers() {
let mut p = Panel::new(app("wheel", "hue"));
let fix = aa_fix(&p);
p.point(CHIP);
match fill(&p) {
Paint::Solid { color, .. } => assert_eq!(color, fix),
other => panic!("the fill is {other:?}"),
}
assert!(p.fx.by_label(CHIP).is_none(), "the color now passes AA: no chip");
assert!(p.fx.by_label("AA Pass").is_some());
}
/// A screen reader's click on the chip applies the color as a pointer click does.
#[test]
fn a_screen_readers_click_applies_the_fix() {
let mut p = Panel::new(app("box", "hue"));
let fix = aa_fix(&p);
p.click(CHIP);
match fill(&p) {
Paint::Solid { color, .. } => assert_eq!(color, fix),
other => panic!("the fill is {other:?}"),
}
}
#[test]
fn the_chip_offers_aaa_once_aa_passes_and_nothing_once_both_pass() {
let mut app = app("wheel", "hue");
app.run("ui.colorWheel", json!({"contrastFor": "largeText"})).unwrap();
let p = Panel::new(app);
assert!(p.fx.by_label(CHIP).is_none(), "4.49:1 meets large text AA");
assert!(p.fx.by_label("The closest color that passes AAA: click to apply it.").is_some());
let mut app = self::app("wheel", "hue");
app.run("paint.setFill", json!({"color": "#ffffff"})).unwrap();
app.run("ui.colorWheel", json!({"contrastFor": "largeText"})).unwrap();
let p = Panel::new(app);
for level in ["AA", "AAA"] {
assert!(p.fx.by_label(&format!("The closest color that passes {level}: click to apply it.")).is_none());
}
}
#[test]
fn the_panel_keeps_its_height_when_the_chip_goes() {
let height = |fill: &str| {
let mut app = app("box", "hue");
app.run("paint.setFill", json!({"color": fill})).unwrap();
Panel::new(app).fx.shown().height()
};
// #FDC96E fails AA and shows the chip; #FFFFFF passes both levels and hides it.
assert_eq!(height("#fdc96e"), height("#ffffff"));
}
/// A drag that changes the field on every frame (here the box's hue) finds the lines coarsely, and
/// in full again once it ends; a drag that leaves the field as it is keeps the full lines.
#[test]
fn a_drag_that_changes_the_field_finds_its_lines_coarsely_until_it_ends() {
let mut p = Panel::new(app("box", "hue"));
assert!(!coarse(&p));
p.app_mut().session.begin_interaction("test").unwrap();
p.fx.idle(2);
assert!(!coarse(&p), "the field is unchanged, so the full lines are kept");
p.app_mut().run("paint.setFill", json!({"color": "#6efdc9"})).unwrap();
assert!(p.app().session.in_interaction(), "the new color is part of the drag");
p.fx.idle(2);
assert!(coarse(&p), "another hue during the drag");
p.app_mut().session.commit_interaction().unwrap();
p.fx.idle(2);
assert!(!coarse(&p), "found in full once the drag ends");
}
@@ -90,8 +90,9 @@ fn ui_color_wheel_sets_and_reads_the_settings() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let settings = |view: &str, vision: bool| {
json!({
"view": view, "channel": "hue", "sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "opacity": false,
"hexField": false, "contrast": false, "contrastFor": "normalText", "contrastBackground": null, "vision": vision, "documentColors": false
"view": view, "channel": "hue", "sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary",
"opacity": false, "hexField": false, "contrast": false, "contrastFor": "normalText", "contrastBackground": null,
"vision": vision, "documentColors": false
})
};
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false));
+7 -5
View File
@@ -241,11 +241,13 @@ its variation grid; the panel draws the same grid. `ui.colorGuideOptions` opens
as `ui.color_guide` (`variation`, `steps`, `amount`). Save Colors as Swatches runs `swatch.new {colors: [...]}`
(one swatch per colour, one undo step).
Color Wheel contrast: `color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio of the active
proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given color,
with the AA and AAA results for normal text and large text and the AA result for graphics (docs/mcp.md). The Color Wheel panel's Show
Contrast row shows the same answer for the category picked under Contrast For; `ui.colorWheel {contrast?, contrastFor?,
contrastBackground?}` sets the row, its category and a pinned background, and `ui.inspect` reports them as
Color Wheel contrast: `color.contrast {color?, against?, opacity?, for?}` answers the WCAG 2 contrast ratio of the
active proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given
color, with the AA and AAA results for normal text and large text and the AA result for graphics, and as `fix` the
closest color of the same hue that meets each level of the category `for` names (docs/mcp.md). The Color Wheel panel's
Show Contrast row shows the same answer for the category picked under Contrast For, with a chip of the fix color;
`ui.colorWheel {contrast?, contrastFor?, contrastBackground?}` sets the row, its category and a pinned background, and
`ui.inspect` reports them as
`ui.color_wheel`.
Color Guide Limit to Library: `ui.colorGuideLimit {library}` (a swatch library id or name, `"document"` for the
+30 -9
View File
@@ -698,12 +698,19 @@ with a slider and a percent field sets the opacity of the fill row (`paint.setFi
(`paint.setStroke {opacity}`), the selected gradient stop or the selected freeform point (the first stop or point
when none is selected), and `false` hides the row. The row is gray with nothing selected, for an object selected in
a symbol instance, and when the fill or stroke row it would set is on type characters or missing.
`{"contrast": true}` shows Show Contrast's row under the wheel or the box, `contrastFor` (`normalText`, `largeText` or
`graphics`, which has AA only) picks the category its results are for, and `contrastBackground` (a color, or `null` for
the color behind the selection) pins the background it measures against, as `color.contrast` below answers it.
Keys left out keep their values, and so do keys given as `null`, except `contrastBackground`. Params that are not an object, another key or a value off
the list return an error and change nothing. `{"contrast": true}` shows Show Contrast's row under the wheel or the
box, `contrastFor` (`normalText`, `largeText` or `graphics`, which has AA only) picks the category its results are for, and
`contrastBackground` (a color, or `null` for the color behind the selection) pins the background it measures against,
as `color.contrast` below answers it. With the row shown, the wheel's square and the box's field draw lines where the
color picked there meets AA (solid) and AAA (dashed) for the category, also when the active fill or stroke is None
or a pattern and the row shows a dash. The lines are hidden while Alt is held, since a pick then goes to the other
proxy. The row's first chip shows the background the ratio is measured against, so a pinned 100 % K shows as black
with a rich black Appearance of Black. When the color fails a level and
`color.contrast`'s `fix` has a color for the first level it fails, a chip at the end of the row shows that color; a
click, or Enter while the chip has the focus, applies it. When that fix is `null`, the row shows no chip.
`{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel
or the box. Keys left out keep their values. Params that are not an object, another key or a value off
the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity,
or the box. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, opacity,
hexField, contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences.
`ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or
@@ -1256,7 +1263,7 @@ panel's Limit to Library does (`ui.colorGuideLimit`); Recolor Artwork's `limitTo
that is not a string, such as `5`, names no library and gets the same error as an unknown name; `null` or `""` sets no
limit.
`color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio
`color.contrast {color?, against?, opacity?, for?}` answers the WCAG 2 contrast ratio
([definition](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio)) of a color against a background, from 1 to 21, and
whether it meets AA and AAA for normal text (4.5:1 and 7:1), large text (3:1 and 4.5:1) and graphics (3:1, AA only):
`{ratio, against, normalText: {aa, aaa}, largeText: {aa, aaa}, graphics: {aa}}`. The results compare the unrounded
@@ -1280,15 +1287,29 @@ is drawn); a picked object of a dynamic symbol instance hides only itself, and t
These are errors: `"below"` with nothing selected; a "?" proxy (hidden objects count there, as in the Color panel);
selected objects that draw one color with different blend modes, or at different opacities without `opacity` (with
`"below"`, also in different groups or layers that are translucent, have a blend mode or isolate their blending, or
with a translucent or blending row over different shown rows below it), where hidden objects do not count, and the
with a translucent or blending row over different shown rows below it, or over a shown row that blends in objects
that differ in isolating their blending), where hidden objects do not count, and the
error names `opacity` when giving it settles the difference; a proxy of None, a pattern or a hidden row without `color`; and without `color`, a
proxy's object drawn through an opacity mask that is not disabled, its own or that of a group, layer or instance
around it, since the mask sets how much of the color shows at each point. `against` in the
around it, since the mask sets how much of the color shows at each point; and with `"below"`, a color drawn with a
blend mode other than Normal (its row's, the object's, or a group's or layer's) while the art read behind it (a 1 pt
square at the center, as each level reads it) is not one color, since the mode mixes the color with each part of
that art in its own way. `against` in the
answer is the background as a working RGB `#rrggbb`, the form `against` takes; the sampled background is rounded to 8
bits, so giving it back answers the same ratio, except when `opacity` is omitted and a group or layer around the
object is translucent, has a blend mode or isolates its blending, or the measured row is translucent or blends over
rows below it: there `"below"` reads the art below each such level, and a given background stands for that art.
Headless MCP answers it too.
Headless MCP answers it too. The answer also has `for` (the category `for` names: `normalText`, the default,
`largeText` or `graphics`) and `fix: {aa, aaa}` (no `aaa` for graphics): for each level of that category, the closest
color that meets it when drawn the same way, in the model of the measured color, as the Color Wheel stores a pick. The
closest color also meets the level with the color, the background, the art below each group or layer it is drawn
through, the opacities, and the color and alpha each level gives rounded to 8 bits per channel. The
search keeps the color's [OKLCH](https://bottosson.github.io/posts/oklab/) hue, raises or lowers its lightness,
whichever takes the smaller step, and lowers its chroma where sRGB cannot show it. It tests 16 lightnesses on each
side and narrows down the first that passes, so where the passing lightnesses on a side fall apart in more than one
stretch (under some blend modes), a nearer passing color between two tested lightnesses can be missed. A level is
`null` when the color already meets it, or when no lightness of the hue does (white on `#355f78` is 6.87:1, so no
color meets 7:1 there).
Color Themes (local only: no online service) keeps five-colour themes in the preferences. `colorTheme.save
{colors: [...]}` saves up to five colours as they are, `colorTheme.save {color, rule}` saves the five-colour theme a
+1
View File
@@ -2150,6 +2150,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Color Wheel panel (part of #978):** Window › Color Wheel shows the Fill and Stroke proxy beside a hue ring around a square with saturation across and brightness up. It edits what the Color panel's sliders edit (the active proxy's color, the selected gradient stop or freeform point) through the same paint commands, and a drag is one undo step. Alt paints the other proxy, and Shift steps the ring by 45°. A pick goes from display sRGB into the working RGB space; an RGB, CMYK or Lab color keeps its model, and a Gray color or a tint of a global swatch becomes a process color in the document's color mode. A click gives the ring or the square the keyboard focus, and the arrow keys then step the color; both report their names and values to screen readers, and the Color Picker's color field takes the same keys. The panel menu's Box View puts a box in the wheel's place: a color field with a channel strip at its right for Hue, Saturation, Brightness, Red, Green or Blue (Box Channel), on the Color Picker's axes, kept with the preferences (`ui.colorWheel`); the strip and the Color Picker's channel slider take the arrow keys after a click. Show Out-of-Gamut Colors grays out the parts of the square and the box's field whose colors the CMYK space cannot print, by the out-of-gamut warning's test on a 16 by 16 grid (`ui.colorWheel {gamut}`). The panel menu's Show Harmony marks the other colors of a harmony rule (Harmony Rule) on the ring; the markers follow the current color, and a click on a marker applies its color (`ui.colorWheel {harmony, harmonyRule}`). Scores and estimates are unchanged.
VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill row (`paint.setFill {opacity}`) or the stroke row (`paint.setStroke {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged.
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents.
The panel menu's Show Contrast (VectorCraft's own) adds a row with the [WCAG 2 contrast ratio](https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio) of the color, at the opacity it is drawn with, against the color drawn behind the selection (locked art, opacity and blending included) or a pinned color, cut off at two decimals, with the AA and AAA results for normal text, large text or graphics (AA only for graphics). `color.contrast` answers the same for agents. With the row shown, the wheel's square and the box's field draw the AA and AAA lines, and a chip in the row offers the closest color of the same hue that passes, which `color.contrast` answers as `fix`.
- **Colour:** a Color Picker (colour field, H/S/B/R/G/B channel slider, HSB/RGB/Lab/CMYK fields, hex, web-only snapping, out-of-gamut correction); the Color panel shows a selected colour in its own model and, with nothing selected, the new-art defaults in the mode picked last, which it keeps between sessions; Alt-click paints the other proxy; proxies look through groups and show "?" for mixed paint; Invert, Complement, Apply Last Color (`,`) and Apply Last Gradient (`.`) keep the colour model; every paint command feeds the recent colours. The Color Guide has 21 harmony rules, Steps and Variation options and Limit to Library. Adjust Color Balance (its Global mode shifts tints) and Saturate preview live; Edit Colors and Recolor also reach meshes, images and patterns. Recolor Artwork has colour reduction, five recolour methods, presets, Limit to Library, a colour-wheel Edit tab and Edit Color Group; a local Color Themes panel saves five-colour themes. Fill/Stroke chips open swatch and mixer popovers (the Properties panel has the Control bar's Fill and Stroke chips, Stroke link and weight spinner, with nothing selected too), panels have Illustrator's Window menu keys (Align Shift+F7, Transform Shift+F8, Pathfinder Cmd+Shift+F9, Layers F7, Character Cmd+T…; every panel can be given one in Edit › Keyboard Shortcuts), and Eyedropper Options pick up and apply chosen attributes (Alt and Shift+Alt, image pixels). An ICC CMYK profile converts straight into the RGB working space (not through sRGB, so a wider space such as Wide Gamut RGB keeps colours sRGB can't hold) with the colour settings' black-point compensation, on the canvas and in RGB exports alike (the built-in Generic CMYK compensates both ways, so RGB black separated to a rich black displays as black again). Fills and strokes can overprint (Attributes panel, Overprint Black options), and CMYK documents blend in inks on screen, in PDF and when flattening. Document Color Mode converts the art, symbols, pattern tiles and swatches through the colour settings: Gray stays Gray, RGB grays separate into light grays in cyan, magenta and yellow only, darker four-color grays and a rich black, or go on the black plate only with `grays: "black"` (also for `document.open {colorMode}`).
**Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged.