Color Wheel: Show Contrast reports the WCAG contrast against the color behind the selection

The Color Wheel panel menu gains Show Contrast, Contrast For (Normal Text,
Large Text, Graphics) and Contrast Background (Behind Selection, Current
Color). Show Contrast adds 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 the chosen category.

The new color.contrast query answers the ratio and the results for a color
(by default the active Fill or Stroke proxy's color, at the opacity and
with the blend modes it is drawn with) against a given color or the color
drawn behind the selection. ui.colorWheel takes contrast, contrastFor and
contrastBackground, kept with the preferences. vectorcraft-color gains a
wcag module with the relative luminance and contrast ratio definitions
(https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio).

Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-14 16:24:33 -08:00
1 parent e397a3d28d
commit b437355d5d
45 files changed
+1922 -23

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ pub mod libraries;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
pub mod wcag;
pub use blend::BlendMode;
pub use freeform::{Freeform, FreeformMode, FreeformPoint};
+146
View File
@@ -0,0 +1,146 @@
//! Contrast between two colors as WCAG 2 measures it (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>):
//! 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).
/// What the content in front is, which sets the ratio it needs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Category {
/// Text below the large-scale size: AA 4.5:1, AAA 7:1.
#[default]
NormalText,
/// Large-scale text (at least 18 pt, or 14 pt bold): AA 3:1, AAA 4.5:1.
LargeText,
/// User interface components and graphical objects: AA 3:1, no AAA level.
Graphics,
}
impl Category {
pub const ALL: [Category; 3] = [Category::NormalText, Category::LargeText, Category::Graphics];
/// The id commands and settings use.
pub fn id(self) -> &'static str {
match self {
Category::NormalText => "normalText",
Category::LargeText => "largeText",
Category::Graphics => "graphics",
}
}
pub fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|c| c.id() == s)
}
/// The English name shown in menus.
pub fn label(self) -> &'static str {
match self {
Category::NormalText => "Normal Text",
Category::LargeText => "Large Text",
Category::Graphics => "Graphics",
}
}
/// The minimum ratio for AA, and for AAA where the category has that level.
pub fn minimums(self) -> (f64, Option<f64>) {
match self {
Category::NormalText => (4.5, Some(7.0)),
Category::LargeText => (3.0, Some(4.5)),
Category::Graphics => (3.0, None),
}
}
/// Whether `ratio` meets AA, and AAA where the category has that level. The unrounded ratio
/// is compared, so 4.499:1 fails 4.5:1.
pub fn passes(self, ratio: f64) -> (bool, Option<bool>) {
let (aa, aaa) = self.minimums();
(ratio >= aa, aaa.map(|m| ratio >= m))
}
}
/// The relative luminance of display sRGB `srgb` (each channel 0 to 1), from 0 for black to 1
/// for white.
pub fn relative_luminance(srgb: [f32; 3]) -> f64 {
let lin = |v: f32| {
let v = f64::from(v.clamp(0.0, 1.0));
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * lin(srgb[0]) + 0.7152 * lin(srgb[1]) + 0.0722 * lin(srgb[2])
}
/// The contrast ratio of display sRGB colors `a` and `b`, from 1 to 21, whichever is lighter.
pub fn contrast_ratio(a: [f32; 3], b: [f32; 3]) -> f64 {
let (la, lb) = (relative_luminance(a), relative_luminance(b));
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}
/// Display sRGB `fg` drawn at `opacity` (0 to 1) over the opaque `bg`, mixed per channel as the
/// canvas mixes a translucent color.
pub fn over(fg: [f32; 3], opacity: f32, bg: [f32; 3]) -> [f32; 3] {
let a = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 };
std::array::from_fn(|i| fg[i] * a + bg[i] * (1.0 - a))
}
/// `ratio` as text with two decimals, cut off rather than rounded, so a ratio just under a
/// minimum never reads as the minimum: 4.4963 is "4.49:1".
pub fn ratio_text(ratio: f64) -> String {
let r = if ratio.is_finite() { ratio.clamp(1.0, 21.0) } else { 1.0 };
format!("{:.2}:1", (r * 100.0).floor() / 100.0)
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(s: &str) -> [f32; 3] {
let v = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).map_or(0.0, |b| f32::from(b) / 255.0);
[v(0), v(2), v(4)]
}
#[test]
fn black_on_white_is_21_and_a_color_on_itself_is_1() {
assert!((contrast_ratio(hex("000000"), hex("ffffff")) - 21.0).abs() < 1e-9);
assert!((contrast_ratio(hex("ffffff"), hex("000000")) - 21.0).abs() < 1e-9);
assert!((contrast_ratio(hex("355f78"), hex("355f78")) - 1.0).abs() < 1e-12);
}
#[test]
fn ratios_near_a_minimum_are_compared_unrounded_and_cut_off_in_text() {
let r = contrast_ratio(hex("fdc96e"), hex("355f78"));
assert!((r - 4.4963).abs() < 1e-3, "{r}");
assert_eq!(ratio_text(r), "4.49:1");
assert_eq!(Category::NormalText.passes(r), (false, Some(false)));
assert_eq!(Category::LargeText.passes(r), (true, Some(false)));
let gray = contrast_ratio(hex("767676"), hex("ffffff"));
assert!((gray - 4.542).abs() < 1e-3, "{gray}");
assert_eq!(ratio_text(gray), "4.54:1");
assert!(Category::NormalText.passes(gray).0);
let lighter = contrast_ratio(hex("777777"), hex("ffffff"));
assert!((lighter - 4.478).abs() < 1e-3, "{lighter}");
assert_eq!(ratio_text(lighter), "4.47:1");
assert!(!Category::NormalText.passes(lighter).0);
assert_eq!(ratio_text(21.0), "21.00:1");
assert_eq!(ratio_text(f64::NAN), "1.00:1");
}
#[test]
fn graphics_have_no_aaa_level() {
assert_eq!(Category::Graphics.passes(3.0), (true, None));
assert_eq!(Category::Graphics.passes(2.99), (false, None));
assert_eq!(Category::LargeText.passes(4.5), (true, Some(true)));
}
#[test]
fn category_ids_parse_back() {
for c in Category::ALL {
assert_eq!(Category::parse(c.id()), Some(c));
}
assert_eq!(Category::parse("NormalText"), None);
}
#[test]
fn half_opaque_black_over_white_is_mid_gray() {
assert_eq!(over([0.0; 3], 0.5, [1.0; 3]), [0.5; 3]);
assert_eq!(over([0.2; 3], f32::NAN, [1.0; 3]), [0.2; 3]);
assert_eq!(over([0.2; 3], 2.0, [1.0; 3]), [0.2; 3]);
}
}
+336 -1
View File
@@ -14,7 +14,8 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::cms::Model;
use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation};
use vectorcraft_color::{Color, Paint, keep_model};
use vectorcraft_color::wcag::{self, Category};
use vectorcraft_color::{BlendMode, Color, Paint, keep_model};
use vectorcraft_doc::live::lerp_color;
use vectorcraft_doc::pattern::PatternDef;
pub(crate) use vectorcraft_doc::recolor::map_paint;
@@ -135,6 +136,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
harmony
),
cmd!(
query "color.contrast",
"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}}",
always,
contrast
),
]
}
@@ -973,3 +983,328 @@ fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
let hex = |cs: &[Color]| cs.iter().map(Color::to_hex).collect::<Vec<_>>();
Ok(json!({ "rule": rule.id(), "colors": hex(&g.colors), "grid": g.grid.iter().map(|r| hex(r)).collect::<Vec<_>>() }))
}
/// The side, in points, of the square [`color_below`] renders.
const BELOW_SIDE: f64 = 1.0;
/// The pixels per point [`color_below`] renders at.
const BELOW_SCALE: f64 = 4.0;
fn contrast(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.contrast";
check_numbers(p, &["opacity"], C)?;
let opacity = match p.get("opacity").and_then(Value::as_f64) {
Some(o) if (0.0..=100.0).contains(&o) => Some(o as f32 / 100.0),
Some(_) => {
let key = "opacity";
return Err(bad(C, format!("`{key}` must be from 0 to 100")));
}
None => None,
};
let below = p.get("against").is_none_or(|v| v.is_null() || v.as_str() == Some("below"));
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 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) {
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).map_err(|e| bad(C, e))?));
(cms.rgb_to_srgb(working.map(|v| f32::from(v) / 255.0)), working)
}
Some(v) => {
let key = "against";
let shown = shown(&color_value(v).ok_or_else(|| bad(C, format!("`{key}` must be a color or {}", "\"below\"")))?);
(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)
}
};
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),
}))
}
/// The opacity of each object around the proxy's object that draws it, innermost first, with the
/// object to hide to read what is outside it (`None` for a group of a symbol's art).
type Around = Vec<Level>;
/// One object of [`Around`]: its opacity and the object to hide.
type Level = (f32, Option<NodeId>);
/// The active proxy's color (its selected gradient stop or freeform point, else the first), the
/// opacity it is drawn with inside its object: the object's opacity times that of its fill or
/// stroke row (none for type's character paint or a colorize color) and of a stop or point, the
/// blend modes it is drawn with, innermost first ([`drawn_modes`]), and the opacities of the groups
/// and layer around the object ([`Around`]). 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 groups or layers differ, since each
/// such level is hidden to read what is outside it.
fn proxy_color(s: &Session, given_opacity: bool, below: bool) -> std::result::Result<(Color, f32, Vec<BlendMode>, Around), String> {
let stroke = !s.fill_active;
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
if if stroke { stroke_mixed } else { fill_mixed } {
return Err("the selected objects' colors differ: give `color`".into());
}
let (fill, stroke_paint) = s.proxy_paints();
let source = || s.proxy_source(stroke).map(|(n, item)| drawn_settings(s, &n, item, stroke)).transpose();
let (layer, mode, around);
// 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()) {
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
// one gives the opacity and blend modes the answer uses.
let shown = |id: NodeId| st.doc.ancestry(id).unwrap_or_default().iter().all(|a| st.doc.node(*a).is_some_and(|x| x.visible));
let mut drawn = vec![];
for n in st.selection.subjects().iter().filter_map(|id| st.doc.node(*id)) {
for (n, item) in shown_sources(n, item, stroke).into_iter().filter(|(c, _)| shown(c.id)) {
drawn.push(drawn_settings(s, n, item, stroke)?);
}
}
(layer, mode, around) = match drawn.first() {
Some(first) => first.clone(),
None => source()?.unwrap_or((1.0, vec![], vec![])),
};
// Only the groups and layers that draw at less than full opacity change the answer.
let translucent = |a: &Around| a.iter().filter(|x| x.0 < 1.0).copied().collect::<Vec<_>>();
let levels = translucent(&around);
let same = |(o, m, a): &(f32, Vec<BlendMode>, Around)| {
let a = translucent(a);
let level = |x: &Level, y: &Level| (x.0 - y.0).abs() < 1e-6 && (!below || x.1 == y.1);
let opacities = given_opacity || ((o - layer).abs() < 1e-6 && a.len() == levels.len() && a.iter().zip(&levels).all(|(x, y)| level(x, y)));
*m == mode && opacities
};
if !drawn.iter().all(same) {
return Err("the selected objects' colors differ: give `color`".into());
}
} else {
(layer, mode, around) = source()?.unwrap_or((1.0, vec![], vec![]));
}
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::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, layer * pt.opacity, mode, around)).ok_or_else(no_color)
}
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, layer * st.opacity, mode, around)).ok_or_else(no_color)
}
Paint::None | Paint::Pattern { .. } => Err(no_color()),
}
}
/// The objects whose fill or stroke the proxy shows for selected object `n`, with the appearance
/// item each shows: `n` itself when it holds such an item, else every painted object inside it
/// ([`Session::proxy_source`] shows the first).
fn shown_sources(n: &Node, item: Option<usize>, stroke: bool) -> Vec<(&Node, Option<usize>)> {
if n.appearance.item_of_kind(item, !stroke).is_some() {
return vec![(n, item)];
}
let mut nodes = vec![];
super::paint::painted(n, true, &mut nodes);
nodes.into_iter().map(|c| (c, None)).collect()
}
/// How object `n` draws its fill or stroke (`item`, else the proxy's row): its opacity times that of
/// the row (none for type's character paint or a colorize color), the blend modes, innermost first
/// ([`drawn_modes`]), and the groups and layer around it ([`Around`]). An error for a hidden row.
fn drawn_settings(s: &Session, n: &Node, item: Option<usize>, stroke: bool) -> std::result::Result<(f32, Vec<BlendMode>, Around), String> {
let item = n.appearance.item_of_kind(item, !stroke);
// Without a targeted row, type shows its characters' paint and a colorized image its
// colorize color, which no fill or stroke row's opacity applies to.
let own_paint = item.is_none() && (matches!(n.kind, NodeKind::Text(_)) || (!stroke && n.extras().colorize.is_some()));
let own = match (own_paint, stroke) {
(true, _) => None,
(false, true) => n.appearance.stroke_at(item).map(|l| (l.opacity, l.blend, l.visible)),
(false, false) => n.appearance.fill_at(item).map(|l| (l.opacity, l.blend, l.visible)),
};
if own.is_some_and(|o| !o.2) {
return Err("the active fill or stroke is hidden: give `color`".to_string());
}
// The groups and layer the object is in draw it at their opacity too (`outer` lists the
// outermost first).
let outer = enclosing(s, n.id);
let opacity = n.opacity * own.map_or(1.0, |o| o.0);
let around: Around = outer.iter().rev().map(|a| (a.0, a.3)).collect();
// Innermost first: the row (which the object holds), the object, then its groups and layer.
let levels = own.map(|o| (o.1, false)).into_iter().chain([(n.blend, n.isolate)]).chain(outer.iter().rev().map(|a| (a.1, a.2)));
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 blend modes that apply to a color drawn through `levels` (each a blend mode and whether that
/// level isolates the blending inside it, innermost first), innermost first. Inside a level that
/// does not isolate, blending reaches the art below, so each mode blends the result of the ones
/// inside it with the background; inside one that does, the art is blended with nothing, so the
/// modes inside the outermost isolating level do not apply.
fn drawn_modes(levels: Vec<(BlendMode, bool)>) -> Vec<BlendMode> {
let first = levels.iter().rposition(|l| l.1).unwrap_or(0);
levels.into_iter().skip(first).map(|l| l.0).filter(|m| *m != BlendMode::Normal).collect()
}
/// The opacity, blend mode and isolation of each object that draws the proxy's object `id`, with
/// its id in the document (`None` for a group of a symbol's art), outermost first: its groups and
/// layer, and for a picked object of a dynamic symbol instance, the instance, its groups and layer,
/// and the groups of the symbol's art around the object.
fn enclosing(s: &Session, id: NodeId) -> Vec<(f32, BlendMode, bool, Option<NodeId>)> {
let Some(st) = s.active() else { return vec![] };
let doc = &st.doc;
// `ancestry` lists the object itself last.
let in_doc = |id: NodeId, own: bool| {
let ids = doc.ancestry(id).unwrap_or_default();
let nodes = ids.into_iter().filter(|a| own || *a != id).filter_map(|a| doc.node(a));
nodes.map(|a| (a.opacity, a.blend, a.isolate, Some(a.id))).collect::<Vec<_>>()
};
let Some(sp) = st.selection.symbol_part.as_ref() else { return in_doc(id, false) };
let art = doc.node(sp.instance).and_then(|inst| {
let NodeKind::SymbolInstance { symbol, .. } = &inst.kind else { return None };
let sym = doc.symbols.iter().find(|s| s.name == *symbol)?;
Some(vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, inst))
});
// Without the picked object, the proxy shows the selected object itself (`proxy_source`).
let Some(art) = art.filter(|a| vectorcraft_doc::symbol_overrides::part(a, &sp.path).is_some()) else { return in_doc(id, false) };
let mut out = in_doc(sp.instance, true);
if let Some((_, groups)) = sp.path.split_last() {
// The art's root and each group on the way to the object, not the object itself.
let mut n = &art;
out.push((n.opacity, n.blend, n.isolate, None));
for &i in groups {
let Some(c) = n.children().and_then(|c| c.get(usize::try_from(i).ok()?)) else { break };
n = c;
out.push((n.opacity, n.blend, n.isolate, None));
}
}
out
}
/// The display sRGB VectorCraft draws at the center of the selection's bounds with the selected
/// objects hidden: the average of a small square rendered as the canvas renders it (artboards, the
/// on-screen Appearance of Black, no proof, no template layers or guides), over white where nothing
/// is drawn. With `instead`, that object (a group or layer around the selection) is hidden in place
/// of the selection.
fn color_below(s: &Session, rich_black: bool, instead: Option<NodeId>) -> std::result::Result<[f32; 3], String> {
super::has_selection(s)?;
let st = s.active().ok_or("no document open")?;
let ids = st.selection.objects.clone();
// A picked object of a dynamic symbol instance hides only itself: the rest of the instance
// stays in the sample, measured at the object's center.
let part = st.selection.symbol_part.as_ref().and_then(|sp| {
let inst = st.doc.node(sp.instance)?;
let center = kurbo::Shape::bounding_box(&vectorcraft_doc::hit::symbol_part_outline(&st.doc, inst, &sp.path)?).center();
let copy = if instead.is_some() { None } else { Some(without_symbol_part(&st.doc, sp)?) };
Some((center, copy))
});
let center = match &part {
Some((center, _)) => *center,
None => st.doc.bounds_of(&ids, false).ok_or("nothing selected")?.center(),
};
let (doc, hidden) = match (&part, instead) {
(_, Some(id)) => (&*st.doc, vec![id]),
(Some((_, Some(copy))), None) => (copy, vec![]),
_ => (&*st.doc, ids),
};
let h = BELOW_SIDE / 2.0;
let region = vectorcraft_geom::Rect::new(center.x - h, center.y - h, center.x + h, center.y + h);
// Template layers and guides are aids to drawing, not artwork: left out as exports leave them.
let opts = vectorcraft_render::RenderOptions {
background: Some([255, 255, 255, 255]),
artboards: true,
hidden,
rich_black,
skip_templates: true,
..Default::default()
};
let img = vectorcraft_render::Renderer::new().render_region_with(doc, region, BELOW_SCALE, &opts);
let px = img.pixels.as_chunks::<4>().0;
if px.is_empty() {
return Ok([1.0; 3]);
}
// Over the opaque background every pixel is opaque, so premultiplied values are the colors.
let mut sum = [0.0f64; 3];
for p in px {
for (s, v) in sum.iter_mut().zip(p) {
*s += f64::from(*v);
}
}
Ok(sum.map(|v| (v / (px.len() as f64 * 255.0)) as f32))
}
/// A copy of `doc` in which the instance of `sp` shows its symbol's art without the picked object:
/// the instance draws a copy of the symbol whose object at `sp.path` is hidden, so other instances
/// of the symbol keep it. `None` when the instance or the object is not found.
fn without_symbol_part(doc: &Document, sp: &vectorcraft_doc::SymbolPart) -> Option<Document> {
let NodeKind::SymbolInstance { symbol, .. } = &doc.node(sp.instance)?.kind else { return None };
let mut sym = doc.symbols.iter().find(|s| s.name == *symbol)?.clone();
vectorcraft_doc::symbol_overrides::part(&sym.art, &sp.path)?;
let mut n = Arc::make_mut(&mut sym.art);
for &i in &sp.path {
n = Arc::make_mut(n.children_mut()?.get_mut(usize::try_from(i).ok()?)?);
}
n.visible = false;
let mut out = doc.clone();
sym.name = unique_name(&sym.name, |name| out.symbols.iter().any(|s| s.name == name));
let name = sym.name.clone();
out.symbols.push(sym);
if let NodeKind::SymbolInstance { symbol, .. } = &mut out.node_mut(sp.instance)?.kind {
*symbol = name;
}
Some(out)
}
@@ -702,6 +702,7 @@ pub(super) const DENIED: &[&str] = &[
"addon.cleanup.splitText",
"addon.pathtools.movePointsTogether",
"addon.pen.nextSegment",
"color.contrast",
"effect.refreshDeferred",
"graphicStyle.setOptions",
"object.blend.createSpine",
+1
View File
@@ -30,6 +30,7 @@ mod clipflavours;
mod clippaint;
mod cmdsplit;
mod cmykflatten;
mod colorcontrast;
mod colorguide;
mod colorguidelib;
mod colorize;
+443
View File
@@ -0,0 +1,443 @@
//! `color.contrast`: the WCAG 2 contrast of a color against the color behind the selection.
use serde_json::{Value, json};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
s
}
fn ratio(r: &Value) -> f64 {
r["ratio"].as_f64().unwrap()
}
#[test]
fn a_pair_just_under_aa_fails_it() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#fdc96e", "against": "#355f78"})).unwrap();
assert!((ratio(&r) - 4.496).abs() < 1e-3, "{r}");
assert_eq!(r["against"], "#355f78");
assert_eq!(r["normalText"], json!({"aa": false, "aaa": false}));
assert_eq!(r["largeText"], json!({"aa": true, "aaa": false}));
assert_eq!(r["graphics"], json!({"aa": true}), "graphics have no AAA level");
assert_eq!(vectorcraft_color::wcag::ratio_text(ratio(&r)), "4.49:1");
}
#[test]
fn black_on_white_is_21_and_grays_fall_either_side_of_aa() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
assert_eq!(r["normalText"], json!({"aa": true, "aaa": true}));
let pass = s.execute("color.contrast", &json!({"color": "#767676", "against": "#ffffff"})).unwrap();
assert!((ratio(&pass) - 4.542).abs() < 1e-3 && pass["normalText"]["aa"] == true, "{pass}");
let fail = s.execute("color.contrast", &json!({"color": "#777777", "against": "#ffffff"})).unwrap();
assert!((ratio(&fail) - 4.478).abs() < 1e-3 && fail["normalText"]["aa"] == false, "{fail}");
}
#[test]
fn the_background_is_the_locked_art_behind_the_selected_type() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 80})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ffff00"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
s.execute("text.create", &json!({"x": 60, "y": 70, "text": "Label", "size": 24, "color": "#000000"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ffff00", "{r}");
let want = vectorcraft_color::wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]);
assert!((ratio(&r) - want).abs() < 1e-3, "{r}");
}
#[test]
fn a_translucent_fill_counts_at_the_opacity_it_is_drawn_with() {
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})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ffffff", "the selected rectangle is hidden: the artboard's white shows");
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "{r}");
// A given opacity replaces it, and a given color is drawn fully opaque.
let full = s.execute("color.contrast", &json!({"opacity": 100})).unwrap();
assert!((ratio(&full) - 21.0).abs() < 1e-3, "{full}");
let given = s.execute("color.contrast", &json!({"color": "#000000"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-3, "{given}");
}
#[test]
fn a_translucent_group_counts_for_the_art_inside_it() {
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("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the group draws the black at 50 %: {r}");
}
#[test]
fn a_blend_mode_counts_as_it_draws_over_the_background() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).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": "multiply"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ff0000", "{r}");
assert!((ratio(&r) - 1.0).abs() < 1e-3, "white multiplied over red draws red: {r}");
// A group's blend mode counts for the art inside it, and a given color draws in Normal mode.
s.execute("transparency.set", &json!({"blend": "normal"})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "multiply"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 1.0).abs() < 1e-3, "{r}");
let given = s.execute("color.contrast", &json!({"color": "#ffffff"})).unwrap();
let want = vectorcraft_color::wcag::contrast_ratio([1.0; 3], [1.0, 0.0, 0.0]);
assert!((ratio(&given) - want).abs() < 1e-3, "{given}");
}
/// A selected blue square at (50, 50) over locked red art, with its fill row's blend mode set to
/// `row`.
fn blended_over_red(row: &str) -> Session {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).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": "#4080c0"})).unwrap();
s.execute("transparency.set", &json!({"item": fill_index(&s), "blend": row})).unwrap();
s
}
/// The index of the selected object's fill row.
fn fill_index(s: &Session) -> usize {
let st = s.active().unwrap();
let n = st.doc.node(st.selection.objects[0]).unwrap();
n.appearance.items.iter().position(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))).unwrap()
}
/// The contrast against red of the color the canvas draws at the square's center.
fn drawn_ratio(s: &Session) -> f64 {
let doc = &s.doc().unwrap().doc;
let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true);
let p = img.pixel(1, 1);
vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), [1.0, 0.0, 0.0])
}
#[test]
fn nested_blend_modes_count_as_the_canvas_draws_them() {
let mut s = blended_over_red("multiply");
s.execute("transparency.set", &json!({"item": null, "blend": "screen"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ff0000", "{r}");
let drawn = drawn_ratio(&s);
assert!((ratio(&r) - drawn).abs() < 0.02, "the fill multiplies, then the object screens: {r} against {drawn}");
// A translucent row and object: the canvas takes the backdrop back out of a group that blends
// through before it blends the group, so the opacities multiply over the nested modes.
s.execute("transparency.set", &json!({"item": fill_index(&s), "opacity": 50})).unwrap();
s.execute("transparency.set", &json!({"item": null, "blend": "overlay", "opacity": 70})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let drawn = drawn_ratio(&s);
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
s.execute("transparency.set", &json!({"item": null, "opacity": 100})).unwrap();
// Grouped, the group's mode blends the result again.
s.execute("transparency.set", &json!({"item": null, "blend": "normal"})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("transparency.set", &json!({"blend": "difference"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let drawn = drawn_ratio(&s);
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// In a 50 % group, a black square over a white one draws black over the black outside: the group's
/// opacity applies to the white behind the square once, not again over it.
#[test]
fn a_translucent_group_draws_the_art_behind_the_object_once() {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let white = id(s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let black = id(s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap());
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("object.group", &json!({"ids": [white.0, black.0]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.active_mut().unwrap().selection.objects = vec![black];
let r = s.execute("color.contrast", &json!({})).unwrap();
let doc = &s.doc().unwrap().doc;
let img = vectorcraft_render::Renderer::new().render_region(doc, vectorcraft_geom::Rect::new(99.0, 99.0, 101.0, 101.0), 1.0, true);
let p = img.pixel(1, 1);
let behind = vectorcraft_color::Color::from_hex(r["against"].as_str().unwrap()).unwrap().to_rgb_uncalibrated();
let drawn = vectorcraft_color::wcag::contrast_ratio([p[0], p[1], p[2]].map(|v| f32::from(v) / 255.0), behind);
assert!(p[0] < 3, "the canvas draws black: {p:?}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
#[test]
fn template_layers_and_guides_are_left_out_of_the_background() {
let mut s = session();
let first = s.doc().unwrap().doc.layers[0].id;
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("layer.setProps", &json!({"id": first.0, "template": true})).unwrap();
s.execute("layer.new", &json!({"top": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 120, "height": 120})).unwrap();
s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 60, "y": 60, "width": 80, "height": 80})).unwrap();
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert_eq!(r["against"], "#ffffff", "the artboard, without the template's red or the guide: {r}");
}
#[test]
fn objects_that_draw_one_color_differently_have_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `color`"), "{e}");
s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
// A given opacity takes the place of the objects' own.
let r = s.execute("color.contrast", &json!({"against": "#ffffff", "opacity": 100})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
}
#[test]
fn a_selected_group_whose_objects_draw_one_color_differently_has_no_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
s.execute("select.set", &json!({"ids": [b]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `color`"), "{e}");
}
#[test]
fn a_hidden_object_in_a_selected_group_leaves_one_answer() {
let id = |v: Value| v["id"].as_u64().unwrap();
// The first and then the second object hidden: the hidden one is neither compared nor measured.
for first in [false, true] {
let mut s = session();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
s.execute("select.set", &json!({"ids": [if first { a } else { b }]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
s.execute("object.hide", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "first hidden {first}: {r}");
}
}
#[test]
fn a_given_color_is_drawn_at_a_given_opacity() {
let mut s = Session::new();
let r = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff", "opacity": 50})).unwrap();
let opaque = s.execute("color.contrast", &json!({"color": "#808080", "against": "#ffffff"})).unwrap();
assert!((ratio(&r) - ratio(&opaque)).abs() < 0.05, "{r} {opaque}");
assert!(ratio(&r) < 5.0, "{r}");
}
#[test]
fn an_opaque_group_around_one_of_the_objects_leaves_one_answer() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
s.execute("object.group", &json!({"ids": [b]})).unwrap();
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let r = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-6, "{r}");
}
#[test]
fn objects_in_two_groups_of_one_opacity_answer_against_a_given_color() {
let mut s = session();
let id = |v: Value| v["id"].as_u64().unwrap();
let a = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap());
let b = id(s.execute("shape.rectangle", &json!({"x": 80, "y": 20, "width": 40, "height": 40})).unwrap());
s.execute("paint.setFill", &json!({"ids": [a, b], "color": "#000000"})).unwrap();
for o in [a, b] {
let g = id(s.execute("object.group", &json!({"ids": [o]})).unwrap());
s.execute("select.set", &json!({"ids": [g]})).unwrap();
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
}
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
// Sampled, each group is hidden in turn to read what is outside it, so the two differ.
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("the selected objects' colors differ: give `color`"), "{e}");
}
#[test]
fn a_hidden_fill_row_has_no_color_to_measure() {
let mut s = blended_over_red("normal");
s.execute("paint.setFill", &json!({"color": "#000000"})).unwrap();
s.execute("appearance.setItem", &json!({"index": fill_index(&s), "visible": false})).unwrap();
let e = s.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap_err().to_string();
assert!(e.contains("the active fill or stroke is hidden: give `color`"), "{e}");
let given = s.execute("color.contrast", &json!({"color": "#000000", "against": "#ffffff"})).unwrap();
assert!((ratio(&given) - 21.0).abs() < 1e-6, "{given}");
}
/// A background sampled across an edge averages two colors; the answer's `against` is exactly the
/// background the ratio used, so giving it back answers the same ratio.
#[test]
fn the_background_written_back_answers_the_same_ratio() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 80.3, "height": 160})).unwrap();
s.execute("paint.setFill", &json!({"color": "#2050a0"})).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": "#808080"})).unwrap();
let below = s.execute("color.contrast", &json!({})).unwrap();
let hex = below["against"].as_str().unwrap();
assert!(hex != "#ffffff" && hex != "#2050a0", "the sample straddles the edge: {below}");
let given = s.execute("color.contrast", &json!({"against": hex})).unwrap();
assert!((ratio(&below) - ratio(&given)).abs() < 1e-6, "{below} {given}");
}
#[test]
fn an_object_that_isolates_its_blending_draws_its_fill_as_it_is() {
let mut s = blended_over_red("multiply");
s.execute("transparency.set", &json!({"item": null, "isolate": true})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let drawn = drawn_ratio(&s);
let own = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::Color::from_hex("#4080c0").unwrap().to_rgb_uncalibrated(), [1.0, 0.0, 0.0]);
assert!((drawn - own).abs() < 0.02, "the canvas draws the fill unblended: {drawn} against {own}");
assert!((ratio(&r) - drawn).abs() < 0.02, "{r} against {drawn}");
}
/// A dynamic symbol instance of a white square in front of a red one, at 50 % opacity, with its
/// white square picked.
fn picked_symbol_part() -> Session {
let mut s = session();
let id = |v: Value| vectorcraft_doc::NodeId(v["id"].as_u64().unwrap());
let back = id(s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 160, "height": 160})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let front = id(s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap());
s.execute("paint.setFill", &json!({"color": "#ffffff"})).unwrap();
let inst = id(s.execute("symbol.new", &json!({"name": "Pair", "ids": [back.0, front.0], "type": "dynamic"})).unwrap());
s.execute("transparency.set", &json!({"opacity": 50})).unwrap();
let st = s.active_mut().unwrap();
st.selection.objects = vec![inst];
st.selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
s
}
#[test]
fn a_picked_symbol_object_is_measured_against_the_rest_of_its_instance() {
let mut s = picked_symbol_part();
let r = s.execute("color.contrast", &json!({"opacity": 100})).unwrap();
// The red square at 50 % over the artboard's white (#ff7f7f or #ff8080 as the renderer rounds
// it), not the artboard alone.
let hex = r["against"].as_str().unwrap();
let gb = vectorcraft_color::Color::from_hex(hex).unwrap().to_rgb_uncalibrated();
assert!(hex.starts_with("#ff") && (gb[1] - 0.5).abs() < 0.01 && (gb[2] - 0.5).abs() < 0.01, "{r}");
}
#[test]
fn a_picked_symbol_object_is_measured_with_its_instances_stain() {
let mut s = picked_symbol_part();
let inst = s.active().unwrap().selection.symbol_part.as_ref().unwrap().instance;
// The instance's fill stains its art half way to black.
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();
let n = s.doc().unwrap().doc.node(inst).unwrap().clone();
assert!(vectorcraft_doc::symbol_overrides::stain(&n).is_some_and(|(_, a)| (a - 0.5).abs() < 1e-6));
s.active_mut().unwrap().selection.symbol_part = Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![1] });
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}");
}
#[test]
fn a_picked_symbol_object_is_drawn_at_its_instances_opacity() {
let mut s = picked_symbol_part();
let r = s.execute("color.contrast", &json!({"against": "#000000"})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio(vectorcraft_color::wcag::over([1.0; 3], 0.5, [0.0; 3]), [0.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the instance draws the white at 50 %: {r}");
}
#[test]
fn type_measures_its_characters_without_an_appearance_rows_opacity() {
let mut s = session();
s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Label", "size": 24, "color": "#000000"})).unwrap();
s.execute("appearance.addFill", &json!({})).unwrap();
let index = s.doc().unwrap().doc.node(s.doc().unwrap().selection.objects[0]).unwrap().appearance.items.len() - 1;
s.execute("appearance.setItem", &json!({"index": index, "opacity": 0})).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": null})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
assert!((ratio(&r) - 21.0).abs() < 1e-3, "the characters stay opaque black: {r}");
}
#[test]
fn a_gradient_stop_counts_with_its_own_opacity() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
let stops = json!([{"offset": 0, "color": "#000000", "opacity": 0.5}, {"offset": 1, "color": "#ff0000"}]);
s.execute("paint.setFill", &json!({"gradient": {"stops": stops}})).unwrap();
let r = s.execute("color.contrast", &json!({})).unwrap();
let gray = vectorcraft_color::wcag::contrast_ratio([0.5; 3], [1.0; 3]);
assert!((ratio(&r) - gray).abs() < 1e-3, "the first stop, black at 50 %: {r}");
}
#[test]
fn below_needs_a_selection_and_bad_params_are_errors() {
let mut s = session();
let none = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(none.contains("nothing selected"), "{none}");
// A given background needs no selection: the proxy shows the defaults for new art.
assert!(s.execute("color.contrast", &json!({"against": "#ffffff"})).is_ok());
for bad in [
json!({"color": "#000000", "against": "behind"}),
json!({"color": "#000000", "against": 3}),
json!({"color": "#00000080", "against": "#ffffff"}),
json!({"color": "nope", "against": "#ffffff"}),
json!({"color": "#000000", "against": "#ffffff", "opacity": 101}),
json!({"color": "#000000", "against": "#ffffff", "opacity": -1}),
json!({"color": "#000000", "against": "#ffffff", "opacity": "50"}),
] {
assert!(s.execute("color.contrast", &bad).is_err(), "{bad}");
}
}
#[test]
fn a_fill_of_none_has_no_color_to_measure() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap();
s.execute("paint.setFill", &json!({"none": true})).unwrap();
let e = s.execute("color.contrast", &json!({})).unwrap_err().to_string();
assert!(e.contains("has no color"), "{e}");
assert!(s.execute("color.contrast", &json!({"color": "#000000"})).is_ok());
}
+26
View File
@@ -865,3 +865,29 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
assert!(!saved.bpc && saved.cmyk == cms::GENERIC_CMYK, "written over by the next change: {saved:?}");
}
}
/// With a working RGB space other than sRGB, `color.contrast` writes the background in working RGB,
/// the form `against` takes: a given brown comes back as it was given, and the background read
/// 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 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"}));
exec(&mut s, "file.new", json!({"width": 200, "height": 200}));
exec(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 80.3, "height": 160}));
exec(&mut s, "paint.setFill", json!({"color": "#2050a0"}));
exec(&mut s, "object.lock", json!({}));
exec(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100}));
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());
assert_eq!(below["against"], again["against"], "{below} {again}");
assert!((below["ratio"].as_f64().unwrap() - again["ratio"].as_f64().unwrap()).abs() < 1e-9, "{below} {again}");
}
+1 -1
View File
@@ -1354,7 +1354,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: 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); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both 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}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null} 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 set Show Contrast, Contrast For and Contrast Background: 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); 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, 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); keys left out 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, 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, contrast, contrastFor, contrastBackground}",
),
(
"ui.savePdfDialog",
+11
View File
@@ -1406,6 +1406,17 @@ font-technology Variable Променливи
Graphic Styles Графични стилове
Graphic Styles Options Опции за графични стилове
Graphics Графика
Show Contrast Показване на контраста
Contrast For Контраст за
Normal Text Нормален текст
Large Text Голям текст
Contrast Background Фон за контраста
Behind Selection Зад селекцията
Current Color Текущ цвят
Pass Покрива
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. Фонът се отчита в центъра на селекцията.
Graphics Processor Графичен процесор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
Can't render this file because it contains an unexpected character in line 2 and column 73.
+11
View File
@@ -1927,6 +1927,17 @@ digits Malayalam Malajalam
@msg `Custom` stands for changed settings: save the preset under another name `Custom` označava promijenjene postavke: sačuvajte unaprijed postavljeno pod drugim nazivom
@msg `{key}` must be an array of these names: {_1} `{key}` mora biti niz ovih naziva: {_1}
Graphics Grafika
Show Contrast Prikaži kontrast
Contrast For Kontrast za
Normal Text Normalni tekst
Large Text Veliki tekst
Contrast Background Pozadina kontrasta
Behind Selection Iza odabira
Current Color Trenutna boja
Pass Prolazi
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.
Local Libraries Lokalne biblioteke
Add Content Dodaj sadržaj
Click to apply to the selected type Kliknite da primijenite na odabrani tekst
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15
View File
@@ -1913,6 +1913,17 @@ digits Malayalam Malaiàlam
Graphic Styles (4) Estils gràfics (4)
Graphic Styles Options Opcions d’estils gràfics
Graphics Gràfics
Show Contrast Mostra el contrast
Contrast For Contrast per a
Normal Text Text normal
Large Text Text gran
Contrast Background Fons del contrast
Behind Selection Darrere la selecció
Current Color Color actual
Pass Supera
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ó.
Graphics Processor Processador gràfic
Graphics: {adapter} Gràfics: {adapter}
Gravity Gravetat
@@ -5969,6 +5980,10 @@ digits Malayalam Malaiàlam
@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for no s’ha aplicat res del conjunt de dades {name}: cap objecte està vinculat a una variable per a la qual tingui un valor
@msg no bound object reports a value (locked objects and embedded images report none) cap objecte vinculat no informa d’un valor (els objectes bloquejats i les imatges incrustades no n’informen cap)
@msg nothing selected no hi ha res seleccionat
@msg `{key}` must be a color or {_1} `{key}` ha de ser un color o {_1}
@msg the selected objects' colors differ: give `color` els colors dels objectes seleccionats són diferents: indiqueu `color`
@msg the active fill or stroke has no color: give `color` l’emplenament o el traç actiu no té color: indiqueu `color`
@msg the active fill or stroke is hidden: give `color` l’emplenament o el traç actiu està ocult: indiqueu `color`
@msg nothing to align no hi ha res per alinear
@msg nothing to distort no hi ha res per distorsionar
@msg nothing to export: the document has no visible art (or turn on Use Artboards) no hi ha res per exportar: el document no té art visible (o activeu Utilitza els taulers)
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15
View File
@@ -1958,6 +1958,17 @@ digits Malayalam Malajálamské
@msg `Custom` stands for changed settings: save the preset under another name `Custom` označuje změněná nastavení: uložte přednastavení pod jiným názvem
@msg `{key}` must be an array of these names: {_1} `{key}` musí být pole těchto názvů: {_1}
Graphics Grafika
Show Contrast Zobrazit kontrast
Contrast For Kontrast pro
Normal Text Normální text
Large Text Velký text
Contrast Background Pozadí kontrastu
Behind Selection Za výběrem
Current Color Aktuální barva
Pass Vyhovuje
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.
Local Libraries Místní knihovny
Add Content Přidat obsah
Click to apply to the selected type Kliknutím použijete na vybraný text
@@ -5132,6 +5143,10 @@ imageTrace Outline Obrys
@msg finish editing the pattern first nejprve dokončete úpravy vzorku
@msg nothing encoded nic nebylo zakódováno
@msg nothing selected nic není vybráno
@msg `{key}` must be a color or {_1} `{key}` musí být barva nebo {_1}
@msg the selected objects' colors differ: give `color` barvy vybraných objektů se liší: zadejte `color`
@msg the active fill or stroke has no color: give `color` aktivní výplň nebo tah nemá barvu: zadejte `color`
@msg the active fill or stroke is hidden: give `color` aktivní výplň nebo tah je skrytý: zadejte `color`
@msg nothing selected is in a group nic z výběru není ve skupině
@msg nothing to align není co zarovnat
@msg nothing to distort není co deformovat
Can't render this file because it is too large.
+11
View File
@@ -2380,6 +2380,17 @@ digits Malayalam Malayalam
Create New Sublayer Opret nyt underlag
Search All Søg i alle
Graphics Grafik
Show Contrast Vis kontrast
Contrast For Kontrast for
Normal Text Normal tekst
Large Text Stor tekst
Contrast Background Kontrastbaggrund
Behind Selection Bag markeringen
Current Color Aktuel farve
Pass Bestået
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.
Local Libraries Lokale biblioteker
Add Content Tilføj indhold
Click to apply to the selected type Klik for at anvende på den markerede tekst
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15
View File
@@ -1451,6 +1451,17 @@ file-filter Templates Vorlagen
Graphic Styles Grafikstile
Graphic Styles Options Optionen für Grafikstile
Graphics Grafik
Show Contrast Kontrast einblenden
Contrast For Kontrast für
Normal Text Normaler Text
Large Text Großer Text
Contrast Background Kontrasthintergrund
Behind Selection Hinter der Auswahl
Current Color Aktuelle Farbe
Pass Bestanden
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.
Graphics Processor Grafikprozessor
Graphics: {adapter} Grafik: {adapter}
Gravity Schwerkraft
@@ -4747,6 +4758,10 @@ theme Appearance Erscheinungsbild
@msg finish editing the pattern first beenden Sie zuerst die Bearbeitung des Musters
@msg nothing encoded nichts kodiert
@msg nothing selected nichts ausgewählt
@msg `{key}` must be a color or {_1} `{key}` muss eine Farbe oder {_1} sein
@msg the selected objects' colors differ: give `color` die Farben der ausgewählten Objekte unterscheiden sich: geben Sie `color` an
@msg the active fill or stroke has no color: give `color` die aktive Fläche oder Kontur hat keine Farbe: geben Sie `color` an
@msg the active fill or stroke is hidden: give `color` die aktive Fläche oder Kontur ist ausgeblendet: geben Sie `color` an
@msg nothing selected is in a group nichts Ausgewähltes befindet sich in einer Gruppe
@msg nothing to align nichts auszurichten
@msg nothing to distort nichts zu verzerren
Can't render this file because it is too large.
+15
View File
@@ -1381,6 +1381,17 @@ font-technology Variable Μεταβλητές
Graphic Styles Στυλ γραφικών
Graphic Styles Options Επιλογές στυλ γραφικών
Graphics Γραφικά
Show Contrast Εμφάνιση αντίθεσης
Contrast For Αντίθεση για
Normal Text Κανονικό κείμενο
Large Text Μεγάλο κείμενο
Contrast Background Φόντο αντίθεσης
Behind Selection Πίσω από την επιλογή
Current Color Τρέχον χρώμα
Pass Επιτυχία
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. Το φόντο διαβάζεται στο κέντρο της επιλογής.
Graphics Processor Επεξεργαστής γραφικών
Graphics: {adapter} Γραφικά: {adapter}
Gravity Βαρύτητα
@@ -4777,6 +4788,10 @@ digits Malayalam Μαλαγιάλαμ
@msg finish editing the pattern first ολοκληρώστε πρώτα την επεξεργασία του μοτίβου
@msg nothing encoded δεν κωδικοποιήθηκε τίποτα
@msg nothing selected δεν έχει επιλεγεί τίποτα
@msg `{key}` must be a color or {_1} το `{key}` πρέπει να είναι χρώμα ή {_1}
@msg the selected objects' colors differ: give `color` τα χρώματα των επιλεγμένων αντικειμένων διαφέρουν: δώστε `color`
@msg the active fill or stroke has no color: give `color` το ενεργό γέμισμα ή η πινελιά δεν έχει χρώμα: δώστε `color`
@msg the active fill or stroke is hidden: give `color` το ενεργό γέμισμα ή η πινελιά είναι κρυφό: δώστε `color`
@msg nothing selected is in a group τίποτα από τα επιλεγμένα δεν βρίσκεται σε ομάδα
@msg nothing to align δεν υπάρχει τίποτα για στοίχιση
@msg nothing to distort δεν υπάρχει τίποτα για παραμόρφωση
Can't render this file because it is too large.
+15
View File
@@ -1460,6 +1460,17 @@ font-technology Variable Variables
Graphic Styles Estilos gráficos
Graphic Styles Options Opciones de estilos gráficos
Graphics Gráficos
Show Contrast Mostrar contraste
Contrast For Contraste para
Normal Text Texto normal
Large Text Texto grande
Contrast Background Fondo del contraste
Behind Selection Detrás de la selección
Current Color Color actual
Pass Cumple
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.
Graphics Processor Procesador gráfico
Graphics: {adapter} Gráficos: {adapter}
Gravity Gravedad
@@ -4823,6 +4834,10 @@ axis Both Ambos
@msg finish editing the pattern first termina primero la edición del motivo
@msg nothing encoded no se codificó nada
@msg nothing selected no hay nada seleccionado
@msg `{key}` must be a color or {_1} `{key}` debe ser un color o {_1}
@msg the selected objects' colors differ: give `color` los colores de los objetos seleccionados difieren: indique `color`
@msg the active fill or stroke has no color: give `color` el relleno o trazo activo no tiene color: indique `color`
@msg the active fill or stroke is hidden: give `color` el relleno o trazo activo está oculto: indique `color`
@msg nothing selected is in a group nada de lo seleccionado está en un grupo
@msg nothing to align no hay nada que alinear
@msg nothing to distort no hay nada que distorsionar
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15
View File
@@ -1919,6 +1919,17 @@ digits Malayalam Malajalam
Create New Sublayer Luo uusi alataso
Search All Hae kaikista
Graphics Grafiikka
Show Contrast Näytä kontrasti
Contrast For Kontrasti kohteelle
Normal Text Tavallinen teksti
Large Text Suuri teksti
Contrast Background Kontrastin tausta
Behind Selection Valinnan takana
Current Color Nykyinen väri
Pass Läpäisee
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ä.
Local Libraries Paikalliset kirjastot
Add Content Lisää sisältöä
Click to apply to the selected type Käytä valittuun tekstiin napsauttamalla
@@ -5036,6 +5047,10 @@ imageTrace Outline Ääriviiva
@msg finish editing the pattern first lopeta ensin kuvion muokkaus
@msg nothing encoded mitään ei koodattu
@msg nothing selected mitään ei ole valittu
@msg `{key}` must be a color or {_1} `{key}` on oltava väri tai {_1}
@msg the selected objects' colors differ: give `color` valittujen objektien värit eroavat: anna `color`
@msg the active fill or stroke has no color: give `color` aktiivisella täytöllä tai viivalla ei ole väriä: anna `color`
@msg the active fill or stroke is hidden: give `color` aktiivinen täyttö tai viiva on piilotettu: anna `color`
@msg nothing selected is in a group mikään valituista ei ole ryhmässä
@msg nothing to align ei tasattavaa
@msg nothing to distort ei vääristettävää
Can't render this file because it contains an unexpected character in line 2 and column 73.
+15
View File
@@ -1454,6 +1454,17 @@ font-technology Variable Variables
Graphic Styles Styles graphiques
Graphic Styles Options Options des styles graphiques
Graphics Graphiques
Show Contrast Afficher le contraste
Contrast For Contraste pour
Normal Text Texte normal
Large Text Grand texte
Contrast Background Arrière-plan du contraste
Behind Selection Derrière la sélection
Current Color Couleur actuelle
Pass Réussi
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.
Graphics Processor Processeur graphique
Graphics: {adapter} Carte graphique : {adapter}
Gravity Gravité
@@ -4812,6 +4823,10 @@ axis Both Les deux
@msg finish editing the pattern first terminez d’abord la modification du motif
@msg nothing encoded rien n’a été encodé
@msg nothing selected aucune sélection
@msg `{key}` must be a color or {_1} `{key}` doit être une couleur ou {_1}
@msg the selected objects' colors differ: give `color` les couleurs des objets sélectionnés diffèrent : indiquez `color`
@msg the active fill or stroke has no color: give `color` le fond ou le contour actif n’a pas de couleur : indiquez `color`
@msg the active fill or stroke is hidden: give `color` le fond ou le contour actif est masqué : indiquez `color`
@msg nothing selected is in a group aucun élément sélectionné ne se trouve dans un groupe
@msg nothing to align rien à aligner
@msg nothing to distort rien à déformer
Can't render this file because it is too large.
+12
View File
@@ -1546,6 +1546,18 @@
Graphic Styles ગ્રાફિક સ્ટાઇલ્સ
Graphic Styles Options ગ્રાફિક સ્ટાઇલ્સ વિકલ્પો
Graphics ગ્રાફિક્સ
Contrast કોન્ટ્રાસ્ટ
Show Contrast કોન્ટ્રાસ્ટ બતાવો
Contrast For આના માટે કોન્ટ્રાસ્ટ
Normal Text સામાન્ય ટેક્સ્ટ
Large Text મોટું ટેક્સ્ટ
Contrast Background કોન્ટ્રાસ્ટ પૃષ્ઠભૂમિ
Behind Selection પસંદગીની પાછળ
Current Color વર્તમાન રંગ
Pass પાસ
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. પૃષ્ઠભૂમિ પસંદગીના કેન્દ્રમાં વાંચવામાં આવે છે.
Graphics Processor ગ્રાફિક્સ પ્રોસેસર
Graphics: {adapter} ગ્રાફિક્સ: {adapter}
Gravity ગ્રેવિટી
Can't render this file because it contains an unexpected character in line 72 and column 5.
+15
View File
@@ -2123,6 +2123,17 @@ antiAlias Sharp शार्प
Graphic Styles (4) ग्राफिक स्टाइल्स (4)
Graphic Styles Options ग्राफ़िक स्टाइल ऑप्शन्स
Graphics ग्राफ़िक्स
Show Contrast कंट्रास्ट दिखाएँ
Contrast For इसके लिए कंट्रास्ट
Normal Text सामान्य टेक्स्ट
Large Text बड़ा टेक्स्ट
Contrast Background कंट्रास्ट पृष्ठभूमि
Behind Selection सिलेक्शन के पीछे
Current Color मौजूदा रंग
Pass पास
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. पृष्ठभूमि सिलेक्शन के केंद्र पर पढ़ी जाती है।
Graphics Processor ग्राफिक्स प्रोसेसर
Graphics: {adapter} ग्राफिक्स: {adapter}
Gravity ग्रेविटी
@@ -7565,6 +7576,10 @@ antiAlias Sharp शार्प
@msg nothing in data set {name} was applied: no object is bound to a variable it has a value for डेटा सेट {name} से कुछ भी लागू नहीं हुआ: उसमें मान वाले किसी भी वेरिएबल से कोई ऑब्जेक्ट नहीं बाँधा गया है
@msg nothing prints कुछ भी प्रिंट
@msg nothing selected कुछ भी नहीं चुना
@msg `{key}` must be a color or {_1} `{key}` कोई रंग या {_1} होना चाहिए
@msg the selected objects' colors differ: give `color` चुने गए ऑब्जेक्ट्स के रंग अलग-अलग हैं: `color` दें
@msg the active fill or stroke has no color: give `color` सक्रिय फ़िल या स्ट्रोक में कोई रंग नहीं है: `color` दें
@msg the active fill or stroke is hidden: give `color` सक्रिय फ़िल या स्ट्रोक छिपा हुआ है: `color` दें
@msg nothing selected is in a group कुछ भी नहीं चुना गया है एक समूह में
@msg nothing to align संरेखित करने के लिए कुछ नहीं
@msg nothing to bind बाध्य करने के लिए कुछ नहीं
Can't render this file because it is too large.
+15
View File
@@ -1840,6 +1840,17 @@ file-filter Templates Sablonok
Graphic Styles (4) Grafikai stílusok (4)
Graphic Styles Options Grafikai stílusok beállításai
Graphics Grafikák
Show Contrast Kontraszt megjelenítése
Contrast For Kontraszt ehhez
Normal Text Normál szöveg
Large Text Nagy szöveg
Contrast Background Kontraszt háttere
Behind Selection A kijelölés mögött
Current Color Aktuális szín
Pass Megfelel
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.
Graphics Processor Grafikus processzor
Graphics: {adapter} Grafika: {adapter}
Gravity Gravitáció
@@ -5514,6 +5525,10 @@ imageTrace Outline Körvonal
@msg finish editing the pattern first előbb fejezd be a mintázat szerkesztését
@msg nothing encoded nincs kódolt adat
@msg nothing selected nincs kijelölés
@msg `{key}` must be a color or {_1} a(z) `{key}` értéke csak szín vagy {_1} lehet
@msg the selected objects' colors differ: give `color` a kijelölt objektumok színei eltérnek: adja meg a `color` értékét
@msg the active fill or stroke has no color: give `color` az aktív kitöltésnek vagy körvonalnak nincs színe: adja meg a `color` értékét
@msg the active fill or stroke is hidden: give `color` az aktív kitöltés vagy körvonal rejtett: adja meg a `color` értékét
@msg nothing selected is in a group a kijelölésből semmi sincs csoportban
@msg nothing to align nincs mit igazítani
@msg nothing to distort nincs mit torzítani
Can't render this file because it is too large.
+11
View File
@@ -1771,6 +1771,17 @@ digits Malayalam Malayalam
Create New Sublayer Buat sublapisan baru
Search All Cari semua
Graphics Grafis
Show Contrast Tampilkan kontras
Contrast For Kontras untuk
Normal Text Teks normal
Large Text Teks besar
Contrast Background Latar kontras
Behind Selection Di belakang seleksi
Current Color Warna saat ini
Pass Lulus
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.
Local Libraries Pustaka lokal
Add Content Tambahkan konten
Click to apply to the selected type Klik untuk menerapkan ke teks terpilih
1 # Indonesian (id) catalog. Same format as zh-hant.tsv: context <TAB> source <TAB> translation
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
+15
View File
@@ -1481,6 +1481,17 @@ file-filter Templates Modelli
Graphic Styles Stili grafici
Graphic Styles Options Opzioni stili grafici
Graphics Grafica
Show Contrast Mostra contrasto
Contrast For Contrasto per
Normal Text Testo normale
Large Text Testo grande
Contrast Background Sfondo del contrasto
Behind Selection Dietro la selezione
Current Color Colore corrente
Pass Superato
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.
Graphics Processor Processore grafico
Graphics: {adapter} Scheda grafica: {adapter}
Gravity Gravità
@@ -4875,6 +4886,10 @@ axis Both Entrambi
@msg finish editing the pattern first termina prima la modifica del motivo
@msg nothing encoded nessun dato codificato
@msg nothing selected nessuna selezione
@msg `{key}` must be a color or {_1} `{key}` deve essere un colore o {_1}
@msg the selected objects' colors differ: give `color` i colori degli oggetti selezionati sono diversi: indica `color`
@msg the active fill or stroke has no color: give `color` il riempimento o la traccia attivi non hanno colore: indica `color`
@msg the active fill or stroke is hidden: give `color` il riempimento o la traccia attivi sono nascosti: indica `color`
@msg nothing selected is in a group nessun elemento selezionato si trova in un gruppo
@msg nothing to align niente da allineare
@msg nothing to distort niente da distorcere
Can't render this file because it is too large.
+15
View File
@@ -3887,6 +3887,17 @@ file-filter Templates テンプレート
Stacked 積み重ね
Graphic Style Libraries Menu グラフィックスタイルライブラリメニュー
Graphics グラフィックス
Show Contrast コントラストを表示
Contrast For コントラストの対象
Normal Text 通常のテキスト
Large Text 大きなテキスト
Contrast Background コントラストの背景
Behind Selection 選択範囲の背後
Current Color 現在のカラー
Pass 合格
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. 背景は選択範囲の中央で読み取ります。
Greek & Cyrillic ギリシャ文字とキリル文字
Hex by Column 六角形 (列)
Hex by Row 六角形 (行)
@@ -5300,6 +5311,10 @@ swatch Bright Violet ビビッドバイオレット
@msg Couldn't paste from the clipboard: {e} クリップボードから貼り付けられませんでした: {e}
@msg Couldn't paste: the document it was pasted in was closed 貼り付けられませんでした: 貼り付け先のドキュメントは閉じられています
@msg nothing selected 何も選択されていません
@msg `{key}` must be a color or {_1} `{key}` はカラーまたは {_1} である必要があります
@msg the selected objects' colors differ: give `color` 選択したオブジェクトのカラーが異なります:`color` を指定してください
@msg the active fill or stroke has no color: give `color` アクティブな塗りまたは線にカラーがありません:`color` を指定してください
@msg the active fill or stroke is hidden: give `color` アクティブな塗りまたは線が非表示です:`color` を指定してください
@msg nothing selected is in a group 選択したオブジェクトはどれもグループ内にありません
@msg the {tool} tool has no options {tool} ツールにはオプションがありません
@msg unknown tool `{tool}` `{tool}` は不明なツールです
Can't render this file because it is too large.
+15
View File
@@ -1709,6 +1709,17 @@ digits Malayalam მალაიალამური
Create New Sublayer ახალი ქვეშრის შექმნა
Search All ყველგან ძიება
Graphics გრაფიკა
Show Contrast კონტრასტის ჩვენება
Contrast For კონტრასტი ამისთვის
Normal Text ჩვეულებრივი ტექსტი
Large Text დიდი ტექსტი
Contrast Background კონტრასტის ფონი
Behind Selection მონიშნულის უკან
Current Color მიმდინარე ფერი
Pass აკმაყოფილებს
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. ფონი იკითხება მონიშნულის ცენტრში.
Local Libraries ლოკალური ბიბლიოთეკები
Add Content შიგთავსის დამატება
Click to apply to the selected type დაწკაპეთ მონიშნულ ტექსტზე გამოსაყენებლად
@@ -4495,6 +4506,10 @@ font-technology Variable ცვლადი
@msg finish editing the pattern first ჯერ დაასრულეთ პატერნის რედაქტირება
@msg nothing encoded არაფერია კოდირებული
@msg nothing selected არაფერია მონიშნული
@msg `{key}` must be a color or {_1} `{key}` უნდა იყოს ფერი ან {_1}
@msg the selected objects' colors differ: give `color` მონიშნული ობიექტების ფერები განსხვავდება: მიუთითეთ `color`
@msg the active fill or stroke has no color: give `color` აქტიურ შევსებას ან კონტურს ფერი არ აქვს: მიუთითეთ `color`
@msg the active fill or stroke is hidden: give `color` აქტიური შევსება ან კონტური დამალულია: მიუთითეთ `color`
@msg nothing selected is in a group მონიშნულთაგან არაფერია ჯგუფში
@msg nothing to align გასასწორებელი არაფერია
@msg nothing to distort დასადეფორმირებელი არაფერია
Can't render this file because it is too large.
+15
View File
@@ -3875,6 +3875,17 @@ file-filter Templates 템플릿
Stacked 누적
Graphic Style Libraries Menu 그래픽 스타일 라이브러리 메뉴
Graphics 그래픽
Show Contrast 대비 표시
Contrast For 대비 기준
Normal Text 일반 텍스트
Large Text 큰 텍스트
Contrast Background 대비 배경
Behind Selection 선택 영역 뒤
Current Color 현재 색상
Pass 통과
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. 배경은 선택 영역의 중앙에서 읽습니다.
Greek & Cyrillic 그리스어 및 키릴 문자
Hex by Column 열 기준 육각형
Hex by Row 행 기준 육각형
@@ -5227,6 +5238,10 @@ theme Appearance 외관
@msg Couldn't paste from the clipboard: {e} 클립보드에서 붙여넣을 수 없습니다: {e}
@msg Couldn't paste: the document it was pasted in was closed 붙여넣을 수 없습니다: 붙여넣던 문서가 닫혔습니다
@msg nothing selected 선택된 항목이 없습니다
@msg `{key}` must be a color or {_1} `{key}`은(는) 색상 또는 {_1}이어야 합니다
@msg the selected objects' colors differ: give `color` 선택한 개체의 색상이 서로 다릅니다: `color`를 지정하세요
@msg the active fill or stroke has no color: give `color` 활성 칠 또는 획에 색상이 없습니다: `color`를 지정하세요
@msg the active fill or stroke is hidden: give `color` 활성 칠 또는 획이 숨겨져 있습니다: `color`를 지정하세요
@msg nothing selected is in a group 선택한 항목 중 그룹에 속한 항목이 없습니다
@msg the {tool} tool has no options {tool} 도구에는 옵션이 없습니다
@msg unknown tool `{tool}` 알 수 없는 도구 `{tool}`
Can't render this file because it is too large.
+15
View File
@@ -2289,6 +2289,17 @@ digits Malayalam Malayalam
Create New Sublayer Nieuwe sublaag maken
Search All Alles doorzoeken
Graphics Illustraties
Show Contrast Contrast tonen
Contrast For Contrast voor
Normal Text Normale tekst
Large Text Grote tekst
Contrast Background Contrastachtergrond
Behind Selection Achter selectie
Current Color Huidige kleur
Pass Geslaagd
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.
Local Libraries Lokale bibliotheken
Add Content Inhoud toevoegen
Click to apply to the selected type Klik om toe te passen op de geselecteerde tekst
@@ -5179,6 +5190,10 @@ imageTrace Outline Contour
@msg finish editing the pattern first rond eerst het bewerken van het patroon af
@msg nothing encoded niets gecodeerd
@msg nothing selected niets geselecteerd
@msg `{key}` must be a color or {_1} `{key}` moet een kleur of {_1} zijn
@msg the selected objects' colors differ: give `color` de kleuren van de geselecteerde objecten verschillen: geef `color` op
@msg the active fill or stroke has no color: give `color` de actieve vulling of lijn heeft geen kleur: geef `color` op
@msg the active fill or stroke is hidden: give `color` de actieve vulling of lijn is verborgen: geef `color` op
@msg nothing selected is in a group niets van de selectie zit in een groep
@msg nothing to align niets om uit te lijnen
@msg nothing to distort niets om te vervormen
Can't render this file because it is too large.
+15
View File
@@ -1876,6 +1876,17 @@ digits Malayalam Malajalam
@msg `Custom` stands for changed settings: save the preset under another name `Custom` oznacza zmienione ustawienia: zapisz ustawienie pod inną nazwą
@msg `{key}` must be an array of these names: {_1} `{key}` musi być tablicą tych nazw: {_1}
Graphics Grafiki
Show Contrast Pokaż kontrast
Contrast For Kontrast dla
Normal Text Zwykły tekst
Large Text Duży tekst
Contrast Background Tło kontrastu
Behind Selection Za zaznaczeniem
Current Color Bieżący kolor
Pass Spełnia
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.
Local Libraries Biblioteki lokalne
Add Content Dodaj zawartość
Click to apply to the selected type Kliknij, aby zastosować do zaznaczonego tekstu
@@ -4958,6 +4969,10 @@ imageTrace Outline Kontur
@msg finish editing the pattern first najpierw zakończ edycję wzorka
@msg nothing encoded nic nie zakodowano
@msg nothing selected nic nie zaznaczono
@msg `{key}` must be a color or {_1} `{key}` musi być kolorem lub {_1}
@msg the selected objects' colors differ: give `color` kolory zaznaczonych obiektów się różnią: podaj `color`
@msg the active fill or stroke has no color: give `color` aktywne wypełnienie lub obrys nie ma koloru: podaj `color`
@msg the active fill or stroke is hidden: give `color` aktywne wypełnienie lub obrys jest ukryte: podaj `color`
@msg nothing selected is in a group nic z zaznaczenia nie należy do grupy
@msg nothing to align nie ma czego wyrównać
@msg nothing to distort nie ma czego zniekształcić
Can't render this file because it is too large.
+15
View File
@@ -3613,6 +3613,17 @@ font-technology Variable Variáveis
Symbol Set Density: Densidade do conjunto de símbolos:
Flatten Artwork Achatar arte-final
Graphics Gráficos
Show Contrast Mostrar Contraste
Contrast For Contraste Para
Normal Text Texto Normal
Large Text Texto Grande
Contrast Background Fundo do Contraste
Behind Selection Atrás da Seleção
Current Color Cor Atual
Pass Aprovado
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.
Highlight Rows Destacar linhas
Highlight Variable Destacar variável
Palette: Paleta:
@@ -4273,6 +4284,10 @@ axis Both Ambos
@msg finish editing the pattern first termine de editar o padrão primeiro
@msg nothing encoded nada codificado
@msg nothing selected nada selecionado
@msg `{key}` must be a color or {_1} `{key}` deve ser uma cor ou {_1}
@msg the selected objects' colors differ: give `color` as cores dos objetos selecionados são diferentes: informe `color`
@msg the active fill or stroke has no color: give `color` o preenchimento ou traçado ativo não tem cor: informe `color`
@msg the active fill or stroke is hidden: give `color` o preenchimento ou traçado ativo está oculto: informe `color`
@msg nothing selected is in a group nada do que está selecionado está em um grupo
@msg nothing to align nada para alinhar
@msg nothing to distort nada para distorcer
Can't render this file because it is too large.
+15
View File
@@ -1470,6 +1470,17 @@ file-filter Templates Шаблоны
Graphic Styles Графические стили
Graphic Styles Options Параметры графических стилей
Graphics Графика
Show Contrast Показать контраст
Contrast For Контраст для
Normal Text Обычный текст
Large Text Крупный текст
Contrast Background Фон контраста
Behind Selection За выделением
Current Color Текущий цвет
Pass Соответствует
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. Фон определяется в центре выделения.
Graphics Processor Графический процессор
Graphics: {adapter} Графика: {adapter}
Gravity Гравитация
@@ -4860,6 +4871,10 @@ axis Both Оба
@msg finish editing the pattern first сначала завершите редактирование узора
@msg nothing encoded ничего не закодировано
@msg nothing selected ничего не выделено
@msg `{key}` must be a color or {_1} `{key}` должен быть цветом или {_1}
@msg the selected objects' colors differ: give `color` цвета выделенных объектов различаются: укажите `color`
@msg the active fill or stroke has no color: give `color` у активной заливки или обводки нет цвета: укажите `color`
@msg the active fill or stroke is hidden: give `color` активная заливка или обводка скрыта: укажите `color`
@msg nothing selected is in a group ничего из выделенного не находится в группе
@msg nothing to align нечего выравнивать
@msg nothing to distort нечего искажать
Can't render this file because it is too large.
+15
View File
@@ -1419,6 +1419,17 @@ font-technology Variable Variabla
Graphic Styles Grafikstilar
Graphic Styles Options Grafikstilalternativ
Graphics Grafik
Show Contrast Visa kontrast
Contrast For Kontrast för
Normal Text Normal text
Large Text Stor text
Contrast Background Kontrastbakgrund
Behind Selection Bakom markeringen
Current Color Aktuell färg
Pass Godkänd
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.
Graphics Processor Grafikprocessor
Graphics: {adapter} Grafik: {adapter}
Gravity Gravitation
@@ -4721,6 +4732,10 @@ axis Both Båda
@msg finish editing the pattern first slutför redigeringen av mönstret först
@msg nothing encoded inget kodat
@msg nothing selected inget markerat
@msg `{key}` must be a color or {_1} `{key}` måste vara en färg eller {_1}
@msg the selected objects' colors differ: give `color` de markerade objektens färger skiljer sig: ange `color`
@msg the active fill or stroke has no color: give `color` den aktiva fyllningen eller linjen har ingen färg: ange `color`
@msg the active fill or stroke is hidden: give `color` den aktiva fyllningen eller linjen är dold: ange `color`
@msg nothing selected is in a group inget av det markerade ligger i en grupp
@msg nothing to align inget att justera
@msg nothing to distort inget att förvränga
Can't render this file because it is too large.
+15
View File
@@ -1383,6 +1383,17 @@ font-technology Variable Değişken
Graphic Styles Grafik Stilleri
Graphic Styles Options Grafik Stilleri Seçenekleri
Graphics Grafik
Show Contrast Kontrastı Göster
Contrast For Kontrast Hedefi
Normal Text Normal Metin
Large Text Büyük Metin
Contrast Background Kontrast Arka Planı
Behind Selection Seçimin Arkası
Current Color Geçerli Renk
Pass Geçti
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.
Graphics Processor Grafik İşlemcisi
Graphics: {adapter} Grafik: {adapter}
Gravity Yerçekimi
@@ -4596,6 +4607,10 @@ axis Both Her İkisi
@msg finish editing the pattern first önce deseni düzenlemeyi bitir
@msg nothing encoded kodlanmış hiçbir şey yok
@msg nothing selected hiçbir şey seçilmedi
@msg `{key}` must be a color or {_1} `{key}` bir renk veya {_1} olmalıdır
@msg the selected objects' colors differ: give `color` seçili nesnelerin renkleri farklı: `color` belirtin
@msg the active fill or stroke has no color: give `color` etkin dolgu veya konturun rengi yok: `color` belirtin
@msg the active fill or stroke is hidden: give `color` etkin dolgu veya kontur gizli: `color` belirtin
@msg nothing selected is in a group seçilenlerin hiçbiri bir grupta değil
@msg nothing to align hizalanacak hiçbir şey yok
@msg nothing to distort çarpıtılacak hiçbir şey yok
Can't render this file because it contains an unexpected character in line 5 and column 25.
+15
View File
@@ -1475,6 +1475,17 @@ file-filter Templates Шаблони
Graphic Styles Графічні стилі
Graphic Styles Options Параметри графічних стилів
Graphics Графіка
Show Contrast Показати контраст
Contrast For Контраст для
Normal Text Звичайний текст
Large Text Великий текст
Contrast Background Фон контрасту
Behind Selection За виділенням
Current Color Поточний колір
Pass Відповідає
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. Фон визначається в центрі виділення.
Graphics Processor Графічний процесор
Graphics: {adapter} Графіка: {adapter}
Gravity Гравітація
@@ -4859,6 +4870,10 @@ axis Both Обидві
@msg finish editing the pattern first спочатку завершіть редагування візерунка
@msg nothing encoded нічого не закодовано
@msg nothing selected нічого не виділено
@msg `{key}` must be a color or {_1} `{key}` має бути кольором або {_1}
@msg the selected objects' colors differ: give `color` кольори виділених об’єктів відрізняються: укажіть `color`
@msg the active fill or stroke has no color: give `color` активна заливка чи обведення не має кольору: укажіть `color`
@msg the active fill or stroke is hidden: give `color` активна заливка чи обведення приховані: укажіть `color`
@msg nothing selected is in a group нічого з виділеного не перебуває в групі
@msg nothing to align нічого вирівнювати
@msg nothing to distort нічого спотворювати
Can't render this file because it is too large.
+15
View File
@@ -1700,6 +1700,17 @@ file-filter Templates Mẫu
Graphic Styles Kiểu đồ họa
Graphic Styles Options Tùy chọn kiểu đồ họa
Graphics Đồ họa
Show Contrast Hiện độ tương phản
Contrast For Tương phản cho
Normal Text Văn bản thường
Large Text Văn bản lớn
Contrast Background Nền tương phản
Behind Selection Phía sau vùng chọn
Current Color Màu hiện tại
Pass Đạt
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.
Graphics Processor Bộ xử lý đồ họa
Graphics: {adapter} Đồ họa: {adapter}
Gravity Trọng lực
@@ -5176,6 +5187,10 @@ theme Appearance Giao diện
@msg finish editing the pattern first hãy hoàn tất chỉnh sửa họa tiết trước
@msg nothing encoded không có gì được mã hóa
@msg nothing selected chưa chọn gì
@msg `{key}` must be a color or {_1} `{key}` phải là một màu hoặc {_1}
@msg the selected objects' colors differ: give `color` màu của các đối tượng đã chọn khác nhau: hãy cung cấp `color`
@msg the active fill or stroke has no color: give `color` phần tô hoặc nét đang hoạt động không có màu: hãy cung cấp `color`
@msg the active fill or stroke is hidden: give `color` phần tô hoặc nét đang hoạt động bị ẩn: hãy cung cấp `color`
@msg nothing selected is in a group không mục nào được chọn nằm trong nhóm
@msg nothing to align không có gì để căn chỉnh
@msg nothing to distort không có gì để làm méo
Can't render this file because it contains an unexpected character in line 204 and column 5.
+15
View File
@@ -1411,6 +1411,17 @@ file-filter Templates 模板
Graphic Styles 图形样式
Graphic Styles Options 图形样式选项
Graphics 图形
Show Contrast 显示对比度
Contrast For 对比度适用于
Normal Text 普通文本
Large Text 大号文本
Contrast Background 对比度背景
Behind Selection 所选对象后方
Current Color 当前颜色
Pass 通过
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. 背景在所选对象的中心读取。
Gravity 重力
Grays 灰度级数
Grays and Neutrals 灰色和中性色
@@ -4979,6 +4990,10 @@ imageTrace Outline 轮廓
@msg Couldn't paste from the clipboard: {e} 无法从剪贴板粘贴:{e}
@msg Couldn't paste: the document it was pasted in was closed 无法粘贴:要粘贴到的文档已关闭
@msg nothing selected 未选择任何对象
@msg `{key}` must be a color or {_1} `{key}` 必须是颜色或 {_1}
@msg the selected objects' colors differ: give `color` 所选对象的颜色不同:请提供 `color`
@msg the active fill or stroke has no color: give `color` 现用填色或描边没有颜色:请提供 `color`
@msg the active fill or stroke is hidden: give `color` 现用填色或描边已隐藏:请提供 `color`
@msg nothing selected is in a group 所选对象均不在编组中
@msg the {tool} tool has no options {tool} 工具没有选项
@msg unknown tool `{tool}` 未知工具 `{tool}`
Can't render this file because it is too large.
+15
View File
@@ -1446,6 +1446,17 @@ file-filter Templates 範本
Graphic Styles 繪圖樣式
Graphic Styles Options 繪圖樣式選項
Graphics 圖形
Show Contrast 顯示對比度
Contrast For 對比度適用於
Normal Text 一般文字
Large Text 大型文字
Contrast Background 對比度背景
Behind Selection 選取範圍後方
Current Color 目前顏色
Pass 通過
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. 背景在選取範圍的中心讀取。
Graphics Processor 圖形處理器
Graphics: {adapter} 圖形:{adapter}
Gravity 重力
@@ -2680,6 +2691,10 @@ file-filter Templates 範本
@msg Couldn't paste from the clipboard: {e} 無法從剪貼簿貼上:{e}
@msg Couldn't paste: the document it was pasted in was closed 無法貼上:要貼上的文件已關閉
@msg nothing selected 未選取任何物件
@msg `{key}` must be a color or {_1} `{key}` 必須是顏色或 {_1}
@msg the selected objects' colors differ: give `color` 所選物件的顏色不同:請提供 `color`
@msg the active fill or stroke has no color: give `color` 作用中的填色或筆畫沒有顏色:請提供 `color`
@msg the active fill or stroke is hidden: give `color` 作用中的填色或筆畫已隱藏:請提供 `color`
@msg nothing selected is in a group 選取的物件都不在群組中
@msg the {tool} tool has no options {tool} 工具沒有選項
@msg unknown tool `{tool}` 未知的工具 `{tool}`
Can't render this file because it is too large.
+1 -1
View File
@@ -1355,7 +1355,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: 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); keys left out keep their values, params that are not an object, another key or a value off the list are an error and change nothing, both 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}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, contrast?: bool, contrastFor?: normalText|largeText|graphics, contrastBackground?: a color, or null} 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 set Show Contrast, Contrast For and Contrast Background: 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); 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, 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); keys left out 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, 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, contrast, contrastFor, contrastBackground}",
),
(
"ui.savePdfDialog",
+2
View File
@@ -746,6 +746,8 @@ mod tests_color_wheel;
#[cfg(test)]
mod tests_color_wheel_box;
#[cfg(test)]
mod tests_color_wheel_contrast;
#[cfg(test)]
mod tests_constrain;
#[cfg(test)]
mod tests_css_properties;
+227 -6
View File
@@ -11,16 +11,22 @@
//! channel strip at its right, for the channel picked under Box Channel (Hue, Saturation,
//! Brightness, Red, Green or Blue). The field shows the other two components on the Color
//! Picker's axes. The view and the channel are kept with the preferences (`ui.colorWheel`).
//!
//! Panel menu › Show Contrast adds a row under the wheel or the box with the WCAG 2 contrast ratio
//! (<https://www.w3.org/TR/WCAG22/#dfn-contrast-ratio>) of the color against the color drawn
//! behind the selection, or against a color pinned with Contrast Background › Current Color, and
//! whether it meets AA and AAA for the category picked under Contrast For (`color.contrast`).
use egui::{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 super::color::{Target, apply, wheel_target};
use super::{pstate, set_pstate};
use super::{color_json, pstate, set_pstate};
use crate::VectorcraftApp;
use crate::dialogs::color_picker::Channel;
use crate::widgets::{self, FieldAxis, Live, SliderValue, menu_item};
@@ -67,6 +73,16 @@ pub struct Settings {
pub view: View,
#[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")]
pub channel: Channel,
/// Show Contrast: the contrast row under the wheel or the box.
#[serde(deserialize_with = "deserialize_flag")]
pub contrast: bool,
/// Contrast For: the category whose AA and AAA results the row shows.
#[serde(serialize_with = "serialize_category", deserialize_with = "deserialize_category")]
pub contrast_for: Category,
/// Contrast Background › Current Color: the pinned background; None for the color behind the
/// selection.
#[serde(deserialize_with = "deserialize_background")]
pub contrast_background: Option<Color>,
}
fn deserialize_view<'de, D: serde::Deserializer<'de>>(d: D) -> Result<View, D::Error> {
@@ -83,6 +99,29 @@ fn deserialize_channel<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Channel
Ok(v.as_str().and_then(Channel::parse).unwrap_or_default())
}
fn deserialize_flag<'de, D: serde::Deserializer<'de>>(d: D) -> Result<bool, D::Error> {
Ok(<Value as Deserialize>::deserialize(d)?.as_bool().unwrap_or_default())
}
fn serialize_category<S: serde::Serializer>(c: &Category, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(c.id())
}
fn deserialize_category<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Category, D::Error> {
let v = <Value as Deserialize>::deserialize(d)?;
Ok(v.as_str().and_then(Category::parse).unwrap_or_default())
}
/// A pinned background as saved (`{model, …}`) or as `ui.colorWheel` takes it (any color the
/// paint commands take); anything else reads as no pin.
fn background_value(v: &Value) -> Option<Color> {
serde_json::from_value(v.clone()).ok().or_else(|| vectorcraft_engine::cmd::color_value(v))
}
fn deserialize_background<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Color>, D::Error> {
Ok(background_value(&<Value as Deserialize>::deserialize(d)?))
}
/// Serde reader for the saved settings ([`crate::UiState::color_wheel`]): a value that is not an
/// object reads as the defaults, so it doesn't lose the rest of the preferences.
pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Settings, D::Error> {
@@ -90,11 +129,13 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Se
Ok(serde_json::from_value(v).unwrap_or_default())
}
/// `ui.colorWheel {view?, channel?}`: show the wheel or the box, and pick the box's channel. Keys
/// left out keep their values; params that are not an object, another key or a value off the list
/// are an error and change nothing. → the settings.
/// `ui.colorWheel {view?, channel?, contrast?, contrastFor?, contrastBackground?}`: show the wheel
/// or the box, pick the box's channel, and set the contrast row, its category and its pinned
/// background (`contrastBackground: null` unpins it). Keys left out keep their values; params that
/// are not an object, another key or a value off the list are an error and change nothing. → the
/// settings.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
const KEYS: [&str; 2] = ["view", "channel"];
const KEYS: [&str; 5] = ["view", "channel", "contrast", "contrastFor", "contrastBackground"];
match p {
Value::Null => {}
Value::Object(o) => {
@@ -113,11 +154,40 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri
None | Some(Value::Null) => {}
Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?,
}
match p.get("contrast") {
None | Some(Value::Null) => {}
Some(v) => {
let key = "contrast";
set.contrast = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?;
}
}
match p.get("contrastFor") {
None | Some(Value::Null) => {}
Some(v) => {
let key = "contrastFor";
let ids: Vec<&str> = Category::ALL.iter().map(|c| c.id()).collect();
set.contrast_for = v.as_str().and_then(Category::parse).ok_or_else(|| format!("`{key}` must be one of {}", ids.join(", ")))?;
}
}
match p.get("contrastBackground") {
None => {}
Some(Value::Null) => set.contrast_background = None,
Some(v) => {
let key = "contrastBackground";
set.contrast_background = Some(background_value(v).ok_or_else(|| format!("`{key}` must be a color or {}", "null"))?);
}
}
app.ui.color_wheel = set;
Ok(json!(app.ui.color_wheel))
}
/// The panel menu: Wheel View and Box View, and Box Channel while the box shows.
/// A Contrast For category's menu label in the interface language.
pub(super) fn category_name(c: Category) -> &'static str {
tl!(c.label())
}
/// The panel menu: Wheel View and Box View, Box Channel while the box shows, Show Contrast,
/// Contrast For and Contrast Background.
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let set = app.ui.color_wheel.clone();
for (label, view) in [(tl!("Wheel View"), View::Wheel), (tl!("Box View"), View::Box)] {
@@ -134,6 +204,28 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
}
});
});
ui.separator();
if menu_item(ui, tl!("Show Contrast"), true, set.contrast) {
command(app, &json!({ "contrast": !set.contrast })).ok();
}
ui.menu_button(format!(" {}", tl!("Contrast For")), |ui| {
for c in Category::ALL {
if menu_item(ui, category_name(c), true, set.contrast_for == c) {
command(app, &json!({ "contrastFor": c.id() })).ok();
}
}
});
ui.menu_button(format!(" {}", tl!("Contrast Background")), |ui| {
if menu_item(ui, tl!("Behind Selection"), true, set.contrast_background.is_none()) {
command(app, &json!({ "contrastBackground": null })).ok();
}
let current = wheel_target(app, ui).color();
if menu_item(ui, tl!("Current Color"), current.is_some(), set.contrast_background.is_some())
&& let Some(c) = current
{
command(app, &json!({ "contrastBackground": color_json(&c) })).ok();
}
});
}
/// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness,
@@ -207,6 +299,132 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) ->
/// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored.
const MEMORY: &str = "color-wheel-hsb";
/// Panel state: the color behind the selection, as `#rrggbb`, with the [`BehindKey`] it was read for.
const BEHIND: &str = "color-wheel-behind";
/// Panel state: the contrast row's `color.contrast` answer, with the [`RatioKey`] it was asked for.
const RATIO: &str = "color-wheel-ratio";
/// The side of the contrast row's background chip.
const CHIP: f32 = 16.0;
/// What the color behind the selection depends on: the document and its revision, the selected
/// objects, the picked object of a dynamic symbol instance, the on-screen Appearance of Black and
/// the color settings ([`under`]).
type BehindKey = (u64, u64, Vec<NodeId>, Option<Vec<u32>>, 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.
pub(super) type RatioKey =
(String, String, Option<(u64, u64)>, Vec<NodeId>, Option<Vec<u32>>, bool, Option<usize>, Option<usize>, Option<usize>, String, Under);
/// 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).
pub(super) type Under = (cms::ColorSettings, u64);
fn under() -> Under {
(cms::active_settings(), cms::profiles_generation())
}
/// The path of the picked object of a dynamic symbol instance, if one is picked.
fn picked_part(st: &vectorcraft_engine::DocState) -> Option<Vec<u32>> {
st.selection.symbol_part.as_ref().map(|sp| sp.path.clone())
}
/// The background the contrast row measures against: the pinned color, else the color
/// `color.contrast` reads behind the selection, kept per document revision and selection, and kept
/// as it is while an interaction is in progress (the selection being dragged is hidden from it).
/// None with nothing selected.
fn background(app: &mut VectorcraftApp, ui: &Ui) -> Option<Color> {
if let Some(c) = app.ui.color_wheel.contrast_background {
return Some(c);
}
let st = app.session.active()?;
let key: BehindKey = (st.uid, st.revision, st.selection.objects.clone(), picked_part(st), app.session.prefs.black_on_screen.clone(), under());
// During an interaction only the revision may differ: another document, selection or setting is
// read again.
let same_but_revision = |k: &BehindKey| k.0 == key.0 && k.2 == key.2 && k.3 == key.3 && k.4 == key.4 && k.5 == key.5;
let hex = match pstate::<Option<(BehindKey, Option<String>)>>(ui.ctx(), BEHIND) {
Some((k, hex)) if k == key || (app.session.in_interaction() && same_but_revision(&k)) => hex,
_ => {
// Any opaque color reads the background; only `against` is used.
let r = app.session.execute("color.contrast", &json!({ "color": "#000000" })).ok();
let hex = r.and_then(|r| r["against"].as_str().map(str::to_string));
set_pstate(ui.ctx(), BEHIND, Some((key, hex.clone())));
hex
}
};
// `against` is written in working RGB, the form a color takes.
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) {
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 answer = against.as_ref().and_then(|bg| {
let st = app.session.active();
let key: RatioKey = (
if sampled { "below".to_string() } else { format!("{bg:?}") },
format!("{:?}", super::active_paint(app)),
st.map(|d| (d.uid, d.revision)),
st.map(|d| d.selection.objects.clone()).unwrap_or_default(),
st.and_then(picked_part),
app.session.fill_active,
app.session.appearance_item(),
app.session.selected_stop(),
app.session.selected_freeform_point(),
app.session.prefs.black_on_screen.clone(),
under(),
);
match pstate::<Option<(RatioKey, Option<Value>)>>(ui.ctx(), RATIO) {
Some((k, r)) if k == key => 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())));
r
}
}
});
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);
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 {
ui.label("—");
return;
};
ui.label(wcag::ratio_text(ratio));
let (aa, aaa) = category.passes(ratio);
let result = |pass: bool| if pass { tl!("Pass") } else { tl!("Fail") };
ui.label(format!("AA {}", result(aa)));
if let Some(aaa) = aaa {
ui.label(format!("AAA {}", result(aaa)));
}
})
.response;
let mut tip = tl!(
"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)."
)
.to_string();
if !pinned {
tip.push(' ');
tip.push_str(tl!("The background is read at the center of the selection."));
}
resp.on_hover_text(tip);
}
/// What the HSB picked last belongs to: the document, the selected objects or text characters,
/// the appearance item, the proxy, the gradient stop or freeform point, its paint, and the color
@@ -344,6 +562,9 @@ 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 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);
@@ -167,16 +167,23 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() {
#[test]
fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), json!({"view": "wheel", "channel": "hue"}));
assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue"}));
assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), json!({"view": "box", "channel": "green"}));
let contrast = json!({"contrast": false, "contrastFor": "normalText", "contrastBackground": null});
let with = |view: &str, channel: &str| {
let mut v = contrast.clone();
v["view"] = json!(view);
v["channel"] = json!(channel);
v
};
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), with("wheel", "hue"));
assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), with("box", "hue"));
assert_eq!(app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), with("box", "green"));
let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err();
assert_eq!(e, "`view` must be wheel or box");
let e = app.run("ui.colorWheel", json!({"view": "wheel", "channel": 7})).unwrap_err();
assert_eq!(e, "`channel` must be hue, saturation, brightness, red, green or blue");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green }, "an error changes nothing");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Green, ..Default::default() }, "an error changes nothing");
let ui = crate::control::inspect(&app, &egui::Context::default());
assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green"}));
assert_eq!(ui["ui"]["color_wheel"], with("box", "green"));
}
/// The command's errors are translated in the catalogs that translate status and error messages,
@@ -211,10 +218,10 @@ fn ui_color_wheel_rejects_other_params() {
let e = app.run("ui.colorWheel", json!([1])).unwrap_err();
assert_eq!(e, "the params must be an object, not [1]");
let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err();
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel");
assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, contrast, contrastFor, contrastBackground");
let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err();
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red }, "an error changes nothing");
assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, contrast, contrastFor, contrastBackground");
assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing");
}
/// With None there is no color to edit: the strip reads 0 to screen readers, as the hue ring does,
@@ -270,7 +277,11 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() {
/// not know reads as the key's default without losing the other preferences.
#[test]
fn the_settings_are_kept_and_read_leniently() {
let ui = crate::UiState { color_wheel: Settings { view: View::Box, channel: Channel::Blue }, color_rgb_percent: true, ..Default::default() };
let ui = crate::UiState {
color_wheel: Settings { view: View::Box, channel: Channel::Blue, ..Default::default() },
color_rgb_percent: true,
..Default::default()
};
let saved = serde_json::to_value(&ui).unwrap();
let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(back.color_wheel, ui.color_wheel);
@@ -283,11 +294,11 @@ fn the_settings_are_kept_and_read_leniently() {
let mut odd = saved.clone();
odd["color_wheel"] = json!({"view": "box", "channel": 7});
let back: crate::UiState = serde_json::from_value(odd).unwrap();
assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default() });
assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::default(), ..Default::default() });
let mut odd = saved.clone();
odd["color_wheel"] = json!({"view": "triangle", "channel": "blue"});
let back: crate::UiState = serde_json::from_value(odd).unwrap();
assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue });
assert_eq!(back.color_wheel, Settings { view: View::Wheel, channel: Channel::Blue, ..Default::default() });
let mut odd = saved;
odd["color_wheel"] = json!("box");
let back: crate::UiState = serde_json::from_value(odd).unwrap();
@@ -0,0 +1,275 @@
//! The Color Wheel panel's Show Contrast row drawn headless: the ratio and the AA and AAA results,
//! the color behind the selection, a pinned background, a drag on the wheel, and `ui.colorWheel`.
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::{Value, json};
use vectorcraft_color::wcag;
use vectorcraft_engine::Session;
use super::color_wheel::show;
use super::pstate;
use crate::VectorcraftApp;
/// An app with a selected rectangle filled with `fill` and the contrast row shown.
fn app(fill: &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": fill})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).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), app);
h.run_steps(2);
h
}
fn shows(h: &Harness<'static, VectorcraftApp>, text: &str) -> bool {
h.query_by_label(text).is_some()
}
fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool) {
h.event(Event::PointerMoved(pos));
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(1);
}
#[test]
fn the_row_cuts_the_ratio_off_and_fails_aa_just_under_it() {
let mut app = app("#fdc96e");
app.run("ui.colorWheel", json!({"contrastBackground": "#355f78"})).unwrap();
let h = harness(app);
assert!(shows(&h, "4.49:1"), "4.4963:1 is cut off, not rounded up to 4.50:1");
assert!(shows(&h, "AA Fail") && shows(&h, "AAA Fail"));
}
#[test]
fn the_contrast_for_menu_shows_the_categories_in_the_interface_language() {
use vectorcraft_color::wcag::Category;
crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered"));
let names: Vec<&str> = Category::ALL.iter().map(|c| super::color_wheel::category_name(*c)).collect();
crate::i18n::set_current(crate::i18n::Lang::EN);
assert_eq!(names, ["Normaler Text", "Großer Text", crate::i18n::tr(crate::i18n::Lang::from_code("de").unwrap(), "Graphics")]);
assert_ne!(names[0], Category::NormalText.label());
}
/// An answer kept under other color settings (here a profiles generation not yet reached) is asked
/// again: Edit › Color Settings changes how a color displays without a document revision.
#[test]
fn an_answer_kept_under_other_color_settings_is_asked_again() {
type Kept = Option<(super::color_wheel::RatioKey, Option<Value>)>;
let mut app = app("#000000");
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
let mut h = harness(app);
assert!(shows(&h, "21.00:1"));
let (mut key, answer) = pstate::<Kept>(&h.ctx, "color-wheel-ratio").expect("the row keeps its answer");
let mut stale = answer.expect("an answer");
stale["ratio"] = json!(1.0);
key.10.1 = u64::MAX;
super::set_pstate(&h.ctx, "color-wheel-ratio", Some((key, Some(stale))));
h.run_steps(2);
assert!(shows(&h, "21.00:1"), "the answer is asked again under the current settings");
}
#[test]
fn the_row_follows_the_appearance_of_black() {
let mut app = app("#000000");
app.run("paint.setFill", json!({"color": {"c": 0, "m": 0, "y": 0, "k": 100}})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
app.run("prefs.set", json!({"key": "blackOnScreen", "value": "accurate"})).unwrap();
let mut h = harness(app);
let text = |h: &mut Harness<'static, VectorcraftApp>| {
let r = h.state_mut().session.execute("color.contrast", &json!({"against": "#ffffff"})).unwrap();
wcag::ratio_text(r["ratio"].as_f64().unwrap())
};
let accurate = text(&mut h);
assert!(shows(&h, &accurate), "{accurate}");
h.state_mut().run("prefs.set", json!({"key": "blackOnScreen", "value": "rich"})).unwrap();
h.run_steps(2);
let rich = text(&mut h);
assert_ne!(accurate, rich, "rich black draws the black darker");
assert!(shows(&h, &rich), "the row shows {rich}, not {accurate}");
}
#[test]
fn the_category_changes_the_results_and_graphics_have_no_aaa() {
let mut app = app("#fdc96e");
app.run("ui.colorWheel", json!({"contrastBackground": "#355f78", "contrastFor": "largeText"})).unwrap();
let mut h = harness(app);
assert!(shows(&h, "AA Pass") && shows(&h, "AAA Fail"));
h.state_mut().run("ui.colorWheel", json!({"contrastFor": "graphics"})).unwrap();
h.run_steps(2);
assert!(shows(&h, "AA Pass") && !shows(&h, "AAA Fail") && !shows(&h, "AAA Pass"));
}
#[test]
fn the_background_is_the_art_behind_the_selection() {
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": 10, "y": 10, "width": 180, "height": 180})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let h = harness(app);
let want = wcag::ratio_text(wcag::contrast_ratio([0.0; 3], [1.0, 1.0, 0.0]));
assert!(shows(&h, &want), "black on the locked yellow: {want}");
}
#[test]
fn nothing_selected_and_nothing_pinned_shows_no_ratio() {
let mut app = app("#000000");
app.run("select.none", json!({})).unwrap();
let mut h = harness(app);
assert!(shows(&h, "—"));
// A pinned background needs no selection: the proxy shows the defaults for new art.
h.state_mut().run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
h.run_steps(2);
assert!(!shows(&h, "—"));
}
/// With nothing selected the row measures the default fill for new art, and follows a change of
/// it, which leaves the document's revision as it is.
#[test]
fn the_row_follows_the_default_fill_with_nothing_selected() {
let mut app = app("#000000");
app.run("select.none", json!({})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
app.run("ui.colorWheel", json!({"contrastBackground": "#ffffff"})).unwrap();
let mut h = harness(app);
assert!(shows(&h, "21.00:1"));
h.state_mut().run("paint.setFill", json!({"color": "#ffffff"})).unwrap();
h.run_steps(2);
assert!(shows(&h, "1.00:1"), "white on the pinned white");
}
/// While a drag on the wheel is in progress the color behind the selection is not read again,
/// although every preview raises the document's revision.
#[test]
fn a_drag_on_the_wheel_keeps_the_background() {
type Under = (vectorcraft_color::cms::ColorSettings, u64);
type Kept = Option<((u64, u64, Vec<vectorcraft_doc::NodeId>, Option<Vec<u32>>, String, Under), Option<String>)>;
let mut h = harness(app("#336699"));
let read = |h: &Harness<'static, VectorcraftApp>| pstate::<Kept>(&h.ctx, "color-wheel-behind").map(|(k, _)| k.1);
let before = read(&h).expect("the background was read");
let sq = h.get_by_label("Saturation and brightness").rect();
press(&mut h, sq.center(), true);
for i in 1..4 {
h.event(Event::PointerMoved(sq.center() + vec2(8.0 * i as f32, 0.0)));
h.run_steps(1);
}
assert!(h.state().session.in_interaction(), "the drag previews on an interaction");
assert!(h.state().session.active().unwrap().revision > before, "the previews raised the revision");
assert_eq!(read(&h), Some(before), "the background was not read again during the drag");
press(&mut h, sq.center() + vec2(24.0, 0.0), false);
h.run_steps(2);
assert!(read(&h).unwrap() > before, "after the drag it is read for the new revision");
}
/// An interaction keeps the background only for the same document and selection: another
/// selection is read again.
#[test]
fn an_interaction_reads_the_background_again_for_another_selection() {
type Under = (vectorcraft_color::cms::ColorSettings, u64);
type Kept = Option<((u64, u64, Vec<vectorcraft_doc::NodeId>, Option<Vec<u32>>, String, Under), Option<String>)>;
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": 0, "y": 0, "width": 100, "height": 200})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
let id = |v: Value| v["id"].as_u64().unwrap();
let b = id(app.run("shape.rectangle", json!({"x": 130, "y": 20, "width": 40, "height": 40})).unwrap());
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut h = harness(app);
let hex = |h: &Harness<'static, VectorcraftApp>| pstate::<Kept>(&h.ctx, "color-wheel-behind").and_then(|(_, hex)| hex);
assert_eq!(hex(&h).as_deref(), Some("#ffff00"));
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");
}
/// Without a pin the row asks for the color behind the selection, so a translucent group holding
/// other art behind the object counts as `color.contrast {}` counts it.
#[test]
fn the_row_answers_as_color_contrast_does_inside_a_translucent_group() {
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": 0, "y": 0, "width": 200, "height": 200})).unwrap();
app.run("paint.setFill", json!({"color": "#ffff00"})).unwrap();
app.run("object.lock", json!({})).unwrap();
let id = |v: Value| v["id"].as_u64().unwrap();
let back = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 120, "height": 120})).unwrap());
app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap();
let front = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap());
app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap();
let g = id(app.run("object.group", json!({"ids": [back, front]})).unwrap());
app.run("select.set", json!({"ids": [g]})).unwrap();
app.run("transparency.set", json!({"opacity": 50})).unwrap();
app.run("select.set", json!({"ids": [front]})).unwrap();
app.run("ui.colorWheel", json!({"contrast": true})).unwrap();
let mut h = harness(app);
let want = h.state_mut().session.execute("color.contrast", &json!({})).unwrap();
let against = want["against"].clone();
let given = h.state_mut().session.execute("color.contrast", &json!({"against": against})).unwrap();
let (want, given) = (wcag::ratio_text(want["ratio"].as_f64().unwrap()), wcag::ratio_text(given["ratio"].as_f64().unwrap()));
assert_ne!(want, given, "the group's other art makes the two answers differ");
assert!(shows(&h, &want), "the row shows {want}, not {given}");
}
#[test]
fn ui_color_wheel_sets_the_keys_given_and_refuses_bad_values() {
let mut app = app("#000000");
let r = app.run("ui.colorWheel", json!({"contrastFor": "graphics", "contrastBackground": "#ff0000"})).unwrap();
assert_eq!(r["contrast"], true, "keys left out keep their values");
assert_eq!(r["contrastFor"], "graphics");
assert_eq!(app.ui.color_wheel.contrast_background.map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
let before = app.ui.color_wheel.clone();
for (p, e) in [
(json!({"contrast": "yes"}), "`contrast` must be true or false"),
(json!({"contrastFor": "huge"}), "`contrastFor` must be one of normalText, largeText, graphics"),
(json!({"contrastFor": 3}), "`contrastFor` must be one of normalText, largeText, graphics"),
(json!({"contrastBackground": "nope"}), "`contrastBackground` must be a color or null"),
(json!({"contrast": false, "contrastBackground": 5}), "`contrastBackground` must be a color or null"),
] {
assert_eq!(app.run("ui.colorWheel", p.clone()).unwrap_err(), e, "{p}");
}
assert_eq!(app.ui.color_wheel, before, "an error changes nothing");
let r = app.run("ui.colorWheel", json!({"contrastBackground": null})).unwrap();
assert_eq!(r["contrastBackground"], Value::Null, "null goes back to the color behind the selection");
assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), r, "{{}} reads the settings");
}
#[test]
fn the_settings_are_saved_and_each_key_reads_on_its_own() {
let mut app = app("#000000");
app.run("ui.colorWheel", json!({"contrastFor": "largeText", "contrastBackground": {"c": 0, "m": 1, "y": 0, "k": 0}})).unwrap();
let saved: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
assert_eq!(saved.color_wheel, app.ui.color_wheel);
let ui: crate::UiState =
serde_json::from_value(json!({"color_wheel": {"contrast": true, "contrastFor": "huge", "contrastBackground": 5}, "place_link": false}))
.unwrap();
assert!(ui.color_wheel.contrast, "a key that reads keeps its value");
assert_eq!((ui.color_wheel.contrast_for, ui.color_wheel.contrast_background), (wcag::Category::NormalText, None));
assert!(!ui.place_link, "the other preferences still load");
let ui: crate::UiState = serde_json::from_value(json!({"color_wheel": 3, "place_link": false})).unwrap();
assert_eq!((ui.color_wheel, ui.place_link), (Default::default(), false));
}
#[test]
fn ui_color_wheel_answers_junk_params_without_a_panic() {
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.colorWheel").expect("registered").3;
let mut app = app("#336699");
for p in vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent").into_iter().chain(vectorcraft_testkit::strategies::junk_values()) {
let _ = app.run("ui.colorWheel", p);
}
let mut app = VectorcraftApp::new(Session::new(), Default::default());
assert_eq!(app.run("ui.colorWheel", json!({"contrast": true})).unwrap()["contrast"], true);
}
+2 -1
View File
@@ -739,7 +739,8 @@ pub struct UiState {
/// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]).
#[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")]
pub color_rgb_percent: bool,
/// Color Wheel panel: the wheel or the box, and the box's channel (`ui.colorWheel`,
/// Color Wheel panel: the wheel or the box, the box's channel, and Show Contrast, Contrast For
/// and Contrast Background (`ui.colorWheel`,
/// [`crate::panels::color_wheel::deserialize_settings`]).
#[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")]
pub color_wheel: crate::panels::color_wheel::Settings,
+7
View File
@@ -234,6 +234,13 @@ its variation grid; the panel draws the same grid. `ui.colorGuideOptions` opens
as `ui.color_guide` (`variation`, `steps`, `amount`). Save Colors as Swatches runs `swatch.new {colors: [...]}`
(one swatch per colour, one undo step).
Color Wheel contrast: `color.contrast {color?, against?, opacity?}` answers the WCAG 2 contrast ratio of the active
proxy's color against the color drawn behind the selection (`against: "below"`, the default) or against a given color,
with the AA and AAA results for normal text, 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
`ui.color_wheel`.
Color Guide Limit to Library: `ui.colorGuideLimit {library}` (a swatch library id or name, `"document"` for the
document's swatches, `""` for none) limits the panel's colours; `ui.inspect` reports it as `ui.color_guide_limit`, and
`color.harmony {..., limitTo}` answers the limited guide (every colour snaps to the library's nearest colour, ΔE 2000).
+29 -2
View File
@@ -629,8 +629,11 @@ and answers true when the fields show in percent.
`ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's
strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"`
shows the wheel again. Keys left out keep their values. Params that are not an object, another key or a value off
the list return an error and change nothing. The command returns `{view, channel}`, and both settings are kept with
the preferences.
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`) 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.
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
@@ -957,6 +960,30 @@ 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
([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
ratio. `color` defaults to the active Fill or Stroke proxy's color (its selected gradient stop or freeform point; for
a picked object of a dynamic symbol instance, its solid color mixed towards the fill that stains the instance), at
the opacity it is drawn with (the object's opacity times that of its groups and layer, and for a picked object of a
dynamic symbol instance also of the instance and the groups of the symbol's art around it, of its fill or stroke row,
which type's character paint does not use, and of a stop or point; a translucent group or layer draws the art inside
it, the art behind the object included, over what is outside it) and with the blend modes it is drawn with (its
fill or stroke 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);
`opacity` (0 to 100) replaces that opacity. A given `color` is drawn in Normal mode, at `opacity` or fully opaque.
`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
is drawn); a picked object of a dynamic symbol instance hides only itself, and the color is read at its own center.
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 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.
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
harmony rule makes from a base colour (base first; `name?` defaults to "Theme N", `replace: "<name>"` overwrites
+1
View File
@@ -1555,6 +1555,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.
- **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`.