From cc5d3b5537f723cb7885bd8f617d0ec38bf80e44 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:20:49 -0800 Subject: [PATCH 01/13] Color Wheel: the box and the wheel mark the contrast lines and offer the closest passing color With Show Contrast on, the wheel's square and the box's field draw where the color picked there meets AA (solid) and AAA (dashed) for the chosen category, each as a white line over a black one. The field is sampled on a 33 by 33 grid and each crossing is placed by bisection, so a line can run across the field or up it; a passing band narrower than the samples is found by looking for the highest ratio around a failing sample higher than its neighbors. When the color fails AA, or meets AA and fails AAA, a chip at the end of the contrast row shows the closest color that passes that level, and a click applies it. The chip keeps its space while hidden, so the row does not move as a drag crosses a line. Screen readers read it as a button. color.contrast takes `for` (normalText, largeText or graphics) and answers `for` and `fix: {aa, aaa}` (no aaa for graphics): for each level, the closest color that meets it when drawn the same way (blend modes, opacity, translucent groups and layers, the stain of a picked symbol object), in the model of the measured color, or null when the color already meets it or no lightness of its hue does. The search keeps the OKLCH hue, raises or lowers the lightness, whichever takes the smaller step, lowers the chroma where sRGB cannot show it, and tests at most 167 colors. Part of #978 --- crates/color/src/wcag.rs | 154 ++++++++ crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/colorcmds.rs | 234 +++++++++--- crates/engine/src/tests/colorcontrast.rs | 84 +++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 336 ++++++++++++++++-- .../tests_color_wheel_contrast_lines.rs | 167 +++++++++ docs/control-protocol.md | 11 +- docs/mcp.md | 14 +- docs/target-app-parity.md | 2 +- 38 files changed, 946 insertions(+), 87 deletions(-) create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index ef42eec957..d63e07c952 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -2,6 +2,7 @@ //! the relative luminance of display sRGB with the 0.04045 threshold, the ratio //! (L1 + 0.05) / (L2 + 0.05) from 1 to 21, and the minimum ratios of success criteria 1.4.3 //! (Contrast (Minimum), AA), 1.4.6 (Contrast (Enhanced), AAA) and 1.4.11 (Non-text Contrast, AA). +//! [`closest_passing`] finds the color of the same hue nearest in lightness that meets a minimum. /// What the content in front is, which sets the ratio it needs. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -87,6 +88,99 @@ 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; +/// The halvings [`closest_passing`] makes of the chroma when sRGB cannot show it. +const CHROMA_STEPS: usize = 24; + +/// The display sRGB of OKLCH lightness `l`, chroma `c` and the hue whose sine and cosine are `sc`, +/// with the chroma lowered until the color fits in sRGB. +fn oklch_in_gamut(l: f64, c: f64, (sin, cos): (f64, f64)) -> [f32; 3] { + let at = |c: f64| crate::libraries::oklab_to_srgb(l, c * cos, c * sin); + let fits = |rgb: &[f64; 3]| rgb.iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(v)); + let mut rgb = at(c); + if !fits(&rgb) { + let (mut lo, mut hi) = (0.0, c); + for _ in 0..CHROMA_STEPS { + let mid = (lo + hi) / 2.0; + if fits(&at(mid)) { lo = mid } else { hi = mid } + } + rgb = at(lo); + } + rgb.map(|v| v.clamp(0.0, 1.0) as f32) +} + +/// Where between `lo` and `hi` `f` is highest, by golden-section search, which finds the top of a +/// single peak between them. `f` is called 34 times. +pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { + let g = (5f64.sqrt() - 1.0) / 2.0; + let (mut a, mut b) = (hi - g * (hi - lo), lo + g * (hi - lo)); + let (mut fa, mut fb) = (f(a), f(b)); + for _ in 0..PEAK_STEPS { + if fa < fb { + (lo, a, fa) = (a, b, fb); + b = lo + g * (hi - lo); + fb = f(b); + } else { + (hi, b, fb) = (b, a, fa); + a = hi - g * (hi - lo); + fa = f(a); + } + } + if fa > fb { a } else { b } +} + +/// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue +/// () with the lightness raised or lowered, whichever +/// takes the smaller step, and the chroma lowered where sRGB cannot show it. 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. +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, a, b] = crate::libraries::srgb_to_oklab(srgb); + let (c, sc) = (a.hypot(b), b.atan2(a).sin_cos()); + let mut best: Option<(f64, [f32; 3])> = None; + for end in [1.0, 0.0] { + let at = |t: f64| oklch_in_gamut(l + (end - l) * t, c, sc); + let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64; + let ratios: Vec = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect(); + // `lo` fails and `hi` passes, the step before the first sample that passes. + let found = match ratios.iter().position(|r| *r >= minimum) { + Some(i) => Some((step(i), step(i + 1))), + None => { + // Every sample fails: look for a higher ratio around the highest one. + let top = ratios.iter().enumerate().fold((0, f64::NEG_INFINITY), |m, (i, r)| if *r > m.1 { (i, *r) } else { m }).0; + let (lo, hi) = (step(top), step((top + 2).min(LIGHTNESS_SAMPLES))); + let peak = peak_between(lo, hi, &|t| ratio(at(t))); + passes(at(peak)).then_some((lo, peak)) + } + }; + let Some((mut lo, mut hi)) = found else { continue }; + for _ in 0..LIGHTNESS_STEPS { + let mid = (lo + hi) / 2.0; + if passes(at(mid)) { hi = mid } else { lo = mid } + } + let step = (end - l).abs() * hi; + if best.is_none_or(|(d, _)| step < d) { + best = Some((step, at(hi))); + } + } + best.map(|(_, c)| c) +} + #[cfg(test)] mod tests { use super::*; @@ -137,6 +231,66 @@ 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}"); + } + + #[test] + fn a_passing_color_is_its_own_closest_and_nothing_passing_is_none() { + let white = [1.0; 3]; + assert_eq!(closest_passing([0.0; 3], 7.0, &|c| contrast_ratio(c, white)), Some([0.0; 3])); + assert_eq!(closest_passing(hex("808080"), 4.5, &|_| 1.0), None); + // Mid gray: AAA for normal text needs 7:1, which neither white nor black reaches. + let mid = hex("777777"); + assert_eq!(closest_passing(mid, 7.0, &|c| contrast_ratio(c, mid)), None); + assert_eq!(closest_passing([f32::NAN; 3], 4.5, &|c| contrast_ratio(c, white)).map(|c| c.map(|v| v.is_finite())), Some([true; 3])); + } + #[test] fn half_opaque_black_over_white_is_mid_gray() { assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e2bc50cdc5..2859e8751e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -821,6 +821,7 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +pub use colorcmds::{Backdrop, contrast_measure}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index b1817784b6..b3f0a4e2fb 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point; 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`)} 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 background; the modes inside an object, group or layer that isolates its blending do not apply; Normal for a given `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), 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; 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`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} 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 background; the modes inside an object, group or layer that isolates its blending do not apply; Normal for a given `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), 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; null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), @@ -1000,7 +1000,160 @@ 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 blend modes, its opacity and the translucent groups and layers around 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 blend modes the color is drawn with, innermost first. + modes: Vec, + /// The given opacity, which takes the place of the drawn ones. + opacity: Option, + /// Each translucent group or layer around the object, from the outermost in, with the color + /// outside it. + levels: Vec<(f32, [f32; 3])>, + /// The opacity the color is drawn with inside its object. + drawn: f32, + /// The color and amount a fill stains the picked object of a dynamic symbol instance with. + stain: Option<(Color, f32)>, +} + +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, + } + } + + /// Display sRGB `shown`, drawn as the measured color is drawn, over the background. + pub fn front(&self, shown: [f32; 3]) -> [f32; 3] { + // Each blend mode, innermost first, replaces the color with its blend with the background + // where it covers it. + let blended = self.modes.iter().fold(shown, |c, m| vectorcraft_color::blend::blend_rgb(*m, self.against, c)); + match self.opacity { + Some(o) => wcag::over(blended, o, self.against), + None => { + // A translucent group or layer draws the art inside it, the art behind the object + // included, over what is outside it: the color is drawn opaque through each such + // level from the outermost in, over the color read with that level hidden, then at + // the object's own opacity over the background. + let x = self.levels.iter().fold(blended, |x, (a, outside)| wcag::over(x, *a, *outside)); + wcag::over(x, self.drawn, 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) + } + + /// 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). None when `color` already meets it, or when no lightness of its hue does. +fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64, rich_black: bool) -> Option { + let cms = vectorcraft_color::cms::active(); + let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c)); + let ratio = |srgb: [f32; 3]| backdrop.ratio(drawn(&in_model_of(&cms, srgb, color))); + if backdrop.ratio(drawn(color)) >= minimum { + return None; + } + let fix = wcag::closest_passing(shown_rgb(&cms, rich_black, color), minimum, &ratio)?; + Some(in_model_of(&cms, fix, color)) +} + fn contrast(s: &mut Session, p: &Value) -> Result { + contrast_measure(s, p).map(|(answer, _)| answer) +} + +/// `color.contrast`'s answer for params `p`, and what it measured the color against. +pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { + const C: &str = "color.contrast"; + let category = match p.get("for") { + None | Some(Value::Null) => Category::NormalText, + Some(v) => { + let key = "for"; + let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect(); + v.as_str().and_then(Category::parse).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", ids.join(", "))))? + } + }; + let (color, backdrop) = contrast_backdrop(s, p)?; + let rich_black = s.prefs.black_on_screen == "rich"; + let ratio = backdrop.ratio(shown_rgb(&vectorcraft_color::cms::active(), rich_black, &backdrop.drawn_color(&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, rich_black) { + 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)> { const C: &str = "color.contrast"; check_numbers(p, &["opacity"], C)?; let opacity = match p.get("opacity").and_then(Value::as_f64) { @@ -1012,16 +1165,14 @@ fn contrast(s: &mut Session, p: &Value) -> Result { None => None, }; let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below")); + let given = p.get("color").is_some_and(|v| !v.is_null()); let (color, drawn, mode, around) = 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`"))?, 1.0, vec![], vec![]), }; 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); // 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) { @@ -1037,43 +1188,19 @@ fn contrast(s: &mut Session, p: &Value) -> Result { (shown, to_8bit(cms.srgb_to_rgb(shown))) } }; - // Each blend mode, innermost first, replaces the color with its blend with the background - // where it covers it. - let blended = mode.iter().fold(shown(&color), |c, m| vectorcraft_color::blend::blend_rgb(*m, against, c)); - let front = match opacity { - Some(o) => wcag::over(blended, o, against), - None => { - // A translucent group or layer draws the art inside it, the art behind the object - // included, over what is outside it: the color is drawn opaque through each such level - // from the outermost in, over the color read with that level hidden, then at the - // object's own opacity over the background. - let mut x = blended; - for (a, level) in around.iter().rev().filter(|(a, _)| *a < 1.0) { - let outside = match level.filter(|_| below) { - Some(id) => color_below(s, rich_black, Some(id)).map_err(|e| bad(C, e))?, - None => against, - }; - x = wcag::over(x, *a, outside); - } - wcag::over(x, drawn, against) + // Each translucent group or layer, from the outermost in, with the color read with it hidden. + let mut levels = vec![]; + if opacity.is_none() { + for (a, level) in around.iter().rev().filter(|(a, _)| *a < 1.0) { + let outside = match level.filter(|_| below) { + Some(id) => color_below(s, rich_black, Some(id)).map_err(|e| bad(C, e))?, + None => against, + }; + levels.push((*a, outside)); } - }; - 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 }), - } - }; - 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 stain = if given { None } else { stain_of(s) }; + Ok((color, Backdrop { against, written, modes: mode, opacity, levels, drawn, stain })) } /// The opacity of each object around the proxy's object that draws it, innermost first, with the @@ -1134,7 +1261,7 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re } 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), layer, mode, around)), + Paint::Solid { color, .. } => Ok((color, layer, mode, around)), 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); @@ -1186,19 +1313,18 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s Ok((opacity, drawn_modes(levels.collect()), around)) } -/// `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. +fn stain_of(s: &Session) -> Option<(Color, f32)> { + let (fill, stroke) = s.proxy_paints(); + if !matches!(if s.fill_active { fill } else { stroke }, Paint::Solid { .. }) { + 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 blend modes that apply to a color drawn through `levels` (each a blend mode and whether that diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 398dc24b88..20a8b9bcda 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -379,6 +379,14 @@ 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.51).contains(&got), "{fix:?} draws {drawn:?}: {got}"); } #[test] @@ -441,3 +449,79 @@ 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.51).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.51).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}"); +} + +#[test] +fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() { + let mut s = Session::new(); + let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap(); + assert_eq!(r["fix"], json!({"aa": null, "aaa": null})); + let g = s.execute("color.contrast", &json!({"color": "#cccccc", "against": "#ffffff", "for": "graphics"})).unwrap(); + assert_eq!(g["for"], "graphics"); + let fix = g["fix"].as_object().unwrap(); + assert_eq!(fix.keys().collect::>(), ["aa"], "{g}"); + let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap(); + assert!((3.0..3.01).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.01).contains(&ratio(&back)), "{back}"); +} + +#[test] +fn for_takes_only_the_three_categories() { + let mut s = Session::new(); + for bad in [json!("NormalText"), json!("aa"), json!(1), json!(true)] { + let e = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "for": bad})).unwrap_err().to_string(); + assert!(e.contains("`for` must be one of normalText, largeText, graphics"), "{e}"); + } +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 359972b26c..b78684086f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1477,6 +1477,7 @@ font-technology Variable Променливи Fail Не покрива WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимален контраст по WCAG 2.2: нормален текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), голям текст AA 3:1 и AAA 4.5:1, графики и контроли AA 3:1 (1.4.11). The background is read at the center of the selection. Фонът се отчита в центъра на селекцията. + The closest color that passes {level}: click to apply it. Най-близкият цвят, който покрива {level}: щракнете, за да го приложите. Graphics Processor Графичен процесор Graphics: {adapter} Графика: {adapter} Gravity Гравитация diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index a9d9bfe3c2..52513dddfb 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1968,6 +1968,7 @@ digits Malayalam Malajalam Fail Ne prolazi WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalni kontrast po WCAG 2.2: normalni tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), veliki tekst AA 3:1 i AAA 4.5:1, grafike i kontrole AA 3:1 (1.4.11). The background is read at the center of the selection. Pozadina se očitava u sredini odabira. + The closest color that passes {level}: click to apply it. Najbliža boja koja zadovoljava {level}: kliknite da je primijenite. Local Libraries Lokalne biblioteke Add Content Dodaj sadržaj Click to apply to the selected type Kliknite da primijenite na odabrani tekst diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 47559f16c1..7a64590644 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1992,6 +1992,7 @@ digits Malayalam Malaiàlam Fail No supera WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrast mínim de les WCAG 2.2: text normal AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), text gran AA 3:1 i AAA 4.5:1, gràfics i controls AA 3:1 (1.4.11). The background is read at the center of the selection. El fons es llegeix al centre de la selecció. + The closest color that passes {level}: click to apply it. El color més proper que compleix {level}: feu clic per aplicar-lo. Graphics Processor Processador gràfic Graphics: {adapter} Gràfics: {adapter} Gravity Gravetat diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 517c4732e4..e6c2295c24 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2041,6 +2041,7 @@ digits Malayalam Malajálamské Fail Nevyhovuje WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimální kontrast podle WCAG 2.2: normální text AA 4.5:1 (1.4.3) a AAA 7:1 (1.4.6), velký text AA 3:1 a AAA 4.5:1, grafika a ovládací prvky AA 3:1 (1.4.11). The background is read at the center of the selection. Pozadí se čte uprostřed výběru. + The closest color that passes {level}: click to apply it. Nejbližší barva, která splňuje {level}: kliknutím ji použijete. Local Libraries Místní knihovny Add Content Přidat obsah Click to apply to the selected type Kliknutím použijete na vybraný text diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 3ab1d7eb08..c38325c433 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4520,6 +4520,7 @@ digits Malayalam Malayalam Fail Ikke bestået WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindstekontrast efter WCAG 2.2: normal tekst AA 4.5:1 (1.4.3) og AAA 7:1 (1.4.6), stor tekst AA 3:1 og AAA 4.5:1, grafik og kontrolelementer AA 3:1 (1.4.11). The background is read at the center of the selection. Baggrunden aflæses i midten af markeringen. + The closest color that passes {level}: click to apply it. Den nærmeste farve, der består {level}: klik for at anvende den. Local Libraries Lokale biblioteker Add Content Tilføj indhold Click to apply to the selected type Klik for at anvende på den markerede tekst diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index d9f7612aa8..8e3c8847e4 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1527,6 +1527,7 @@ file-filter Templates Vorlagen Fail Nicht bestanden WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Mindestkontrast nach WCAG 2.2: normaler Text AA 4.5:1 (1.4.3) und AAA 7:1 (1.4.6), großer Text AA 3:1 und AAA 4.5:1, Grafiken und Bedienelemente AA 3:1 (1.4.11). The background is read at the center of the selection. Der Hintergrund wird in der Mitte der Auswahl gemessen. + The closest color that passes {level}: click to apply it. Die nächste Farbe, die {level} besteht: Klicken Sie, um sie anzuwenden. Graphics Processor Grafikprozessor Graphics: {adapter} Grafik: {adapter} Gravity Schwerkraft diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f476aa9b33..9b7b485a6f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1459,6 +1459,7 @@ font-technology Variable Μεταβλητές Fail Αποτυχία WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Ελάχιστη αντίθεση κατά WCAG 2.2: κανονικό κείμενο AA 4.5:1 (1.4.3) και AAA 7:1 (1.4.6), μεγάλο κείμενο AA 3:1 και AAA 4.5:1, γραφικά και στοιχεία ελέγχου AA 3:1 (1.4.11). The background is read at the center of the selection. Το φόντο διαβάζεται στο κέντρο της επιλογής. + The closest color that passes {level}: click to apply it. Το πλησιέστερο χρώμα που περνά το {level}: κάντε κλικ για να το εφαρμόσετε. Graphics Processor Επεξεργαστής γραφικών Graphics: {adapter} Γραφικά: {adapter} Gravity Βαρύτητα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c0ced0baaa..78858b8cd4 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1542,6 +1542,7 @@ font-technology Variable Variables Fail No cumple WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo de WCAG 2.2: texto normal AA 4.5:1 (1.4.3) y AAA 7:1 (1.4.6), texto grande AA 3:1 y AAA 4.5:1, gráficos y controles AA 3:1 (1.4.11). The background is read at the center of the selection. El fondo se lee en el centro de la selección. + The closest color that passes {level}: click to apply it. El color más cercano que cumple {level}: haga clic para aplicarlo. Graphics Processor Procesador gráfico Graphics: {adapter} Gráficos: {adapter} Gravity Gravedad diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 018f984732..0f0a867295 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2002,6 +2002,7 @@ digits Malayalam Malajalam Fail Ei läpäise WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2:n vähimmäiskontrastit: tavallinen teksti AA 4.5:1 (1.4.3) ja AAA 7:1 (1.4.6), suuri teksti AA 3:1 ja AAA 4.5:1, grafiikka ja säätimet AA 3:1 (1.4.11). The background is read at the center of the selection. Tausta luetaan valinnan keskeltä. + The closest color that passes {level}: click to apply it. Lähin väri, joka läpäisee tason {level}: käytä sitä napsauttamalla. Local Libraries Paikalliset kirjastot Add Content Lisää sisältöä Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index eaac8d95b1..9cf5367489 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1532,6 +1532,7 @@ font-technology Variable Variables Fail Échec WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste minimal WCAG 2.2 : texte normal AA 4.5:1 (1.4.3) et AAA 7:1 (1.4.6), grand texte AA 3:1 et AAA 4.5:1, graphiques et commandes AA 3:1 (1.4.11). The background is read at the center of the selection. L’arrière-plan est lu au centre de la sélection. + The closest color that passes {level}: click to apply it. La couleur la plus proche qui satisfait {level} : cliquez pour l’appliquer. Graphics Processor Processeur graphique Graphics: {adapter} Carte graphique : {adapter} Gravity Gravité diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index ee71f52157..54f5a79610 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1616,6 +1616,7 @@ Fail નાપાસ WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 લઘુત્તમ કોન્ટ્રાસ્ટ: સામાન્ય ટેક્સ્ટ AA 4.5:1 (1.4.3) અને AAA 7:1 (1.4.6), મોટું ટેક્સ્ટ AA 3:1 અને AAA 4.5:1, ગ્રાફિક્સ અને નિયંત્રણો AA 3:1 (1.4.11). The background is read at the center of the selection. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે. + The closest color that passes {level}: click to apply it. {level} પાસ કરતો સૌથી નજીકનો રંગ: તેને લાગુ કરવા ક્લિક કરો. Graphics Processor ગ્રાફિક્સ પ્રોસેસર Graphics: {adapter} ગ્રાફિક્સ: {adapter} Gravity ગ્રેવિટી diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 6b62bda40f..cffebdc9b7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2208,6 +2208,7 @@ antiAlias Sharp शार्प Fail फ़ेल WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 न्यूनतम कंट्रास्ट: सामान्य टेक्स्ट AA 4.5:1 (1.4.3) और AAA 7:1 (1.4.6), बड़ा टेक्स्ट AA 3:1 और AAA 4.5:1, ग्राफ़िक्स और कंट्रोल AA 3:1 (1.4.11)। The background is read at the center of the selection. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है। + The closest color that passes {level}: click to apply it. {level} पास करने वाला सबसे नज़दीकी रंग: लागू करने के लिए क्लिक करें। Graphics Processor ग्राफिक्स प्रोसेसर Graphics: {adapter} ग्राफिक्स: {adapter} Gravity ग्रेविटी diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1d24dba789..87b38dc4aa 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1925,6 +1925,7 @@ file-filter Templates Sablonok Fail Nem felel meg WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 szerinti minimális kontraszt: normál szöveg AA 4.5:1 (1.4.3) és AAA 7:1 (1.4.6), nagy szöveg AA 3:1 és AAA 4.5:1, grafikák és vezérlők AA 3:1 (1.4.11). The background is read at the center of the selection. A háttér színét a kijelölés közepén olvassa le a program. + The closest color that passes {level}: click to apply it. A legközelebbi szín, amely megfelel a(z) {level} szintnek: kattintson az alkalmazásához. Graphics Processor Grafikus processzor Graphics: {adapter} Grafika: {adapter} Gravity Gravitáció diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index af89105e27..b8e9a88359 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1804,6 +1804,7 @@ digits Malayalam Malayalam Fail Gagal WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Kontras minimum WCAG 2.2: teks normal AA 4.5:1 (1.4.3) dan AAA 7:1 (1.4.6), teks besar AA 3:1 dan AAA 4.5:1, grafis dan kontrol AA 3:1 (1.4.11). The background is read at the center of the selection. Latar dibaca di tengah seleksi. + The closest color that passes {level}: click to apply it. Warna terdekat yang lolos {level}: klik untuk menerapkannya. Local Libraries Pustaka lokal Add Content Tambahkan konten Click to apply to the selected type Klik untuk menerapkan ke teks terpilih diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a902541e0b..52e3aeccb7 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1561,6 +1561,7 @@ file-filter Templates Modelli Fail Non superato WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contrasto minimo WCAG 2.2: testo normale AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), testo grande AA 3:1 e AAA 4.5:1, grafica e controlli AA 3:1 (1.4.11). The background is read at the center of the selection. Lo sfondo viene letto al centro della selezione. + The closest color that passes {level}: click to apply it. Il colore più vicino che soddisfa {level}: fai clic per applicarlo. Graphics Processor Processore grafico Graphics: {adapter} Scheda grafica: {adapter} Gravity Gravità diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index f647393ade..0187ebacc2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3987,6 +3987,7 @@ file-filter Templates テンプレート Fail 不合格 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 の最小コントラスト:通常のテキスト AA 4.5:1 (1.4.3) と AAA 7:1 (1.4.6)、大きなテキスト AA 3:1 と AAA 4.5:1、グラフィックとコントロール AA 3:1 (1.4.11)。 The background is read at the center of the selection. 背景は選択範囲の中央で読み取ります。 + The closest color that passes {level}: click to apply it. {level} を満たす最も近いカラー:クリックで適用します。 Greek & Cyrillic ギリシャ文字とキリル文字 Hex by Column 六角形 (列) Hex by Row 六角形 (行) diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8041133095..516a00d1ec 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3869,6 +3869,7 @@ digits Malayalam მალაიალამური Fail არ აკმაყოფილებს WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2-ის მინიმალური კონტრასტი: ჩვეულებრივი ტექსტი AA 4.5:1 (1.4.3) და AAA 7:1 (1.4.6), დიდი ტექსტი AA 3:1 და AAA 4.5:1, გრაფიკა და მართვის ელემენტები AA 3:1 (1.4.11). The background is read at the center of the selection. ფონი იკითხება მონიშნულის ცენტრში. + The closest color that passes {level}: click to apply it. უახლოესი ფერი, რომელიც აკმაყოფილებს {level}-ს: დააწკაპუნეთ მის გამოსაყენებლად. Local Libraries ლოკალური ბიბლიოთეკები Add Content შიგთავსის დამატება Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9e890e2580..9402411a0d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3975,6 +3975,7 @@ file-filter Templates 템플릿 Fail 실패 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 최소 대비: 일반 텍스트 AA 4.5:1 (1.4.3) 및 AAA 7:1 (1.4.6), 큰 텍스트 AA 3:1 및 AAA 4.5:1, 그래픽과 컨트롤 AA 3:1 (1.4.11). The background is read at the center of the selection. 배경은 선택 영역의 중앙에서 읽습니다. + The closest color that passes {level}: click to apply it. {level}을(를) 충족하는 가장 가까운 색상: 클릭하여 적용합니다. Greek & Cyrillic 그리스어 및 키릴 문자 Hex by Column 열 기준 육각형 Hex by Row 행 기준 육각형 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b63a05e26f..06559f4d4f 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2414,6 +2414,7 @@ digits Malayalam Malayalam Fail Niet geslaagd WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimumcontrast volgens WCAG 2.2: normale tekst AA 4.5:1 (1.4.3) en AAA 7:1 (1.4.6), grote tekst AA 3:1 en AAA 4.5:1, illustraties en bedieningselementen AA 3:1 (1.4.11). The background is read at the center of the selection. De achtergrond wordt in het midden van de selectie gemeten. + The closest color that passes {level}: click to apply it. De dichtstbijzijnde kleur die aan {level} voldoet: klik om deze toe te passen. Local Libraries Lokale bibliotheken Add Content Inhoud toevoegen Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index aeaa4a7bac..e703f9f206 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1959,6 +1959,7 @@ digits Malayalam Malajalam Fail Nie spełnia WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minimalny kontrast według WCAG 2.2: zwykły tekst AA 4.5:1 (1.4.3) i AAA 7:1 (1.4.6), duży tekst AA 3:1 i AAA 4.5:1, grafika i elementy sterujące AA 3:1 (1.4.11). The background is read at the center of the selection. Tło jest odczytywane na środku zaznaczenia. + The closest color that passes {level}: click to apply it. Najbliższy kolor spełniający {level}: kliknij, aby go zastosować. Local Libraries Biblioteki lokalne Add Content Dodaj zawartość Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 91820ab433..2a30fdb4d0 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3684,6 +3684,7 @@ font-technology Variable Variáveis Fail Reprovado WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Contraste mínimo da WCAG 2.2: texto normal AA 4.5:1 (1.4.3) e AAA 7:1 (1.4.6), texto grande AA 3:1 e AAA 4.5:1, gráficos e controles AA 3:1 (1.4.11). The background is read at the center of the selection. O fundo é lido no centro da seleção. + The closest color that passes {level}: click to apply it. A cor mais próxima que atende a {level}: clique para aplicá-la. Highlight Rows Destacar linhas Highlight Variable Destacar variável Sort Variables Ordenar variáveis diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 76a70a4fb6..7dd8cb1654 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1552,6 +1552,7 @@ file-filter Templates Шаблоны Fail Не соответствует WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Минимальный контраст по WCAG 2.2: обычный текст AA 4.5:1 (1.4.3) и AAA 7:1 (1.4.6), крупный текст AA 3:1 и AAA 4.5:1, графика и элементы управления AA 3:1 (1.4.11). The background is read at the center of the selection. Фон определяется в центре выделения. + The closest color that passes {level}: click to apply it. Ближайший цвет, соответствующий {level}: щёлкните, чтобы применить его. Graphics Processor Графический процессор Graphics: {adapter} Графика: {adapter} Gravity Гравитация diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 37292b64ee..6e47263e1c 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1495,6 +1495,7 @@ font-technology Variable Variabla Fail Underkänd WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Minsta kontrast enligt WCAG 2.2: normal text AA 4.5:1 (1.4.3) och AAA 7:1 (1.4.6), stor text AA 3:1 och AAA 4.5:1, grafik och kontroller AA 3:1 (1.4.11). The background is read at the center of the selection. Bakgrunden läses i mitten av markeringen. + The closest color that passes {level}: click to apply it. Den närmaste färgen som klarar {level}: klicka för att använda den. Graphics Processor Grafikprocessor Graphics: {adapter} Grafik: {adapter} Gravity Gravitation diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index fd72402419..75c89b5a0d 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1453,6 +1453,7 @@ font-technology Variable Değişken Fail Kaldı WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 en düşük kontrast: normal metin AA 4.5:1 (1.4.3) ve AAA 7:1 (1.4.6), büyük metin AA 3:1 ve AAA 4.5:1, grafikler ve denetimler AA 3:1 (1.4.11). The background is read at the center of the selection. Arka plan seçimin ortasında okunur. + The closest color that passes {level}: click to apply it. {level} düzeyini karşılayan en yakın renk: uygulamak için tıklayın. Graphics Processor Grafik İşlemcisi Graphics: {adapter} Grafik: {adapter} Gravity Yerçekimi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eedbd4ca26..e46c5e9175 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1555,6 +1555,7 @@ file-filter Templates Шаблони Fail Не відповідає WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Мінімальний контраст за WCAG 2.2: звичайний текст AA 4.5:1 (1.4.3) і AAA 7:1 (1.4.6), великий текст AA 3:1 і AAA 4.5:1, графіка й елементи керування AA 3:1 (1.4.11). The background is read at the center of the selection. Фон визначається в центрі виділення. + The closest color that passes {level}: click to apply it. Найближчий колір, що відповідає {level}: клацніть, щоб застосувати його. Graphics Processor Графічний процесор Graphics: {adapter} Графіка: {adapter} Gravity Гравітація diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4816d2ebaa..03793d07d4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1785,6 +1785,7 @@ file-filter Templates Mẫu Fail Không đạt WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). Độ tương phản tối thiểu theo WCAG 2.2: văn bản thường AA 4.5:1 (1.4.3) và AAA 7:1 (1.4.6), văn bản lớn AA 3:1 và AAA 4.5:1, đồ họa và điều khiển AA 3:1 (1.4.11). The background is read at the center of the selection. Nền được đọc tại tâm vùng chọn. + The closest color that passes {level}: click to apply it. Màu gần nhất đạt {level}: bấm để áp dụng. Graphics Processor Bộ xử lý đồ họa Graphics: {adapter} Đồ họa: {adapter} Gravity Trọng lực diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 3049598865..a9ebbfc8b3 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1490,6 +1490,7 @@ file-filter Templates 模板 Fail 未通过 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低对比度:普通文本 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大号文本 AA 3:1 和 AAA 4.5:1,图形和控件 AA 3:1 (1.4.11)。 The background is read at the center of the selection. 背景在所选对象的中心读取。 + The closest color that passes {level}: click to apply it. 符合 {level} 的最接近颜色:单击即可应用。 Gravity 重力 Grays 灰度级数 Grays and Neutrals 灰色和中性色 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 17e10e55f3..7b28293be5 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1525,6 +1525,7 @@ file-filter Templates 範本 Fail 未通過 WCAG 2.2 contrast minimums: normal text AA 4.5:1 (1.4.3) and AAA 7:1 (1.4.6), large text AA 3:1 and AAA 4.5:1, graphics and controls AA 3:1 (1.4.11). WCAG 2.2 最低對比度:一般文字 AA 4.5:1 (1.4.3) 和 AAA 7:1 (1.4.6),大型文字 AA 3:1 和 AAA 4.5:1,圖形和控制項 AA 3:1 (1.4.11)。 The background is read at the center of the selection. 背景在選取範圍的中心讀取。 + The closest color that passes {level}: click to apply it. 符合 {level} 的最接近顏色:按一下即可套用。 Graphics Processor 圖形處理器 Graphics: {adapter} 圖形:{adapter} Gravity 重力 diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 31dc6307c6..214ecdb392 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -786,6 +786,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_constrain; #[cfg(test)] mod tests_css_properties; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 5bc807f4bb..38cfaf1bc0 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -16,14 +16,20 @@ //! () 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`. -use egui::{Ui, UiBuilder, vec2}; +use std::collections::HashMap; + +use egui::{Color32, Rect, Stroke, Ui, UiBuilder, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms}; use vectorcraft_color::wcag::{self, Category}; use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; use vectorcraft_doc::{ColorMode, NodeId}; +use vectorcraft_engine::cmd::{Backdrop, contrast_measure}; use super::color::{Target, apply, wheel_target}; use super::{color_json, pstate, set_pstate}; @@ -273,15 +279,19 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { /// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with /// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, -/// and its phase. -fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { +/// and its phase, and the field's rect. +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> (Option<([f32; 3], Live)>, Rect) { let (z, x, y) = box_pos(ch, hsb); let mut pick = None; + let mut field_rect = Rect::NOTHING; ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = STRIP_GAP; let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); - if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { + let picked = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at); + // The field is the first thing in the row. + field_rect = Rect::from_min_size(ui.min_rect().min, field); + if let (Some((x, y)), phase) = picked { pick = Some((box_pick(ch, z, x, y, hsb), phase)); } // The hue strip shows the whole spectrum; the others change only their own component. @@ -294,7 +304,7 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> _ => {} } }); - pick + (pick, field_rect) } /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. @@ -313,9 +323,217 @@ type BehindKey = (u64, u64, Vec, Option>, String, Under); /// What the contrast row's answer depends on: the background, the active proxy's paint (with nothing /// selected it is the default for new art, which no revision counts), the document, its revision, /// the selection and its picked symbol object, the proxy, the appearance item, the selected -/// gradient stop and freeform point, the on-screen Appearance of Black and the color settings. +/// gradient stop and freeform point, the on-screen Appearance of Black, the color settings and the +/// Contrast For category, which the closest passing colors are for. pub(super) type RatioKey = - (String, String, Option<(u64, u64)>, Vec, Option>, bool, Option, Option, Option, String, Under); + (String, String, Option<(u64, u64)>, Vec, Option>, bool, Option, Option, Option, String, Under, Category); + +/// Panel state: what the contrast row's answer was measured against, with its [`RatioKey`]. +const BACKDROP: &str = "color-wheel-backdrop"; +/// Panel state: the contrast lines of the square or the field, with the [`LinesKey`] they were +/// found for. +pub(super) const LINES: &str = "color-wheel-lines"; +/// 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, and the color settings. +pub(super) type LinesKey = (Backdrop, Category, String, Under); +/// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates. +pub(super) type Lines = Vec>>; + +/// The columns and rows at which [`contrast_lines`] samples a field. +const LINE_SAMPLES: usize = 32; +/// The 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)>; + +/// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in +/// field coordinates. The field is sampled on a 33 × 33 grid, and each cell whose corners fall on +/// both sides gets a segment between the crossings on its edges, placed by bisection (marching +/// squares; a cell with two opposite corners passing is split by its center). 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. Segments that share an end are joined into one polyline. +pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64]) -> Lines { + let n = LINE_SAMPLES; + let at = |i: usize| i as f32 / n as f32; + // `grid[i][j]` is column i (x) and row j (y). + let grid: Vec> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect(); + let r = |i: usize, j: usize| grid.get(i).and_then(|c| c.get(j)).copied().unwrap_or(f64::NAN); + minimums + .iter() + .map(|&min| { + let pass = |p: FieldPoint| ratio_at(p.0, p.1) >= min; + // The crossing between `p`, on the side `above` says, and `q`. + let cross = |p: FieldPoint, q: FieldPoint, above: bool| { + let lerp = |t: f32| (p.0 + (q.0 - p.0) * t, p.1 + (q.1 - p.1) * t); + let (mut lo, mut hi) = (0.0, 1.0); + for _ in 0..LINE_STEPS { + let mid = (lo + hi) / 2.0; + if pass(lerp(mid)) == above { lo = mid } else { hi = mid } + } + lerp((lo + hi) / 2.0) + }; + let mut edges: HashMap<(usize, usize, bool), Option> = HashMap::new(); + // The crossing on the edge from sample (i, j) across (`across`) or down. + let mut edge = |i: usize, j: usize, across: bool| { + *edges.entry((i, j, across)).or_insert_with(|| { + let (i2, j2) = if across { (i + 1, j) } else { (i, j + 1) }; + let (a, b) = (r(i, j) >= min, r(i2, j2) >= min); + (a != b).then(|| cross((at(i), at(j)), (at(i2), at(j2)), a)) + }) + }; + let mut segments: Vec<[FieldPoint; 2]> = vec![]; + for i in 0..n { + for j in 0..n { + let (top, right, bottom, left) = (edge(i, j, true), edge(i + 1, j, false), edge(i, j + 1, true), edge(i, j, false)); + match (top, right, bottom, left) { + (Some(t), Some(rt), Some(b), Some(l)) => { + // Opposite corners pass: the center says which pair of them it joins. + let half = 0.5 / n as f32; + if pass((at(i) + half, at(j) + half)) == (r(i, j) >= min) { + segments.extend([[t, rt], [b, l]]); + } else { + segments.extend([[t, l], [rt, b]]); + } + } + _ => { + let found: Vec = [top, right, bottom, left].into_iter().flatten().collect(); + if let &[p, q] = found.as_slice() { + segments.push([p, q]); + } + } + } + } + } + // Bands narrower than the samples, along each column and then each row. + for across in [false, true] { + let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) }; + let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) }; + let bands: Vec = (0..=n) + .map(|k| { + let mut found = vec![]; + for s in 0..=n { + let (before, after) = (s.saturating_sub(1), (s + 1).min(n)); + let v = value(k, s); + if v >= min || v < value(k, before) || (after != s && v <= value(k, after)) { + continue; + } + let peak = wcag::peak_between(f64::from(at(before)), f64::from(at(after)), &|t| { + let p = point(k, t as f32); + ratio_at(p.0, p.1) + }) as f32; + if pass(point(k, peak)) { + found.push(( + peak, + cross(point(k, at(before)), point(k, peak), false), + cross(point(k, peak), point(k, at(after)), true), + )); + } + } + found + }) + .collect(); + for pair in bands.windows(2) { + let [this, next] = pair else { continue }; + for (peak, a, b) in this { + if let Some((_, c, d)) = next.iter().find(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32) { + segments.extend([[*a, *c], [*b, *d]]); + } + } + } + } + chain(segments) + }) + .collect() +} + +/// `segments` joined end to end into polylines where they share an end. +fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec> { + let key = |p: FieldPoint| (p.0.to_bits(), p.1.to_bits()); + let mut ends: HashMap<(u32, u32), Vec> = HashMap::new(); + for (s, seg) in segments.iter().enumerate() { + for p in seg { + ends.entry(key(*p)).or_default().push(s); + } + } + let mut used = vec![false; segments.len()]; + let mut lines = vec![]; + for (start, [a, b]) in segments.iter().enumerate() { + if used.get(start).copied().unwrap_or(true) { + continue; + } + if let Some(u) = used.get_mut(start) { + *u = true; + } + let mut line = std::collections::VecDeque::from([*a, *b]); + for back in [true, false] { + loop { + let end = if back { line.back() } else { line.front() }; + let Some(end) = end.copied() else { break }; + let next = ends.get(&key(end)).and_then(|ss| ss.iter().copied().find(|s| !used.get(*s).copied().unwrap_or(true))); + let Some((s, [p, q])) = next.and_then(|s| segments.get(s).map(|seg| (s, *seg))) else { break }; + if let Some(u) = used.get_mut(s) { + *u = true; + } + let other = if key(p) == key(end) { q } else { p }; + if back { line.push_back(other) } else { line.push_front(other) } + } + } + lines.push(line.into_iter().collect()); + } + lines +} + +/// The contrast lines of the wheel's square or the box's field on HSB `hsb`, kept per [`LinesKey`]: +/// where a pick there, stored as the wheel stores it in place of `tgt`'s color, meets each minimum +/// of the chosen category against `backdrop`. +fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, hsb: [f32; 3], cmyk_doc: bool) -> Lines { + let set = &app.ui.color_wheel; + let (category, view, ch) = (set.contrast_for, set.view, set.channel); + let was = replaced(app, tgt, false); + // The component the field holds fixed: the box's strip value, or the wheel's hue. + let fixed = if view == View::Box { box_pos(ch, hsb).0 } else { hsb[0] }; + let field = format!("{view:?} {ch:?} {fixed} {:?} {cmyk_doc}", was.map(|c| c.model())); + let key: LinesKey = (backdrop.clone(), category, field, under()); + if let Some((k, lines)) = pstate::>(ui.ctx(), LINES) + && k == key + { + return lines; + } + let cms = cms::active(); + let at = |x: f32, y: f32| if view == View::Box { box_pick(ch, fixed, x, y, hsb) } else { [hsb[0], x, 1.0 - y] }; + let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc)))); + let (aa, aaa) = category.minimums(); + let minimums: Vec = std::iter::once(aa).chain(aaa).collect(); + let lines = contrast_lines(&ratio_at, &minimums); + set_pstate(ui.ctx(), LINES, Some((key, lines.clone()))); + lines +} + +/// Draw `lines` (from [`contrast_lines`]) over the field in `rect`: AA solid and AAA dashed, each +/// a light line over a dark one, as the field's marker is drawn. +fn draw_contrast_lines(ui: &Ui, rect: Rect, lines: &Lines) { + let painter = ui.painter().with_clip_rect(rect); + let at = |(x, y): &(f32, f32)| egui::pos2(rect.left() + x * rect.width(), rect.top() + y * rect.height()); + for (level, polylines) in lines.iter().enumerate() { + for line in polylines { + let points: Vec = line.iter().map(at).collect(); + for stroke in [Stroke::new(3.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] { + if level == 0 { + painter.add(egui::Shape::line(points.clone(), stroke)); + } else { + painter.extend(egui::Shape::dashed_line(&points, stroke, 4.0, 3.0)); + } + } + } + } +} /// The active color settings and profiles generation, which change how a color displays without /// a document revision (Edit › Color Settings, a document's assigned profiles). @@ -357,17 +575,24 @@ fn background(app: &mut VectorcraftApp, ui: &Ui) -> Option { Color::from_hex(&hex?) } -/// 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, else the pinned color or -/// the one kept by [`background`]. -fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { +/// The contrast row's measurement: the background it was measured against, `color.contrast`'s +/// answer for the chosen category, and what the lines measure picks against. +struct Measured { + against: Option, + answer: Option, + backdrop: Option, +} + +/// Measure the active color for the contrast row and the lines. Without a pinned background it +/// 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 answer is +/// kept per [`RatioKey`]. +fn measure(app: &mut VectorcraftApp, ui: &Ui) -> Measured { let category = app.ui.color_wheel.contrast_for; let pinned = app.ui.color_wheel.contrast_background.is_some(); let against = background(app, ui); let sampled = !pinned; + let mut backdrop = None; let answer = against.as_ref().and_then(|bg| { let st = app.session.active(); let key: RatioKey = ( @@ -382,27 +607,51 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { app.session.selected_freeform_point(), app.session.prefs.black_on_screen.clone(), under(), + category, ); - match pstate::)>>(ui.ctx(), RATIO) { - Some((k, r)) if k == key => r, + let kept = pstate::)>>(ui.ctx(), RATIO); + let kept_backdrop = pstate::)>>(ui.ctx(), BACKDROP); + match (kept, kept_backdrop) { + (Some((k, r)), Some((kb, b))) if k == key && kb == key => { + backdrop = b; + r + } _ => { let against = if sampled { json!("below") } else { color_json(bg) }; - let r = app.session.execute("color.contrast", &json!({ "against": against })).ok(); - set_pstate(ui.ctx(), RATIO, Some((key, r.clone()))); + let m = contrast_measure(&app.session, &json!({ "against": against, "for": category.id() })).ok(); + let (r, b) = m.map_or((None, None), |(r, b)| (Some(r), Some(b))); + set_pstate(ui.ctx(), RATIO, Some((key.clone(), r.clone()))); + set_pstate(ui.ctx(), BACKDROP, Some((key, b.clone()))); + backdrop = b; r } } }); + Measured { against, answer, backdrop } +} + +/// 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; a dash when there is no background or no color to measure. Without a pinned +/// background the first chip shows the background in the answer, else the pinned color or the one +/// kept by [`background`]. The fix chip keeps its space while hidden. Returns the fix color when its +/// chip is clicked. +fn contrast_row(app: &VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option { + let category = app.ui.color_wheel.contrast_for; + let pinned = app.ui.color_wheel.contrast_background.is_some(); + let sampled = !pinned; + let (against, answer) = (m.against, m.answer.as_ref()); + let mut clicked = None; let resp = ui .horizontal(|ui| { let (rect, _) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::hover()); // The chip shows the background the ratio was measured against. - let measured = answer.as_ref().filter(|_| sampled).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); + let measured = answer.filter(|_| sampled).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); match measured.or(against) { Some(c) => widgets::swatch_tile(ui, rect, &Paint::solid(c), false, false), None => widgets::swatch_tile(ui, rect, &Paint::None, false, false), } - let Some(ratio) = answer.as_ref().and_then(|r| r["ratio"].as_f64()) else { + let Some(ratio) = answer.and_then(|r| r["ratio"].as_f64()) else { ui.label("—"); return; }; @@ -413,6 +662,7 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(aaa) = aaa { ui.label(format!("AAA {}", result(aaa))); } + clicked = fix_chip(ui, answer, aa, aaa); }) .response; let mut tip = tl!( @@ -424,6 +674,35 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui) { tip.push_str(tl!("The background is read at the center of the selection.")); } resp.on_hover_text(tip); + clicked +} + +/// 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`. Its space is +/// kept while there is none, so the row does not move as a drag crosses a line. Returns the color +/// when the chip is clicked or activated. +fn fix_chip(ui: &mut Ui, answer: Option<&Value>, aa: bool, aaa: Option) -> Option { + let level = if !aa { + Some(("aa", "AA")) + } else if aaa == Some(false) { + Some(("aaa", "AAA")) + } else { + None + }; + let fix = level.and_then(|(key, name)| { + let v = answer?.get("fix")?.get(key)?; + serde_json::from_value::(v.clone()).ok().map(|c| (c, name)) + }); + let Some((color, name)) = fix else { + ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::hover()); + return None; + }; + let (rect, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::click()); + widgets::swatch_tile(ui, rect, &Paint::solid(color), false, false); + let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &label)); + let resp = resp.on_hover_text(&label); + resp.clicked().then_some(color) } /// What the HSB picked last belongs to: the document, the selected objects or text characters, @@ -528,7 +807,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); + let measured = app.ui.color_wheel.contrast.then(|| measure(app, ui)); let mut pick: Option<([f32; 3], Live)> = None; + let mut field_rect = Rect::NOTHING; ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(44.0); @@ -536,11 +817,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); let size = ui.available_width().min(MAX_WHEEL); if app.ui.color_wheel.view == View::Box { - pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); + (pick, field_rect) = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); return; } let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked); let square = widgets::ring_square(ring.rect); + field_rect = square; let mut field_ui = ui.new_child(UiBuilder::new().id_salt("color-wheel-square").max_rect(square)); let axes = [FieldAxis { name: tl!("Saturation"), units: 100.0, suffix: "%" }, FieldAxis { name: tl!("Brightness"), units: 100.0, suffix: "%" }]; @@ -562,12 +844,18 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); - if app.ui.color_wheel.contrast { - contrast_row(app, ui); + let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + if let Some(m) = &measured { + if let Some(backdrop) = &m.backdrop { + let lines = lines_for(app, ui, backdrop, &tgt, hsb, cmyk_doc); + draw_contrast_lines(ui, field_rect, &lines); + } + if let Some(c) = contrast_row(app, ui, m) { + apply(app, &tgt, c, Live::Released, false); + } } let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); - let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs new file mode 100644 index 0000000000..1418dc5fd2 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -0,0 +1,167 @@ +//! 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. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb}; +use vectorcraft_engine::Session; + +use super::color_wheel::{LINES, Lines, LinesKey, box_pick, show}; +use super::pstate; +use crate::VectorcraftApp; +use crate::dialogs::color_picker::Channel; + +/// 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 harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + // The height the panel took, for the test that checks nothing moves. + let h = ui.min_rect().height(); + ui.ctx().data_mut(|d| d.insert_temp(egui::Id::unique("panel-height"), h)); + }, + app, + ); + h.run_steps(2); + h +} + +fn lines(h: &Harness<'static, VectorcraftApp>) -> Lines { + pstate::>(&h.ctx, LINES).expect("the field's contrast lines were found").1 +} + +/// 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(h: &mut Harness<'static, VectorcraftApp>, 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 = h.state_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))] +} + +#[test] +fn the_box_marks_where_its_colors_meet_aa() { + let mut h = harness(app("box", "hue")); + let lines = lines(&h); + assert_eq!(lines.len(), 2, "AA and AAA for normal text"); + let hsb = vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap())); + let z = super::color_wheel::box_pos(Channel::Hue, hsb).0; + let at = move |x: f32, y: f32| box_pick(Channel::Hue, z, x, y, hsb); + let [above, below] = either_side(&lines); + let (a, b) = (passes_aa(&mut h, &at, above), passes_aa(&mut h, &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); +} + +#[test] +fn the_wheels_square_marks_where_its_colors_meet_aa() { + let mut h = harness(app("wheel", "hue")); + let lines = lines(&h); + let hsb = vectorcraft_color::rgb_to_hsb(cms::active().display_rgb(&Color::from_hex("#fdc96e").unwrap())); + let at = move |x: f32, y: f32| [hsb[0], x, 1.0 - y]; + let [above, below] = either_side(&lines); + assert!(passes_aa(&mut h, &at, above) && !passes_aa(&mut h, &at, below)); +} + +/// 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 mut h = harness(app); + let lines = lines(&h); + let aa = lines.first().expect("an AA level"); + assert!(aa.len() >= 2, "a line on each side of the band: {aa:?}"); + h.state_mut().run("paint.setFill", json!({"color": "#757575"})).unwrap(); + let r = h.state_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 h = harness(app); + let lines = lines(&h); + let line = lines.first().and_then(|aa| aa.iter().max_by_key(|l| l.len())).expect("an AA line"); + let (xs, ys): (Vec, Vec) = 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:?}"); +} + +#[test] +fn graphics_have_one_line() { + let mut app = app("box", "saturation"); + app.run("ui.colorWheel", json!({"contrastFor": "graphics"})).unwrap(); + let h = harness(app); + assert_eq!(lines(&h).len(), 1, "graphics have AA only"); +} + +const CHIP: &str = "The closest color that passes AA: click to apply it."; + +#[test] +fn the_chip_applies_the_fix_color_answers() { + let mut h = harness(app("wheel", "hue")); + let want = h.state_mut().session.execute("color.contrast", &json!({"against": "#355f78"})).unwrap(); + let fix: Color = serde_json::from_value(want["fix"]["aa"].clone()).unwrap(); + h.get_by_label(CHIP).click(); + h.run_steps(2); + match h.state().session.proxy_paints().0 { + Paint::Solid { color, .. } => assert_eq!(color, fix), + other => panic!("the fill is {other:?}"), + } + assert!(h.query_by_label(CHIP).is_none(), "the color now passes AA: no chip"); + assert!(h.query_by_label("AA Pass").is_some()); +} + +#[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 h = harness(app); + assert!(h.query_by_label(CHIP).is_none(), "4.49:1 meets large text AA"); + assert!(h.query_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 h = harness(app); + assert!(h.query_by_label_contains("The closest color that passes").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(); + let h = harness(app); + h.ctx.data(|d| d.get_temp::(egui::Id::unique("panel-height"))).expect("a height") + }; + // #FDC96E fails AA and shows the chip; #FFFFFF passes both levels and hides it. + assert_eq!(height("#fdc96e"), height("#ffffff")); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index efe976d74e..ac5900da54 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -234,11 +234,12 @@ 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, large text and 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, large text and 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 diff --git a/docs/mcp.md b/docs/mcp.md index 0a5f508969..051bd114b4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -658,7 +658,10 @@ the list return an error and change nothing. `{"contrast": true}` shows Show Con box, `contrastFor` (`normalText`, `largeText` or `graphics`) picks the category its AA and AAA 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. The command returns `{view, channel, contrast, contrastFor, -contrastBackground}`, and the settings are kept with the preferences. +contrastBackground}`, and the settings are kept with the preferences. 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, and when the +color fails a level, a chip at the end of the row shows `color.contrast`'s `fix` for the first level it fails; a click +applies it. In remote desktop mode, `invoke_menu` with `{"command":"ui.sampleScreenColor","params":{}}` shows the system's screen color sampler and returns `null` before a color is picked: the system's sampler on macOS, the XDG desktop @@ -1065,7 +1068,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 @@ -1087,7 +1090,12 @@ selected objects that draw one color with different blend modes, or at different `"below"`, also in different translucent groups or layers), where hidden objects do not count; and a proxy of None, a pattern or a hidden row without `color`. `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. Headless MCP -answers it too. +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 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. 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index d808656065..7049dd2e2a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1651,7 +1651,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - **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. 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. `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. `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}`). Plain Comma and Period, and also Shift+Comma and Shift+Period, apply the last solid color and the last gradient to the active Fill or Stroke proxy in VectorCraft ([Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), "Select color fill mode" and "Select gradient fill mode"). Recent Colors keeps the last 30 solid colors applied, newest first and each once, and the list stays the same when another document is opened or made active; a 31st color drops the oldest ([Select colors using the Color panel](https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/select-colors-using-the-color-panel.html)). The list lasts for the session. In the Color and Swatches panels the chips wrap onto further rows when the panel is too narrow for one row (`paint.recent`). Tests: `recent_colors_keep_thirty_colors_across_documents` in `crates/engine/src/tests/paintproxy.rs`, `all_thirty_recent_colors_wrap_into_a_narrow_panel` in `crates/ui-egui/src/panels/color/tests.rs`. From 45f6c20380d68b8b159970d106660c34c1f4624f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:14:52 -0800 Subject: [PATCH 02/13] Color Wheel: a contrast fix also passes with its values rounded to 8 bits color.contrast's fix search now accepts a candidate only when it meets the level both as measured and with the color, the background, the art below each group or layer, the opacities, and the pixel and alpha each level gives rounded to 8 bits per channel. The renderer rounds the paint's color and alpha that way, so a fix that meets 4.5:1 only before rounding (a gray of about 118.7/255 on white, which paints as #777777 at 4.48:1) is no longer offered. The reported ratio and its pass results are unchanged. The per-level drawing of the backdrop moves into Pass::draw, which both the measured ratio and the 8-bit check use. --- crates/engine/src/cmd/colorcmds.rs | 84 +++++++++++++++++------- crates/engine/src/tests/colorcontrast.rs | 56 ++++++++++++++-- docs/mcp.md | 2 + 3 files changed, 113 insertions(+), 29 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index b938c40d0b..c9338e510d 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1016,28 +1016,50 @@ pub struct Backdrop { } /// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color -/// and its alpha), and for a level that blends without isolating, the alpha of what it holds drawn -/// alone. +/// 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), - alone: Option, + 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 `x` (a color and its alpha, drawn over the art below it): a level - /// that blends takes that art back out by the alpha of what it holds drawn alone. - fn source(&self, x: ([f32; 3], f32)) -> ([f32; 3], f32) { - match self.alone { - None => x, - Some(alone) if alone <= 0.0 => (x.0, 0.0), - Some(alone) => { - 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) - } + /// 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() } } } @@ -1053,8 +1075,8 @@ impl Backdrop { /// Display sRGB `shown`, drawn as the measured color is drawn, over the background. pub fn front(&self, shown: [f32; 3]) -> [f32; 3] { - let x = self.passes.iter().fold((shown, 1.0f32), |x, p| composite(p.blend, p.source(x), p.opacity, p.backdrop)); - if x.1 >= 1.0 { x.0 } else { wcag::over(x.0, x.1, self.against) } + 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 @@ -1063,6 +1085,20 @@ impl Backdrop { 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; @@ -1101,11 +1137,16 @@ fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) /// 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). None when `color` already meets it, or when no lightness of its hue does. +/// 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, rich_black: bool) -> Option { let cms = vectorcraft_color::cms::active(); let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c)); - let ratio = |srgb: [f32; 3]| backdrop.ratio(drawn(&in_model_of(&cms, srgb, color))); + let ratio = |srgb: [f32; 3]| { + let shown = drawn(&in_model_of(&cms, srgb, color)); + backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown)) + }; if backdrop.ratio(drawn(color)) >= minimum { return None; } @@ -1249,13 +1290,8 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1, _ => 0.0, }; - let pass = Pass { blend: step.blend, opacity: step.opacity, backdrop, alone: blends(step).then_some(alone) }; - let source = pass.source(([0.0; 3], alpha)).1; - // A level that isolates its blending carries out the alpha of what it holds composited on - // its own. - let drawn = if step.isolate { alpha } else { alone } * step.opacity.clamp(0.0, 1.0); - alpha = composite(step.blend, ([0.0; 3], source), step.opacity, backdrop).1; - alone = drawn + inner * (1.0 - drawn); + 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) }; diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 09210d9e6e..e3489bf047 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -758,7 +758,7 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() { 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.51).contains(&got), "{fix:?} draws {drawn:?}: {got}"); + assert!((4.5..4.57).contains(&got), "{fix:?} draws {drawn:?}: {got}"); } #[test] @@ -877,7 +877,7 @@ fn a_failing_color_answers_the_closest_passing_color_of_its_hue() { 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.51).contains(&ratio(&back)), "{back}"); + 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:?}"); @@ -885,7 +885,53 @@ fn a_failing_color_answers_the_closest_passing_color_of_its_hue() { 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.51).contains(&ratio(&aaa)), "large text AAA is AA's 4.5:1 for normal text: {aaa}"); + 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}"); + let back = s.execute("color.contrast", &json!({"color": r["fix"]["aa"], "against": "#ffffff"})).unwrap(); + assert!((4.5..4.57).contains(&ratio(&back)), "{back}"); +} + +/// 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] @@ -898,7 +944,7 @@ fn a_passing_color_has_no_fix_and_graphics_have_no_aaa_fix() { let fix = g["fix"].as_object().unwrap(); assert_eq!(fix.keys().collect::>(), ["aa"], "{g}"); let back = s.execute("color.contrast", &json!({"color": g["fix"]["aa"], "against": "#ffffff"})).unwrap(); - assert!((3.0..3.01).contains(&ratio(&back)), "{back}"); + 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}"); @@ -925,7 +971,7 @@ fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() { 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.01).contains(&ratio(&back)), "{back}"); + assert!((3.0..3.04).contains(&ratio(&back)), "{back}"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 4adc4d2382..94655f6cd7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1228,6 +1228,8 @@ rows below it: there `"below"` reads the art below each such level, and a given 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, and the opacities 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. 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). From a46d022ed8c8ee7189ec64b5224899867a8eb75e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:17:42 -0800 Subject: [PATCH 03/13] Color Wheel: contrast lines are found coarsely while a drag changes the field A hue ring or strip drag changes the field on every frame, and a CMYK target separates every sample, so finding the full lines each frame slowed the drag. While a drag changes the field, the lines are found on an 8 by 8 grid without the narrow-band search, and the full lines are found once the drag ends. A drag that keeps the field keeps the full lines. --- crates/ui-egui/src/panels/color_wheel.rs | 40 +++++++++++-------- .../tests_color_wheel_contrast_lines.rs | 19 +++++++++ 2 files changed, 43 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 54934c58e6..87481f1861 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -792,13 +792,16 @@ const BACKDROP: &str = "color-wheel-backdrop"; pub(super) const LINES: &str = "color-wheel-lines"; /// 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, and the color settings. -pub(super) type LinesKey = (Backdrop, Category, String, Under); +/// stores, the color settings, and whether they were found coarsely during a drag. +pub(super) type LinesKey = (Backdrop, Category, String, Under, bool); /// Per minimum of the category (AA, then AAA where it has one), the lines in field coordinates. pub(super) type Lines = Vec>>; /// The columns and rows at which [`contrast_lines`] samples a field. const LINE_SAMPLES: usize = 32; +/// The columns and rows at which [`contrast_lines`] samples a field, without the narrow-band +/// search, while a drag changes the field (the hue ring, the box's strip). +const COARSE_LINE_SAMPLES: usize = 8; /// The halvings that place a line on the edge between two samples. const LINE_STEPS: usize = 10; @@ -810,14 +813,15 @@ type FieldPoint = (f32, f32); type Bands = Vec<(f32, FieldPoint, FieldPoint)>; /// Where the contrast `ratio_at` a field point crosses each of `minimums`: per minimum, polylines in -/// field coordinates. The field is sampled on a 33 × 33 grid, and each cell whose corners fall on -/// both sides gets a segment between the crossings on its edges, placed by bisection (marching -/// squares; a cell with two opposite corners passing is split by its center). 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. Segments that share an end are joined into one polyline. -pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64]) -> Lines { - let n = LINE_SAMPLES; +/// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell +/// whose corners fall on both sides gets a segment between the crossings on its edges, placed by +/// bisection (marching squares; a cell with two opposite corners passing is split by its center). +/// With `bands`, 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. Segments that share an end are joined into one +/// polyline. +pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64], n: usize, narrow: bool) -> Lines { + let n = n.max(1); let at = |i: usize| i as f32 / n as f32; // `grid[i][j]` is column i (x) and row j (y). let grid: Vec> = (0..=n).map(|i| (0..=n).map(|j| ratio_at(at(i), at(j))).collect()).collect(); @@ -869,7 +873,7 @@ pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64 } } // Bands narrower than the samples, along each column and then each row. - for across in [false, true] { + for across in [false, true].into_iter().filter(|_| narrow) { let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) }; let value = |k: usize, s: usize| if across { r(s, k) } else { r(k, s) }; let bands: Vec = (0..=n) @@ -949,7 +953,9 @@ fn chain(segments: Vec<[FieldPoint; 2]>) -> Vec> { /// 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`. +/// 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, ui: &Ui, backdrop: &Backdrop, tgt: &Target, hsb: [f32; 3], cmyk_doc: bool) -> Lines { let set = &app.ui.color_wheel; let (category, view, ch) = (set.contrast_for, set.view, set.channel); @@ -957,9 +963,10 @@ fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, h // The component the field holds fixed: the box's strip value, or the wheel's hue. let fixed = if view == View::Box { box_pos(ch, hsb).0 } else { hsb[0] }; let field = format!("{view:?} {ch:?} {fixed} {:?} {cmyk_doc}", was.map(|c| c.model())); - let key: LinesKey = (backdrop.clone(), category, field, under()); + let dragging = app.session.in_interaction(); + let key = |coarse: bool| -> LinesKey { (backdrop.clone(), category, field.clone(), under(), coarse) }; if let Some((k, lines)) = pstate::>(ui.ctx(), LINES) - && k == key + && (k == key(false) || (dragging && k == key(true))) { return lines; } @@ -968,8 +975,9 @@ fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, h let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc)))); let (aa, aaa) = category.minimums(); let minimums: Vec = std::iter::once(aa).chain(aaa).collect(); - let lines = contrast_lines(&ratio_at, &minimums); - set_pstate(ui.ctx(), LINES, Some((key, lines.clone()))); + let samples = if dragging { COARSE_LINE_SAMPLES } else { LINE_SAMPLES }; + let lines = contrast_lines(&ratio_at, &minimums, samples, !dragging); + set_pstate(ui.ctx(), LINES, Some((key(dragging), lines.clone()))); lines } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs index 1418dc5fd2..d8501b6351 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -165,3 +165,22 @@ fn the_panel_keeps_its_height_when_the_chip_goes() { // #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 h = harness(app("box", "hue")); + let coarse = |h: &Harness<'static, VectorcraftApp>| pstate::>(&h.ctx, LINES).expect("lines were found").0.4; + assert!(!coarse(&h)); + h.state_mut().session.begin_interaction("test").unwrap(); + h.run_steps(2); + assert!(!coarse(&h), "the field is unchanged, so the full lines are kept"); + h.state_mut().run("paint.setFill", json!({"color": "#6efdc9"})).unwrap(); + assert!(h.state().session.in_interaction(), "the new color is part of the drag"); + h.run_steps(2); + assert!(coarse(&h), "another hue during the drag"); + h.state_mut().session.commit_interaction().unwrap(); + h.run_steps(2); + assert!(!coarse(&h), "found in full once the drag ends"); +} From c33376b013653f1dd55b7008c05132739ef7d7fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:17:42 -0800 Subject: [PATCH 04/13] Color Wheel: contrast lines follow the Appearance of Black setting The box's and the wheel's contrast lines measured each field color with the plain display conversion, while color.contrast shows 100 % K alone as black when Appearance of Black is rich. The lines now use the same conversion through Backdrop::shown, and the backdrop the lines are kept against carries the setting, so the lines are found again after the setting changes. --- crates/engine/src/cmd/colorcmds.rs | 24 +++++++++++++++--------- crates/engine/src/tests/colorcontrast.rs | 16 ++++++++++++++++ crates/ui-egui/src/panels/color_wheel.rs | 2 +- 3 files changed, 32 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index c9338e510d..6f8b70bc44 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1013,6 +1013,8 @@ pub struct Backdrop { passes: Vec, /// The color and amount a fill stains the picked object of a dynamic symbol instance with. stain: Option<(Color, f32)>, + /// Whether the canvas shows 100 % K alone as black (a rich black Appearance of Black). + rich_black: bool, } /// One level of a [`Backdrop`]: its blend mode and opacity, the art below it (a display sRGB color @@ -1073,6 +1075,12 @@ impl Backdrop { } } + /// 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)); @@ -1140,17 +1148,16 @@ fn in_model_of(cms: &vectorcraft_color::cms::Cms, srgb: [f32; 3], like: &Color) /// 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, rich_black: bool) -> Option { +fn closest_passing(backdrop: &Backdrop, color: &Color, minimum: f64) -> Option { let cms = vectorcraft_color::cms::active(); - let drawn = |c: &Color| shown_rgb(&cms, rich_black, &backdrop.drawn_color(c)); let ratio = |srgb: [f32; 3]| { - let shown = drawn(&in_model_of(&cms, srgb, color)); + let shown = backdrop.shown(&cms, &in_model_of(&cms, srgb, color)); backdrop.ratio(shown).min(backdrop.ratio_at_eight_bits(shown)) }; - if backdrop.ratio(drawn(color)) >= minimum { + if backdrop.ratio(backdrop.shown(&cms, color)) >= minimum { return None; } - let fix = wcag::closest_passing(shown_rgb(&cms, rich_black, color), minimum, &ratio)?; + let fix = wcag::closest_passing(shown_rgb(&cms, backdrop.rich_black, color), minimum, &ratio)?; Some(in_model_of(&cms, fix, color)) } @@ -1170,8 +1177,7 @@ pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { } }; let (color, backdrop) = contrast_backdrop(s, p)?; - let rich_black = s.prefs.black_on_screen == "rich"; - let ratio = backdrop.ratio(shown_rgb(&vectorcraft_color::cms::active(), rich_black, &backdrop.drawn_color(&color))); + let ratio = backdrop.ratio(backdrop.shown(&vectorcraft_color::cms::active(), &color)); let levels = |c: Category| { let (aa, aaa) = c.passes(ratio); match aaa { @@ -1179,7 +1185,7 @@ pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { None => json!({ "aa": aa }), } }; - let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum, rich_black) { + let fix = |minimum: f64| match closest_passing(&backdrop, &color, minimum) { Some(c) => serde_json::to_value(c).unwrap_or(Value::Null), None => Value::Null, }; @@ -1295,7 +1301,7 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { passes.push(pass); } let stain = if given { None } else { stain_of(s) }; - Ok((color, Backdrop { against, written, passes, stain })) + 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 diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index e3489bf047..6b43325d74 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -903,6 +903,22 @@ fn a_fix_passes_as_the_canvas_paints_it() { 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] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 87481f1861..c7627e68a5 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -972,7 +972,7 @@ fn lines_for(app: &VectorcraftApp, ui: &Ui, backdrop: &Backdrop, tgt: &Target, h } let cms = cms::active(); let at = |x: f32, y: f32| if view == View::Box { box_pick(ch, fixed, x, y, hsb) } else { [hsb[0], x, 1.0 - y] }; - let ratio_at = |x: f32, y: f32| backdrop.ratio(cms.display_rgb(&backdrop.drawn_color(&stored(&cms, at(x, y), was.as_ref(), cmyk_doc)))); + let ratio_at = |x: f32, y: f32| backdrop.ratio(backdrop.shown(&cms, &stored(&cms, at(x, y), was.as_ref(), cmyk_doc))); let (aa, aaa) = category.minimums(); let minimums: Vec = std::iter::once(aa).chain(aaa).collect(); let samples = if dragging { COARSE_LINE_SAMPLES } else { LINE_SAMPLES }; From 767c0798a931fec86a8418e0432db70b1b2a32ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:57:36 -0800 Subject: [PATCH 05/13] Color Wheel: a contrast fix keeps the largest chroma sRGB shows at its lightness The fix search lowered an out-of-gamut chroma by bisection, which stops at the first gamut boundary. Near blue the chromas sRGB holds at one lightness come in two stretches, so a blue that needed a little more contrast lost much of its chroma (blue on #B8B8B8 got a fix of chroma 0.25 against blue's 0.31). The search now uses oklab::from_oklch, which takes the largest chroma below the asked one that fits. --- crates/color/src/wcag.rs | 42 +++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 24 deletions(-) diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index d63e07c952..16b34bb166 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -96,26 +96,6 @@ 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; -/// The halvings [`closest_passing`] makes of the chroma when sRGB cannot show it. -const CHROMA_STEPS: usize = 24; - -/// The display sRGB of OKLCH lightness `l`, chroma `c` and the hue whose sine and cosine are `sc`, -/// with the chroma lowered until the color fits in sRGB. -fn oklch_in_gamut(l: f64, c: f64, (sin, cos): (f64, f64)) -> [f32; 3] { - let at = |c: f64| crate::libraries::oklab_to_srgb(l, c * cos, c * sin); - let fits = |rgb: &[f64; 3]| rgb.iter().all(|v| (-1e-6..=1.0 + 1e-6).contains(v)); - let mut rgb = at(c); - if !fits(&rgb) { - let (mut lo, mut hi) = (0.0, c); - for _ in 0..CHROMA_STEPS { - let mid = (lo + hi) / 2.0; - if fits(&at(mid)) { lo = mid } else { hi = mid } - } - rgb = at(lo); - } - rgb.map(|v| v.clamp(0.0, 1.0) as f32) -} - /// 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 { @@ -138,7 +118,8 @@ pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { /// The display sRGB color closest to `srgb` whose `ratio` is at least `minimum`: the same OKLCH hue /// () with the lightness raised or lowered, whichever -/// takes the smaller step, and the chroma lowered where sRGB cannot show it. Each side is tested at +/// 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 @@ -150,11 +131,10 @@ pub fn closest_passing(srgb: [f32; 3], minimum: f64, ratio: &dyn Fn([f32; 3]) -> if passes(srgb) { return Some(srgb); } - let [l, a, b] = crate::libraries::srgb_to_oklab(srgb); - let (c, sc) = (a.hypot(b), b.atan2(a).sin_cos()); + 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| oklch_in_gamut(l + (end - l) * t, c, sc); + let at = |t: f64| crate::oklab::from_oklch(l + (end - l) * t, c, h).0; let step = |k: usize| k as f64 / LIGHTNESS_SAMPLES as f64; let ratios: Vec = (1..=LIGHTNESS_SAMPLES).map(|k| ratio(at(step(k)))).collect(); // `lo` fails and `hi` passes, the step before the first sample that passes. @@ -280,6 +260,20 @@ mod tests { 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]; From 86f148989527a4773e8a8cf55ae44bdbc3330ad4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:57:36 -0800 Subject: [PATCH 06/13] Color Wheel: the contrast row's chips show the focus outline of the color fields The fix chip drew no focus indicator, and the background chip recolored its own border. Both now draw the outline a focused color field draws around itself (widgets::focus_outline). --- crates/ui-egui/src/panels/color_wheel.rs | 5 ++--- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/color.rs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c7627e68a5..3181a5a903 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -1106,9 +1106,7 @@ fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option widgets::swatch_tile(ui, rect, &Paint::solid(c), false, false), None => widgets::swatch_tile(ui, rect, &Paint::None, false, false), } - if chip_resp.has_focus() { - ui.painter().rect_stroke(rect, 0.0, ui.visuals().selection.stroke, StrokeKind::Inside); - } + widgets::focus_outline(ui, &chip_resp, rect); let enabled = ui.is_enabled(); let value = chip.map(|c| hex(bytes(cms::active().display_rgb(&c)))); chip_resp.widget_info(|| egui::WidgetInfo { @@ -1163,6 +1161,7 @@ fn fix_chip(ui: &mut Ui, answer: Option<&Value>, aa: bool, aaa: Option) -> }; let (rect, resp) = ui.allocate_exact_size(vec2(CHIP, CHIP), egui::Sense::click()); widgets::swatch_tile(ui, rect, &Paint::solid(color), false, false); + widgets::focus_outline(ui, &resp, rect); let label = crate::i18n::fmt(tl!("The closest color that passes {level}: click to apply it."), &[("level", name)]); resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), &label)); let resp = resp.on_hover_text(&label); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index b67df13c7f..38b1beca0f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -42,7 +42,7 @@ pub use color::{ color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, ring_markers, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, }; -pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, focus_outline, hex_text, pointer_phase}; #[cfg(test)] pub(crate) use color::{SHADE, shade_cells, shade_edges}; pub use drag::{ diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 8f5ec8b2d9..4bd2846018 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -383,7 +383,7 @@ fn arrow_steps(ui: &Ui, id: egui::Id, horizontal: bool, vertical: bool) -> (f32, } /// The focus outline of a focused color control. -fn focus_outline(ui: &Ui, resp: &Response, rect: Rect) { +pub(crate) fn focus_outline(ui: &Ui, resp: &Response, rect: Rect) { if ui.memory(|m| m.has_focus(resp.id)) { let t = Tokens::get(ui.ctx()); ui.painter().rect_stroke(rect.expand(2.0), 0.0, Stroke::new(1.0, t.accent), StrokeKind::Outside); From 6be0bafa7299fb75667bcb86fee8260d80d906ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:28:18 -0800 Subject: [PATCH 07/13] Color Wheel: color.contrast's params text describes the 8-bit check on a fix The params text now says what docs/mcp.md says: a fix 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. docs/mcp.md names the rounded color and alpha of each level too. --- crates/engine/src/cmd/colorcmds.rs | 2 +- docs/mcp.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 6f8b70bc44..f3f250dba1 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} 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`), 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; null when the color already meets the level, or when no lightness of its hue does}", + "{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`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} 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`), 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; null when the color already meets the level, or when no lightness of its hue does}", always, contrast ), diff --git a/docs/mcp.md b/docs/mcp.md index 94655f6cd7..8246023baa 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1229,7 +1229,7 @@ Headless MCP answers it too. The answer also has `for` (the category `for` names `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, and the opacities rounded to 8 bits per channel. The +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. 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). From 463bdbcac709d7f3517014428ede3631c177cea9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:21:45 -0800 Subject: [PATCH 08/13] Color Wheel: the contrast fix test checks that the fix is the closest gray The test of the #777777 fix now also checks that the gray one 8-bit step lighter than the fix fails AA, so a search that lands on a darker gray fails it. The doc comment of `contrast_lines` names its `narrow` parameter, and `docs/mcp.md` says that Enter applies the focused fix chip, as a click does. --- crates/engine/src/tests/colorcontrast.rs | 3 +++ crates/ui-egui/src/panels/color_wheel.rs | 2 +- docs/mcp.md | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 6b43325d74..8a8c203488 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -899,6 +899,9 @@ fn a_fix_passes_as_the_canvas_paints_it() { 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}"); } diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 3181a5a903..ee1469a833 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -816,7 +816,7 @@ type Bands = Vec<(f32, FieldPoint, FieldPoint)>; /// field coordinates. The field is sampled on a grid of `n` + 1 columns and rows, and each cell /// whose corners fall on both sides gets a segment between the crossings on its edges, placed by /// bisection (marching squares; a cell with two opposite corners passing is split by its center). -/// With `bands`, around a failing sample higher than its neighbors in a column or a row, the highest +/// 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. Segments that share an end are joined into one /// polyline. diff --git a/docs/mcp.md b/docs/mcp.md index 8246023baa..b884e3e6b7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -698,7 +698,7 @@ box, `contrastFor` (`normalText`, `largeText` or `graphics`, which has AA only) `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, and when the color fails a level, a chip at the -end of the row shows `color.contrast`'s `fix` for the first level it fails; a click applies it. +end of the row shows `color.contrast`'s `fix` for the first level it fails; a click, or Enter while the chip has the focus, applies it. `{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel or the box. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences. From d26ae6f344f62ab7729abc0a0dc3bbe7df5a8a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:16:39 -0800 Subject: [PATCH 09/13] Color Wheel: contrast lines follow a widening band, show for a fill of None and hide under Alt - The contrast lines count a narrow band's crossings among a cell's crossings where no band on the next line joins it, so a band that widens past the samples is no longer cut across. - The lines show where a pick passes when the fill or stroke is None or a pattern (`contrast_pick_backdrop`), and are hidden while Alt sends a pick to the other proxy. - The Background chip shows the background the ratio uses, so a pinned 100 % K shows as black with a rich black Appearance of Black. - `color.contrast` with "below" is an error when a blend mode other than Normal mixes the color with art that is not one color where its level reads it; a blend inside an isolating group over such art still answers. - `wcag::closest_passing`, `color.contrast`'s params text and docs/mcp.md say that a nearer passing color can be missed when the passing lightnesses fall in more than one stretch, that a null fix shows no chip, and that a null `contrastBackground` sets Behind Selection. - The wide-gamut contrast test restores the color settings through `restored_settings()`. --- crates/color/src/wcag.rs | 5 +- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/colorcmds.rs | 93 +++++++++---- crates/engine/src/tests/colorcontrast.rs | 116 ++++++++++++++++ crates/engine/tests/color_settings.rs | 4 +- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 131 ++++++++++++------ .../src/panels/tests_color_wheel_contrast.rs | 29 ++-- .../tests_color_wheel_contrast_lines.rs | 54 +++++++- docs/mcp.md | 22 ++- 11 files changed, 370 insertions(+), 90 deletions(-) diff --git a/crates/color/src/wcag.rs b/crates/color/src/wcag.rs index 16b34bb166..ba5bb3b974 100644 --- a/crates/color/src/wcag.rs +++ b/crates/color/src/wcag.rs @@ -124,7 +124,10 @@ pub fn peak_between(mut lo: f64, mut hi: f64, f: &dyn Fn(f64) -> f64) -> f64 { /// 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. +/// 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 }); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fdc6abc838..f4ffaa239e 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -845,7 +845,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::{fold_source, print_hidden}; -pub use colorcmds::{Backdrop, contrast_measure}; +pub use colorcmds::{Backdrop, contrast_measure, contrast_pick_backdrop}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index f3f250dba1..064adcf1ef 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), for?: normalText|largeText|graphics (default normalText: the category `fix` answers for)} 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`), 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; null when the color already meets the level, or when no lightness of its hue does}", + "{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`), 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`), 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 ), @@ -1208,6 +1208,21 @@ pub fn contrast_measure(s: &Session, p: &Value) -> Result<(Value, Backdrop)> { /// The color `color.contrast` measures for params `p`, as stored (before a symbol's stain), and /// what it measures it against. fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { + let (color, backdrop) = contrast_reading(s, p, true)?; + let color = color.ok_or_else(|| bad("color.contrast", no_color()))?; + Ok((color, backdrop)) +} + +/// What a color picked for the active proxy would be measured against by `color.contrast` with +/// params `p` (without `color`), also when the proxy has no color to measure (None, a pattern): the +/// Color Wheel's contrast lines show where a pick would pass. +pub fn contrast_pick_backdrop(s: &Session, p: &Value) -> Result { + contrast_reading(s, p, false).map(|(_, backdrop)| backdrop) +} + +/// [`contrast_backdrop`], with None for the color when the proxy has none, which is an error when +/// `need_color`. +fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option, Backdrop)> { const C: &str = "color.contrast"; check_numbers(p, &["opacity"], C)?; let opacity = match p.get("opacity").and_then(Value::as_f64) { @@ -1222,18 +1237,25 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { 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| 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) => { @@ -1275,6 +1297,8 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { 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 && alpha >= 1.0 && alone >= 1.0 { continue; @@ -1283,19 +1307,29 @@ fn contrast_backdrop(s: &Session, p: &Value) -> Result<(Color, Backdrop)> { let scope = above.iter().find(|a| a.isolate); let full = above.iter().filter(|a| a.blend != BlendMode::Normal || a.opacity < 1.0).map(|a| &a.within).collect::>(); let read = |scope: Option<&Part>| color_below(s, rich_black, step.hide.as_ref(), &full, scope).map_err(|e| bad(C, e)); - let backdrop = match scope { - Some(_) if !sampled => ([0.0; 3], 0.0), - None if !sampled => (against, 1.0), + let (backdrop, one) = match scope { + Some(_) if !sampled => (([0.0; 3], 0.0), true), + None if !sampled => ((against, 1.0), uniform), // The background itself, as the answer writes it. - None if step.hide.is_none() && full.is_empty() => (against, 1.0), + None if step.hide.is_none() && full.is_empty() => ((against, 1.0), uniform), _ => read(scope.map(|a| &a.within))?, }; // The alpha of the art below the level inside the level around it, while a blending level // lies further out (none for a given background). - let inner = match above.first() { - Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => read(Some(&around.within))?.1, - _ => 0.0, + let (inner, inner_one) = match above.first() { + Some(around) if sampled && above.iter().take_while(|a| !a.isolate).any(blends) => { + let ((_, a), one) = read(Some(&around.within))?; + (a, one) + } + _ => (0.0, true), }; + // 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 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); @@ -1415,8 +1449,9 @@ fn draws_alike(a: &Drawn, b: &Drawn, given_opacity: bool, below: bool) -> bool { /// it is drawn ([`Drawn`]). With `given_opacity`, the opacities of the selected objects are not /// compared, since the given opacity takes their place; with `below` (the background is sampled), /// objects in different translucent or blending groups or layers differ, since the art below each -/// such level is read with it hidden. -fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, Drawn), String> { +/// such level is read with it hidden. The color is None when the proxy has none (None, a pattern), +/// and the drawing is then the one a solid color in its place would have. +fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Option, Drawn), String> { let stroke = !s.fill_active; let (fill_mixed, stroke_mixed) = s.proxy_mixed(); if if stroke { stroke_mixed } else { fill_mixed } { @@ -1471,20 +1506,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((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 @@ -1605,14 +1648,14 @@ fn enclosing(s: &Session, id: NodeId) -> Vec { /// hidden in place of the selection, or for [`Part::Rows`], the proxy's row and the rows above it; /// the objects of `full` draw at full opacity in Normal mode; and with `scope` (a group or layer /// around the selection, or the proxy's objects), only the art inside it is drawn, over nothing, -/// without artboards. +/// without artboards. Also whether the square's pixels are all one color. fn color_below( s: &Session, rich_black: bool, hide: Option<&Part>, full: &[&Part], scope: Option<&Part>, -) -> std::result::Result<([f32; 3], f32), String> { +) -> std::result::Result<(([f32; 3], f32), bool), String> { super::has_selection(s)?; let st = s.active().ok_or("no document open")?; let ids = st.selection.objects.clone(); @@ -1741,8 +1784,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 { @@ -1752,10 +1797,10 @@ fn color_below( } let alpha = sum[3] / (px.len() as f64 * 255.0); if alpha <= 0.0 { - return Ok(([0.0; 3], 0.0)); + return Ok((([0.0; 3], 0.0), uniform)); } let rgb = [0, 1, 2].map(|i| (sum[i] / (px.len() as f64 * 255.0) / alpha).clamp(0.0, 1.0) as f32); - Ok((rgb, alpha as f32)) + Ok(((rgb, alpha as f32), uniform)) } /// Hides fill or stroke row `item` of `n` (else its topmost row of the kind) and every row above it. diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 8a8c203488..7c2a5c838f 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -993,6 +993,122 @@ fn a_fix_is_drawn_at_the_same_opacity_and_none_passes_out_of_reach() { 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}"); + } + } + } +} + +/// 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(); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 61bfba6fb3..b388e8ef7b 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -944,8 +944,7 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { /// behind the selection, given back, answers the same ratio. #[test] fn contrast_writes_the_background_as_against_takes_it_with_another_working_space() { - let _g = settings(); - let before = cms::active_settings(); + let _g = restored_settings(); let mut s = session(); exec(&mut s, "edit.colorSettings", json!({"rgb": cms::WIDE_GAMUT_RGB})); let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#806040"})); @@ -957,7 +956,6 @@ fn contrast_writes_the_background_as_against_takes_it_with_another_working_space exec(&mut s, "paint.setFill", json!({"color": "#808080"})); let below = s.execute("color.contrast", &json!({})); let again = below.as_ref().ok().and_then(|b| s.execute("color.contrast", &json!({"against": b["against"].clone()})).ok()); - cms::set_active(&before).unwrap(); let given = given.unwrap(); assert_eq!(given["against"], "#806040", "{given}"); let (below, again) = (below.unwrap(), again.unwrap()); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index ae699a7629..70ffce9503 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1604,7 +1604,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, 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; 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; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, 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; 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; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 71d2ace197..726c717e09 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1605,7 +1605,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, 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; 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; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, 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; 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; contrast shows a row under the wheel or the box with the background's chip, the WCAG 2 contrast ratio cut off at two decimals and the AA and AAA results for contrastFor (AA only for graphics), as color.contrast answers them, and contrastBackground pins the background the row measures against (Contrast Background › Current Color; null: the color drawn behind the selection, Behind Selection); vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out keep their values ({} reads them), and so do keys given as null, except contrastBackground, which null sets to Behind Selection; params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index ee1469a833..c8187102da 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -66,7 +66,7 @@ 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}; +use vectorcraft_engine::cmd::{Backdrop, contrast_measure, contrast_pick_backdrop}; use super::color::{Target, apply, wheel_target}; use super::{color_json, pstate, set_pstate}; @@ -812,14 +812,20 @@ type FieldPoint = (f32, f32); /// 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 corners fall on both sides gets a segment between the crossings on its edges, placed by -/// bisection (marching squares; a cell with two opposite corners passing is split by its center). +/// 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. Segments that share an end are joined into one -/// polyline. +/// 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; @@ -850,28 +856,10 @@ pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64 }) }; let mut segments: Vec<[FieldPoint; 2]> = vec![]; - for i in 0..n { - for j in 0..n { - let (top, right, bottom, left) = (edge(i, j, true), edge(i + 1, j, false), edge(i, j + 1, true), edge(i, j, false)); - match (top, right, bottom, left) { - (Some(t), Some(rt), Some(b), Some(l)) => { - // Opposite corners pass: the center says which pair of them it joins. - let half = 0.5 / n as f32; - if pass((at(i) + half, at(j) + half)) == (r(i, j) >= min) { - segments.extend([[t, rt], [b, l]]); - } else { - segments.extend([[t, l], [rt, b]]); - } - } - _ => { - let found: Vec = [top, right, bottom, left].into_iter().flatten().collect(); - if let &[p, q] = found.as_slice() { - segments.push([p, q]); - } - } - } - } - } + // The crossings of the bands narrower than the samples on each edge between samples, with + // whether no band on the next line (the column to the right, the row below) and no band on + // the line before joins the band on that side. + let mut loose: HashMap> = HashMap::new(); // Bands narrower than the samples, along each column and then each row. for across in [false, true].into_iter().filter(|_| narrow) { let point = |k: usize, t: f32| if across { (t, at(k)) } else { (at(k), t) }; @@ -900,11 +888,62 @@ pub(super) fn contrast_lines(ratio_at: &dyn Fn(f32, f32) -> f64, minimums: &[f64 found }) .collect(); - for pair in bands.windows(2) { - let [this, next] = pair else { continue }; - for (peak, a, b) in this { - if let Some((_, c, d)) = next.iter().find(|(p, ..)| (p - peak).abs() <= 1.5 / n as f32) { - segments.extend([[*a, *c], [*b, *d]]); + // 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]); } } } @@ -1071,8 +1110,12 @@ fn measure(app: &VectorcraftApp, ui: &Ui) -> Measured { (Some((k, answer)), Some((kb, backdrop))) if k == key && kb == key => Measured { answer, backdrop }, _ => { let against = pinned.as_ref().map_or_else(|| json!("below"), color_json); - let m = contrast_measure(&app.session, &json!({ "against": against, "for": category.id() })).ok(); - let (answer, backdrop) = m.map_or((None, None), |(r, b)| (Some(r), Some(b))); + 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()), + }; set_pstate(ui.ctx(), RATIO, Some((key.clone(), answer.clone()))); set_pstate(ui.ctx(), BACKDROP, Some((key, backdrop.clone()))); Measured { answer, backdrop } @@ -1082,17 +1125,20 @@ fn measure(app: &VectorcraftApp, ui: &Ui) -> Measured { /// 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; a dash when there is no background or no color to measure. Without a pinned -/// background the first chip 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 fix chip keeps -/// its space while hidden. Returns the fix color when its chip is clicked. +/// color fails, when `color.contrast` finds one for that level; a dash when there is no background +/// or no color to measure. The first chip shows the background the answer measured against, pinned +/// or not, else the one a pick would be measured against. Only when there is neither is the +/// background read on its own ([`background`]), so the chip still shows it. The fix chip keeps its +/// space while hidden. Returns the fix color when its chip is clicked. fn contrast_row(app: &mut VectorcraftApp, ui: &mut Ui, m: &Measured) -> Option { let category = app.ui.color_wheel.contrast_for; let pinned = app.ui.color_wheel.contrast_background; let answer = m.answer.as_ref(); - // The background the ratio was measured against. - let measured = answer.filter(|_| pinned.is_none()).and_then(|r| r["against"].as_str()).and_then(Color::from_hex); - let chip = match pinned.or(measured) { + // The background the ratio was measured against, or a pick would be (a pinned 100 % K shows + // as black with a rich black Appearance of Black). + 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, ui), }; @@ -1654,7 +1700,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { set_pstate(ui.ctx(), ROWS_LIVE, None::); } if let Some(m) = &measured { - if let Some(backdrop) = &m.backdrop { + // With Alt held a pick goes to the other proxy, which the lines do not measure. + if let Some(backdrop) = m.backdrop.as_ref().filter(|_| !super::alt_held(ui)) { let lines = lines_for(app, ui, backdrop, &tgt, hsb, cmyk_doc); draw_contrast_lines(ui, field_rect, &lines); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index aea80f72d8..1a1606a5bc 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -125,6 +125,18 @@ fn the_background_is_the_art_behind_the_selection() { assert_eq!(chip.value().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 h = harness(app); + assert!(shows(&h, "21.00:1"), "white on black"); + assert_eq!(h.get_by_label("Background").value().as_deref(), Some("000000")); +} + #[test] fn nothing_selected_and_nothing_pinned_shows_no_ratio() { let mut app = app("#000000"); @@ -186,8 +198,8 @@ fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() { assert_eq!(measured(&h).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()); @@ -203,12 +215,13 @@ fn a_paint_with_no_color_still_shows_the_background() { app.run("ui.colorWheel", json!({"contrast": true})).unwrap(); let mut h = harness(app); assert!(shows(&h, "—"), "a fill of None has no ratio"); - let hex = |h: &Harness<'static, VectorcraftApp>| behind(h).and_then(|(_, hex)| hex); - assert_eq!(hex(&h).as_deref(), Some("#ffff00")); + let hex = |h: &Harness<'static, VectorcraftApp>| h.get_by_label("Background").value(); + assert_eq!(hex(&h).as_deref(), Some("FFFF00")); + assert!(behind(&h).is_none(), "the background a pick is measured against was not read again on its own"); h.state_mut().run("select.set", json!({"ids": [b]})).unwrap(); h.state_mut().session.begin_interaction("test").unwrap(); h.run_steps(2); - assert_eq!(hex(&h).as_deref(), Some("#ffffff"), "the other selection's background is read during the interaction"); + assert_eq!(hex(&h).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 @@ -224,14 +237,14 @@ 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 h = harness(app); - let hex = |h: &Harness<'static, VectorcraftApp>| behind(h).and_then(|(_, hex)| hex); + let hex = |h: &Harness<'static, VectorcraftApp>| h.get_by_label("Background").value(); h.state_mut().session.begin_interaction("test").unwrap(); h.run_steps(2); - assert_eq!(hex(&h).as_deref(), Some("#ffff00")); + assert_eq!(hex(&h).as_deref(), Some("FFFF00")); h.state_mut().run("object.move", json!({"dx": 110, "dy": 0})).unwrap(); assert!(h.state().session.in_interaction(), "the move is part of the interaction"); h.run_steps(2); - assert_eq!(hex(&h).as_deref(), Some("#ffffff"), "the background at the new place"); + assert_eq!(hex(&h).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 diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs index d8501b6351..698bb07426 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast_lines.rs @@ -1,15 +1,15 @@ //! 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. -use egui::vec2; +use egui::{Event, Modifiers, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; use vectorcraft_color::{Color, Paint, cms, hsb_to_rgb}; use vectorcraft_engine::Session; -use super::color_wheel::{LINES, Lines, LinesKey, box_pick, show}; -use super::pstate; +use super::color_wheel::{LINES, Lines, LinesKey, box_pick, contrast_lines, show}; +use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; @@ -115,6 +115,54 @@ fn a_line_that_runs_up_the_field_is_found() { 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::>(); + 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 h = harness(app); + assert!(h.query_by_label("—").is_some(), "no color to measure"); + let lines = lines(&h); + 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 h = harness(app("box", "hue")); + set_pstate(&h.ctx, LINES, None::<(LinesKey, Lines)>); + h.event(Event::ModifiersChanged(Modifiers::ALT)); + h.run_steps(2); + assert!(pstate::>(&h.ctx, LINES).is_none(), "no lines with Alt held"); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert!(pstate::>(&h.ctx, LINES).is_some(), "the lines are back"); +} + #[test] fn graphics_have_one_line() { let mut app = app("box", "saturation"); diff --git a/docs/mcp.md b/docs/mcp.md index b884e3e6b7..d57f88be22 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -692,13 +692,17 @@ whole cell or none of it, so a grayed cell can hold printable colors and a clear print. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or -`highContrast2`). Keys left out keep their values. Params that are not an object, another key or a value off +`highContrast2`). 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, and when the color fails a level, a chip at the -end of the row shows `color.contrast`'s `fix` for the first level it fails; a click, or Enter while the chip has the focus, applies it. +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. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, contrast, contrastFor, contrastBackground, vision, documentColors}`, and the settings are kept with the preferences. @@ -1220,7 +1224,10 @@ selected objects that draw one color with different blend modes, or at different with a translucent or blending row over different shown rows below it), 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 @@ -1231,8 +1238,11 @@ color that meets it when drawn the same way, in the model of the measured color, 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. 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). +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 From 8ede10f809d0d51fdf3b40e984f8fb4b37a527fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:15:35 -0800 Subject: [PATCH 10/13] Color Wheel: the contrast drag test drags the hue ring A drag on the wheel's inner square sets the color without a preview interaction, so the test drags the ring, which previews on one. --- crates/ui-egui/src/panels/tests_color_wheel_contrast.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs index dc8bf6a825..2f938cc8e2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_contrast.rs @@ -187,11 +187,14 @@ fn a_drag_on_the_wheel_reads_the_background_only_with_the_ratio() { assert!(behind(&p).is_none(), "the answer gave the background"); 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); - let at = p.node("Saturation and brightness").center(); - p.fx.drag_hold_at(at, egui::vec2(24.0, 0.0)); + // 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"); assert_ne!(ratio(&p), first, "the row asked again for the previewed color"); - p.fx.release_at(at + egui::vec2(24.0, 0.0)).idle(2); + 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")); From 1af9fe50d37d1f3e9472e53fb7d3255fc4b1683a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:14:07 -0800 Subject: [PATCH 11/13] Color Wheel: objects that differ in isolation over a blending lower row have no one answer A translucent or blending row drawn over a lower row that blends reads the art behind the object only when the object does not isolate its blending. Selected objects that differ only in isolation then draw the color over different rows, so color.contrast reports that their colors differ instead of measuring both with the first object's isolation. A blending row at no opacity, or a fill row covered by an opaque solid Normal fill row, does not count. --- crates/engine/src/cmd/colorcmds.rs | 19 ++++++++- crates/engine/src/tests/colorcontrast.rs | 49 ++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 4475897d9a..5bcbb930c9 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1418,7 +1418,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| { @@ -1434,10 +1435,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() diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 7c2a5c838f..609aa9189e 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -1036,6 +1036,55 @@ fn isolation_leaves_a_translucent_normal_row_as_it_draws() { } } +/// 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. diff --git a/docs/mcp.md b/docs/mcp.md index 2787bc8791..0f2326bf51 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1236,7 +1236,8 @@ 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; and with `"below"`, a color drawn with a From 5552e8a0151938daed134ae02d7129a5a2019d53 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:55:54 -0800 Subject: [PATCH 12/13] Color Wheel: contrast measures a painting tool's color without the selection's drawing While the Live Paint Bucket or the Shape Builder is the active tool, the proxy shows the color the tool paints with, so color.contrast no longer takes the selected objects' opacities and blend modes for it, and selected objects drawn differently are no longer an error. This brings the change from #9358 onto this branch. --- crates/engine/src/cmd/colorcmds.rs | 7 ++++--- crates/engine/src/tests/colorcontrast.rs | 25 ++++++++++++++++++++++++ docs/mcp.md | 2 ++ 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 28121554ab..49aec43594 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Contrast", [], None, - "{color?: a color (#rrggbbaa and #rgba are refused; default the active Fill or Stroke proxy's color, or its selected gradient stop or freeform point, or a gradient mesh's first picked point; a picked object's solid color mixed towards the fill that stains its dynamic symbol instance), against?: a color or \"below\" (default: the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it without template layers and guides; a picked object of a dynamic symbol instance hides only itself and is measured at its own center; needs a selection), opacity?: 0..100 (default the opacity the proxy's color is drawn with: the object's opacity times that of its groups and layer (for a picked symbol object, also of its instance and the groups of the symbol's art around it), its fill's or stroke's row (not for type's character paint) and a stop's or point's own, a translucent group or layer drawing the art inside it, the art behind the object included, over what is outside it; 100 for a given `color`), 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`), 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}", + "{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 ), @@ -1496,8 +1496,9 @@ fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Re .transpose() }; let drawing; - // Selected objects that share a color but draw it differently have no one answer. - if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) { + // Selected objects that share a color but draw it differently have no one answer. While the + // active tool paints with the proxy's color, the selection does not draw it. + if let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none() && !s.tool_paints(stroke)) { let item = s.appearance_item(); // Every painted object inside a selected group counts, as the proxy's color comes from all, // except hidden ones and those inside a hidden group, which draw nothing. The first shown diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index 609aa9189e..fdcc6264dc 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -68,6 +68,31 @@ fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() { assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}"); } +/// While the Live Paint Bucket is the active tool, the proxy shows the color it paints with, so the +/// selected objects' opacities and blend modes do not apply, and objects drawn differently are no +/// error. +#[test] +fn the_live_paint_bucket_color_is_measured_without_the_selections_drawing() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("transparency.set", &json!({"opacity": 50, "blend": "multiply"})).unwrap(); + let selection = ratio(&s.execute("color.contrast", &json!({})).unwrap()); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + let bucket = s.execute("color.contrast", &json!({})).unwrap(); + assert!(ratio(&bucket) > selection, "the bucket's black is drawn opaque: {bucket} against {selection}"); + assert!((ratio(&bucket) - 21.0).abs() < 1e-3, "{bucket}"); + // A second selected object drawn at another opacity does not make the answer ambiguous. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let both = s.execute("color.contrast", &json!({})).unwrap(); + assert!((ratio(&both) - ratio(&bucket)).abs() < 1e-3, "{both}"); +} + #[test] fn a_translucent_group_counts_for_the_art_inside_it() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 5cd7a16596..cd97824036 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1229,6 +1229,8 @@ the art below it inside the object, groups and layer around it, the object's row the background when `against` or `opacity` is given; inside an object, group or layer that isolates its blending, the modes blend only with the art it holds); `opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque. +While the active tool paints with the proxy's color (the Live Paint Bucket, the Shape Builder's fill), that color is +drawn the same way, and the selected objects' opacities and blend modes do not apply. `against` takes a color, or `"below"` (the default, also for `null`): the color VectorCraft draws at the center of the selection's bounds with the selected objects hidden, as the canvas shows it (locked art, opacity, blend modes and images included; template layers and guides left out, as exports leave them out; the artboard's white where nothing From 4ec043813a762bef287bf4f86fcf337d1f84bbda Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 18:33:32 -0800 Subject: [PATCH 13/13] Color Wheel: contrast lines stain picks for a symbol object with no fill With a picked object of a dynamic symbol instance whose fill or stroke is None or a pattern, the contrast lines measured picks unstained, although a solid pick there is mixed towards the instance's stain when drawn. Picks are now measured with the stain, as for a solid color; gradients are still measured unstained. --- crates/engine/src/cmd/colorcmds.rs | 13 ++++++++----- crates/engine/src/tests/colorcontrast.rs | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 49aec43594..b046c85090 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -1341,7 +1341,7 @@ fn contrast_reading(s: &Session, p: &Value, need_color: bool) -> Result<(Option< (_, alpha, alone) = pass.draw(([0.0; 3], alpha, alone)); passes.push(pass); } - let stain = if given { None } else { stain_of(s) }; + let stain = if given { None } else { stain_of(s, !need_color) }; Ok((color, Backdrop { against, written, passes, stain, rich_black })) } @@ -1619,11 +1619,14 @@ fn drawn_settings(s: &Session, n: &Node, item: Option, stroke: bool) -> s /// 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. -fn stain_of(s: &Session) -> Option<(Color, f32)> { +/// 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(); - if !matches!(if s.fill_active { fill } else { stroke }, Paint::Solid { .. }) { - return None; + 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()?; diff --git a/crates/engine/src/tests/colorcontrast.rs b/crates/engine/src/tests/colorcontrast.rs index fdcc6264dc..fecd16ed2a 100644 --- a/crates/engine/src/tests/colorcontrast.rs +++ b/crates/engine/src/tests/colorcontrast.rs @@ -786,6 +786,25 @@ fn a_picked_symbol_object_is_measured_with_its_instances_stain() { 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] fn a_picked_symbol_object_is_drawn_at_its_instances_opacity() { let mut s = picked_symbol_part();