From d26ae6f344f62ab7729abc0a0dc3bbe7df5a8a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 08:16:39 -0800 Subject: [PATCH] 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