diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs new file mode 100644 index 0000000000..4d699854ce --- /dev/null +++ b/crates/color/src/css.rs @@ -0,0 +1,417 @@ +//! Color text in the forms CSS Color 4 defines: hex colors with or without an alpha +//! (), `rgb()` and `rgba()` +//! (), `hsl()` and `hsla()` +//! () and `oklch()` +//! (). The functions take the +//! space-separated form with an optional `/ alpha`, and `rgb()`, `rgba()`, `hsl()` and `hsla()` also +//! take the comma-separated legacy form (). +//! Hues take the angle units of CSS Values 4 (). A hex +//! color may leave out its `#`. + +use crate::oklab::{self, CHROMA_FULL}; + +/// The most characters a color text may have, spaces around it not counted. +pub const MAX_CHARS: usize = 48; + +/// The space a parsed color's red, green and blue are in. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Space { + /// The numbers as written: a hex color, `rgb()` or `hsl()`. + Srgb, + /// sRGB converted from `oklch()`. + Oklch, +} + +/// A color read from CSS text. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CssColor { + /// Red, green and blue from 0 to 1. + pub rgb: [f32; 3], + /// The alpha from 0 to 1, when the text gives one (CSS reads a missing alpha as 1). + pub alpha: Option, + pub space: Space, +} + +/// The color `text` gives, or `None` when it is not one of the module's forms or has more than +/// [`MAX_CHARS`] characters. Values are clamped where CSS clamps them when it parses them: red, green +/// and blue to 0..=255 (0..=100 %), alpha to 0..=1, a negative HSL saturation to 0, OKLCH lightness +/// to 0..=1 and chroma to 0 or more. `none` reads as 0. An `hsl()` color whose red, green or blue +/// falls outside 0..=1 has that channel clipped, and an `oklch()` color outside sRGB keeps its +/// lightness and hue and takes the largest chroma that fits ([`oklab::from_oklch`]); CSS maps such +/// colors into the gamut by its own rules instead. +pub fn parse(text: &str) -> Option { + let text = text.trim(); + if text.chars().nth(MAX_CHARS).is_some() { + return None; + } + match text.find('(') { + None => hex(text), + Some(open) => { + // CSS allows no space between a function's name and its `(`. + let name = text.get(..open)?.to_ascii_lowercase(); + let args = text.get(open + 1..)?.strip_suffix(')')?; + if args.contains(['(', ')']) { + return None; + } + match name.as_str() { + "rgb" | "rgba" => rgb(args), + "hsl" | "hsla" => hsl(args), + "oklch" => oklch(args), + _ => None, + } + } + } +} + +/// `#rrggbb` of red, green and blue from 0 to 1, each rounded to the nearest of 256 steps. +pub fn hex_of(rgb: [f32; 3]) -> String { + let [r, g, b] = rgb.map(byte); + format!("#{r:02x}{g:02x}{b:02x}") +} + +/// `v` (0 to 1) as one of 256 steps. +fn byte(v: f32) -> u8 { + (v.clamp(0.0, 1.0) * 255.0).round() as u8 +} + +/// A hex color of 3, 4, 6 or 8 digits, with or without `#`. +fn hex(text: &str) -> Option { + let digits = text.strip_prefix('#').unwrap_or(text); + if !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let nibbles: Vec = digits.bytes().filter_map(|b| (b as char).to_digit(16)).map(|d| d as u8).collect(); + let values: Vec = match nibbles.len() { + 3 | 4 => nibbles.iter().map(|n| n * 17).collect(), + 6 | 8 => nibbles.chunks(2).map(|p| p.iter().fold(0, |v, n| v * 16 + n)).collect(), + _ => return None, + }; + let unit = |i: usize| values.get(i).map(|v| f32::from(*v) / 255.0); + Some(CssColor { rgb: [unit(0)?, unit(1)?, unit(2)?], alpha: unit(3), space: Space::Srgb }) +} + +/// One argument of a color function. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Arg { + Number(f64), + Percent(f64), + /// An angle, in degrees. + Angle(f64), + None, +} + +/// The arguments of a color function, `args` being the text inside its parentheses: the three +/// components and the alpha, if any, and whether they were separated by commas (the legacy form). +fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, bool)> { + let (parts, alpha, legacy): (Vec<&str>, Option<&str>, bool) = if args.contains(',') { + if !legacy_allowed || args.contains('/') { + return None; + } + let mut parts: Vec<&str> = args.split(',').map(str::trim).collect(); + let alpha = if parts.len() == 4 { parts.pop() } else { None }; + (parts, alpha, true) + } else { + let mut halves = args.split('/'); + let colors = halves.next().unwrap_or_default(); + let alpha = halves.next(); + if halves.next().is_some() { + return None; + } + (colors.split_ascii_whitespace().collect(), alpha.map(str::trim), false) + }; + let [a, b, c] = parts.as_slice() else { return None }; + let one = |s: &str| { + let arg = arg(s)?; + // The legacy form has no `none`. + (!(legacy && arg == Arg::None)).then_some(arg) + }; + let alpha = match alpha { + Some(s) => Some(one(s)?), + None => None, + }; + Some(([one(a)?, one(b)?, one(c)?], alpha, legacy)) +} + +/// One argument: `none`, a number, a percentage or an angle (`deg`, `grad`, `rad`, `turn`), with no +/// spaces inside it. +fn arg(s: &str) -> Option { + if s.eq_ignore_ascii_case("none") { + return Some(Arg::None); + } + let end = number_end(s)?; + let n: f64 = s.get(..end)?.parse().ok().filter(|n: &f64| n.is_finite())?; + let unit = s.get(end..)?.to_ascii_lowercase(); + let arg = match unit.as_str() { + "" => Arg::Number(n), + "%" => Arg::Percent(n), + "deg" => Arg::Angle(n), + "grad" => Arg::Angle(n * 0.9), + "rad" => Arg::Angle(n.to_degrees()), + "turn" => Arg::Angle(n * 360.0), + _ => return None, + }; + match arg { + Arg::Angle(a) if !a.is_finite() => None, + _ => Some(arg), + } +} + +/// The byte length of the CSS number at the start of `s`: an optional sign, digits with an +/// optional fraction (at least one digit, and digits after a `.`), and an optional exponent. +fn number_end(s: &str) -> Option { + let b = s.as_bytes(); + let digits = |from: usize| b.get(from..).map_or(0, |rest| rest.iter().take_while(|c| c.is_ascii_digit()).count()); + let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-'))); + let whole = digits(i); + i += whole; + let mut fraction = 0; + if b.get(i) == Some(&b'.') { + fraction = digits(i + 1); + if fraction == 0 { + return None; + } + i += 1 + fraction; + } + if whole + fraction == 0 { + return None; + } + if matches!(b.get(i), Some(b'e' | b'E')) { + let sign = usize::from(matches!(b.get(i + 1), Some(b'+' | b'-'))); + let exp = digits(i + 1 + sign); + if exp > 0 { + i += 1 + sign + exp; + } + } + Some(i) +} + +/// The alpha argument from 0 to 1. +fn alpha(a: Option) -> Option> { + let v = match a { + None => return Some(None), + Some(Arg::Number(n)) => n, + Some(Arg::Percent(p)) => p / 100.0, + Some(Arg::None) => 0.0, + Some(Arg::Angle(_)) => return None, + }; + Some(Some(v.clamp(0.0, 1.0) as f32)) +} + +/// A hue argument in degrees from 0 to 360. +fn hue(a: Arg) -> Option { + match a { + Arg::Number(d) | Arg::Angle(d) => Some(d.rem_euclid(360.0)).filter(|d| d.is_finite()), + Arg::None => Some(0.0), + Arg::Percent(_) => None, + } +} + +fn rgb(args: &str) -> Option { + let (comps, a, legacy) = split(args, true)?; + let percents = comps.iter().filter(|c| matches!(c, Arg::Percent(_))).count(); + if legacy && percents != 0 && percents != 3 { + return None; + } + let unit = |c: Arg| match c { + Arg::Number(n) => Some(n / 255.0), + Arg::Percent(p) => Some(p / 100.0), + Arg::None => Some(0.0), + Arg::Angle(_) => None, + }; + let [r, g, b] = comps; + let rgb = [unit(r)?, unit(g)?, unit(b)?].map(|v| v.clamp(0.0, 1.0) as f32); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb }) +} + +fn hsl(args: &str) -> Option { + let (comps, a, legacy) = split(args, true)?; + let [h, s, l] = comps; + let percent = |c: Arg| match c { + Arg::Percent(v) => Some(v), + Arg::Number(v) if !legacy => Some(v), + Arg::None => Some(0.0), + _ => None, + }; + // CSS clamps a negative saturation to 0 and nothing else. + let (h, s, l) = (hue(h)?, percent(s)?.max(0.0) / 100.0, percent(l)? / 100.0); + // CSS Color 4's hslToRgb (https://www.w3.org/TR/css-color-4/#hsl-to-rgb); a channel outside + // 0..=1 is clipped. + let f = |n: f64| { + let k = (n + h / 30.0) % 12.0; + let amount = s * l.min(1.0 - l); + l - amount * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0) + }; + // Huge saturation and lightness values overflow to an infinity or NaN, which is refused. + let rgb = [f(0.0), f(8.0), f(4.0)]; + if rgb.iter().any(|v| !v.is_finite()) { + return None; + } + let rgb = rgb.map(|v| v.clamp(0.0, 1.0) as f32); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Srgb }) +} + +fn oklch(args: &str) -> Option { + let (comps, a, _) = split(args, false)?; + let [l, c, h] = comps; + let l = match l { + Arg::Number(v) => v, + Arg::Percent(p) => p / 100.0, + Arg::None => 0.0, + Arg::Angle(_) => return None, + }; + let c = match c { + Arg::Number(v) => v, + Arg::Percent(p) => p / 100.0 * CHROMA_FULL, + Arg::None => 0.0, + Arg::Angle(_) => return None, + }; + let (rgb, _) = oklab::from_oklch(l.clamp(0.0, 1.0), c.max(0.0), hue(h)?); + Some(CssColor { rgb, alpha: alpha(a)?, space: Space::Oklch }) +} + +#[cfg(test)] +mod tests { + use super::*; + use proptest::prelude::*; + + fn bytes(text: &str) -> ([u8; 3], Option) { + let c = parse(text).unwrap_or_else(|| panic!("{text} should parse")); + (c.rgb.map(byte), c.alpha.map(|a| (a * 255.0).round() as u8)) + } + + #[test] + fn hex_colors_take_three_four_six_or_eight_digits_with_or_without_the_hash() { + assert_eq!(bytes("#336699"), ([0x33, 0x66, 0x99], None)); + assert_eq!(bytes("33669980"), ([0x33, 0x66, 0x99], Some(0x80))); + assert_eq!(bytes("#369"), ([0x33, 0x66, 0x99], None)); + assert_eq!(bytes("#3698"), ([0x33, 0x66, 0x99], Some(0x88))); + assert_eq!(bytes(" #AbCdEf "), ([0xab, 0xcd, 0xef], None)); + for bad in ["", "#", "#12", "#12345", "#1234567", "#123456789", "#ggg", "##123", "#+12", "#12 3", "123"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn rgb_reads_the_modern_and_the_legacy_forms() { + assert_eq!(bytes("rgb(51 102 153)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(51 102 153 / 50%)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("RGBA(51 102 153/0.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(20% 40% 60%)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(20% 102 none)"), ([51, 102, 0], None), "the modern form mixes numbers and percentages"); + assert_eq!(bytes("rgb(51, 102, 153)"), ([51, 102, 153], None)); + assert_eq!(bytes("rgba(51,102,153,.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(51, 102, 153, 50%)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("rgb(300 -20 1e2)"), ([255, 0, 100], None), "components are clamped"); + assert_eq!(bytes("rgb(0 0 0 / 2)"), ([0, 0, 0], Some(255)), "the alpha is clamped"); + assert_eq!(bytes("rgb(0 0 0 / none)"), ([0, 0, 0], Some(0))); + for bad in [ + "rgb(51, 102%, 153)", + "rgb(51, 102, none)", + "rgb(51 102)", + "rgb(51 102 153 0.5)", + "rgb(51, 102 153)", + "rgb(51, 102, 153 / 0.5)", + "rgb(51 102 153 / 0.5 / 1)", + "rgb(51 102 153deg)", + "rgb(1. 2 3)", + "rgb(1e999 0 0)", + "rgb(51 102 153", + "rgb(51 102 153))", + "rgb(51 102 153) x", + "rgb(calc(1) 2 3)", + "rgb(,,)", + "rgb (1 2 3)", + "rgb()", + "rgbx(1 2 3)", + ] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn hsl_reads_hues_in_every_angle_unit() { + assert_eq!(bytes("hsl(210 50% 40%)"), ([51, 102, 153], None)); + assert_eq!(bytes("hsl(210deg 50 40 / 25%)"), ([51, 102, 153], Some(64))); + assert_eq!(bytes("hsla(210, 50%, 40%, 0.5)"), ([51, 102, 153], Some(128))); + assert_eq!(bytes("hsl(-150 50% 40%)"), ([51, 102, 153], None), "a hue is normalized"); + assert_eq!(bytes("hsl(0.5turn 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(200grad 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(3.14159265rad 100% 50%)"), ([0, 255, 255], None)); + assert_eq!(bytes("hsl(120 -20% 50%)"), ([128, 128, 128], None), "a negative saturation is 0"); + assert_eq!(bytes("hsl(15 150% 50%)"), ([255, 32, 0], None), "a saturation over 100 % is kept and the channels are clipped"); + assert_eq!(bytes("hsl(0 50% 150%)"), ([255, 255, 255], None)); + assert_eq!(bytes("hsl(none 0% 100%)"), ([255, 255, 255], None)); + for bad in + ["hsl(210, 50, 40)", "hsl(210% 50% 40%)", "hsl(210 50% 40% 1)", "hsl(210deg, 50%, none)", "hsl(1e999deg 0% 0%)", "hsl(1e306turn 0% 0%)"] + { + assert_eq!(parse(bad), None, "{bad:?}"); + } + // Saturation and lightness this large overflow to an infinity or NaN. + for bad in ["hsl(90 1e308% 1e308%)", "hsl(90 1e308 -1e308)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn oklch_converts_through_srgb_and_has_no_legacy_form() { + let c = parse("oklch(62.8% 0.2577 29.23)").unwrap(); + assert_eq!((c.rgb.map(byte), c.alpha, c.space), ([255, 0, 0], None, Space::Oklch)); + let c = parse("oklch(0.628 64.4% 29.23 / 0.5)").unwrap(); + assert_eq!((c.rgb.map(byte), c.alpha), ([255, 0, 0], Some(0.5))); + assert_eq!(parse("oklch(1 0 0)").map(|c| c.rgb.map(byte)), Some([255, 255, 255])); + assert_eq!(parse("oklch(2 -1 none)").map(|c| c.rgb.map(byte)), Some([255, 255, 255]), "L and C are clamped"); + let wide = parse("oklch(0.7 0.4 150)").unwrap(); + assert!(wide.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a color outside sRGB is brought inside: {:?}", wide.rgb); + let huge = parse("oklch(0.5 1e308 30)").unwrap(); + assert!(huge.rgb.iter().all(|v| (0.0..=1.0).contains(v)), "a huge chroma is brought inside: {:?}", huge.rgb); + for bad in ["oklch(0.6, 0.1, 30)", "oklch(0.6 0.1 30% )", "oklch(0.6deg 0.1 30)", "oklch(0.6 0.1)"] { + assert_eq!(parse(bad), None, "{bad:?}"); + } + } + + #[test] + fn text_longer_than_the_limit_is_refused() { + let at_limit = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 15)); + assert_eq!(at_limit.chars().count(), MAX_CHARS); + assert!(parse(&at_limit).is_some()); + let over = format!("rgb(51 102 153{})", " ".repeat(MAX_CHARS - 14)); + assert_eq!(parse(&over), None); + assert_eq!(parse(&format!(" {at_limit} ")).map(|c| c.rgb.map(byte)), Some([51, 102, 153]), "spaces around it are not counted"); + assert_eq!(parse(&"(".repeat(100_000)), None); + } + + #[test] + fn hex_of_rounds_each_component() { + assert_eq!(hex_of([0.2, 0.4, 0.6]), "#336699"); + assert_eq!(hex_of([-1.0, 2.0, f32::NAN]), "#00ff00"); + } + + proptest! { + #[test] + fn random_text_never_panics(text in "\\PC{0,60}") { + // `contains` is false for NaN, so these also check that every channel is finite. + if let Some(c) = parse(&text) { + prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v))); + prop_assert!(c.alpha.is_none_or(|a| (0.0..=1.0).contains(&a))); + } + } + + #[test] + fn function_shaped_text_never_panics( + name in "(rgb|rgba|hsl|hsla|oklch|RGB)", + args in "[-+0-9.eE%a-z ,/]{0,40}", + ) { + if let Some(c) = parse(&format!("{name}({args})")) { + prop_assert!(c.rgb.iter().all(|v| (0.0..=1.0).contains(v))); + } + } + + #[test] + fn eight_digit_hex_round_trips(r: u8, g: u8, b: u8, a: u8) { + let c = parse(&format!("#{r:02x}{g:02x}{b:02x}{a:02x}")).unwrap(); + prop_assert_eq!(c.rgb.map(byte), [r, g, b]); + prop_assert_eq!(c.alpha.map(|v| (v * 255.0).round() as u8), Some(a)); + prop_assert_eq!(hex_of(c.rgb), format!("#{r:02x}{g:02x}{b:02x}")); + } + } +} diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index 846dadb940..7c9b3a37e8 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -6,6 +6,7 @@ pub mod blend; pub mod cms; +pub mod css; pub mod freeform; pub mod gradient; pub mod harmony; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a9dee00af3..a68eca7e5c 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -13,6 +13,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::cms::Model; +use vectorcraft_color::css; use vectorcraft_color::harmony::{Guide, GuideOptions, Harmony, Variation}; use vectorcraft_color::{Color, Paint, keep_model}; use vectorcraft_doc::live::lerp_color; @@ -135,9 +136,33 @@ pub fn specs() -> Vec { always, harmony ), + cmd!( + query "color.parse", + "Parse Color", + [], + None, + "{text: a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa; the # may be left out) or a CSS color: rgb() or rgba(), hsl() or hsla() (space-separated with an optional / alpha, or the comma-separated legacy form), or oklch(), as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch); at most 48 characters, spaces around it not counted} the color the text gives → {color: an RGB color, the numbers written for a hex color, rgb() or hsl() and the sRGB of an oklch() color, whose chroma is lowered to fit sRGB; hex: \"#rrggbb\" of it; opacity: 0..100, the text's alpha, or null when the text gives none (CSS reads that as 100)}; values are clamped where CSS clamps them when it parses them, and an hsl() channel outside 0..255 is clipped; any other text is an error, and so is oklch() while the working RGB space is not sRGB", + always, + parse_color + ), ] } +fn parse_color(_: &mut Session, p: &Value) -> Result { + const C: &str = "color.parse"; + let text = text_param(p, "text", C)?.ok_or_else(|| bad(C, "missing `text`"))?; + let parsed = css::parse(text).ok_or_else(|| { + bad(C, "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters") + })?; + if parsed.space == css::Space::Oklch && !vectorcraft_color::cms::active().rgb_is_srgb() { + return Err(bad(C, "OKLCH needs sRGB as the working RGB space")); + } + let [r, g, b] = parsed.rgb; + // As paint.proxies answers an opacity: a percentage to two places. + let opacity = parsed.alpha.map(|a| (f64::from(a) * 10_000.0).round() / 100.0); + Ok(json!({ "color": Color::rgb(r, g, b), "hex": css::hex_of(parsed.rgb), "opacity": opacity })) +} + /// The RGB inverse of `c`, expressed in `c`'s colour model. pub(crate) fn invert(c: Color) -> Color { c.invert_keep_model() diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index c7c23e15c1..ff5734a4f6 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -142,6 +142,7 @@ pub(super) const ALLOWED: &[&str] = &[ "color.convert", "color.gamutCheck", "color.harmony", + "color.parse", "color.plates", "dataset.capture", "dataset.delete", diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 811b2e09af..2c76f2b0b6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -348,6 +348,48 @@ fn convert_to_oklch_answers_lightness_chroma_and_hue() { assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}"); } +/// `color.parse` reads each notation into an RGB color, its hex and the alpha as a percentage (null +/// when the text gives none), and answers an error for anything else. +#[test] +fn parse_reads_hex_with_alpha_and_css_colors() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let mut parse = |text: &str| s.execute("color.parse", &json!({ "text": text })); + for (text, opacity) in [ + ("#33669980", json!(50.2)), + ("33669980", json!(50.2)), + ("#3698", json!(53.33)), + ("#336699", Value::Null), + ("#369", Value::Null), + ("rgb(51 102 153 / 50%)", json!(50.0)), + ("rgba(51, 102, 153, 0.25)", json!(25.0)), + ("rgb(20% 40% 60%)", Value::Null), + ("hsl(210 50% 40%)", Value::Null), + ("hsla(210deg, 50%, 40%, 1)", json!(100.0)), + ] { + let r = parse(text).unwrap(); + assert_eq!(r["hex"], "#336699", "{text}: {r}"); + assert_eq!(r["opacity"], opacity, "{text}: {r}"); + let c: Color = serde_json::from_value(r["color"].clone()).unwrap(); + let Color::Rgb { r: red, g, b } = c else { panic!("{text}: {c:?}") }; + assert_eq!([red, g, b].map(|v| (v * 255.0).round() as u8), [0x33, 0x66, 0x99], "{text}"); + } + let red = parse("oklch(62.8% 0.2577 29.23 / 0.5)").unwrap(); + assert_eq!((&red["hex"], &red["opacity"]), (&json!("#ff0000"), &json!(50.0)), "{red}"); + let message = "`text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters"; + let long = format!("rgb(1 2 3{})", " ".repeat(40)); + for bad in ["", "#12345", "#gggggg", "rgb(1, 2%, 3)", "rgb(1 2)", "oklch(0.5, 0.1, 30)", "cmyk 0 100 100 0", "red", long.as_str()] { + let e = parse(bad).unwrap_err().to_string(); + assert!(e.ends_with(message), "{bad:?}: {e}"); + } + assert!(parse_err(&mut s, json!({})).ends_with("missing `text`")); + assert!(parse_err(&mut s, json!({"text": 5})).ends_with("`text` must be a string")); +} + +fn parse_err(s: &mut Session, p: Value) -> String { + s.execute("color.parse", &p).unwrap_err().to_string() +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 8ea057cd12..81fc274743 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -1031,3 +1031,20 @@ fn color_management_policies_are_checked_and_kept() { next.attach_color_settings(file); assert_eq!(cms::active_settings(), cms::ColorSettings::default()); } + +/// `color.parse` takes `oklch()` only while the working RGB space is sRGB; a hex color still gives +/// its numbers as the document's RGB numbers in another working space. +#[test] +fn color_parse_takes_oklch_only_in_an_srgb_working_space() { + let _g = settings(); + let old = cms::active_settings(); + let mut s = session(); + s.execute("edit.colorSettings", &json!({"rgb": cms::WIDE_GAMUT_RGB})).unwrap(); + let oklch = s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).map_err(|e| e.to_string()); + let hex = s.execute("color.parse", &json!({"text": "#33669980"})).map_err(|e| e.to_string()); + cms::set_active(&old).unwrap(); + assert!(oklch.as_ref().unwrap_err().ends_with("OKLCH needs sRGB as the working RGB space"), "{oklch:?}"); + let hex = hex.unwrap(); + assert_eq!((&hex["hex"], &hex["opacity"]), (&json!("#336699"), &json!(50.2))); + assert!(s.execute("color.parse", &json!({"text": "oklch(0.6 0.1 30)"})).is_ok(), "sRGB again"); +} diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b661478e0f..20660c672f 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -841,6 +841,11 @@ fn structured_junk() { ("node.move", json!({"id": 1, "parent": null, "index": 1000})), ("layer.setProps", json!({"id": 1, "color": 1000})), ("layer.newSublayer", json!({"parent": 2})), + ("color.parse", json!({"text": "rgb(1e308 -1e308 1e-400 / 1e308)"})), + ("color.parse", json!({"text": "hsl(1e308turn 1e308% -1e308%)"})), + ("color.parse", json!({"text": "oklch(1e308 1e308 -1e308rad / -1)"})), + ("color.parse", json!({"text": "#\u{1F600}\u{0}\u{FFFF}"})), + ("color.parse", json!({"text": "rgb(((((((((((("})), ("text.create", json!({"x": 0, "y": 0, "text": "\u{0}\u{FFFF}\u{1F600}", "size": -1})), ("text.create", json!({"x": 0, "y": 0, "text": "a", "size": 1e308, "area": {"width": -1, "height": 0}})), ("text.setStyle", json!({"size": 0, "leading": -1, "tracking": 1e308})), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 40fb92d958..d456e8282f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1384,7 +1384,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); keys left out keep their values, params that are not an object, another key or a value off the list (opacity: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more for an opacity under 100 %) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 6b1cd1de3a..8d6a2c626f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2357,6 +2357,9 @@ font-technology Variable Променливи Only Web Colors Само уеб цветове Opacity Непрозрачност Show Opacity Показване на непрозрачността + Show Hex Field Показване на шестнадесетичното поле + Hex or CSS color Шестнадесетичен или CSS цвят + Parse Color Разчитане на цвят Opacity & Mask Define Knockout Shape Непрозрачността и маската определят формата на изрязване Opacity Mask Маска за непрозрачност Opacity Mask Info Информация за маската за непрозрачност @@ -4351,6 +4354,7 @@ axis Both И двете @msg `color` must be a colour `color` трябва да бъде цвят @msg `sliders` must be none or oklch `sliders` трябва да бъде none или oklch @msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` трябва да бъде шестнадесетичен цвят (#rgb, #rgba, #rrggbb или #rrggbbaa) или CSS цвят rgb(), hsl() или oklch() с най-много 48 знака @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index f7a338ceea..0120f0ce67 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -463,6 +463,9 @@ Fill Color Boja ispune Opacity Neprozirnost Show Opacity Prikaži neprozirnost + Show Hex Field Prikaži hex polje + Hex or CSS color Hex ili CSS boja + Parse Color Raščlani boju Stroke Color Boja poteza Fill Gradient Gradijent ispune Stroke Gradient Gradijent poteza @@ -4768,6 +4771,7 @@ imageTrace Outline Obris @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue @msg `sliders` must be none or oklch `sliders` mora biti none ili oklch @msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` mora biti hex boja (#rgb, #rgba, #rrggbb ili #rrggbbaa) ili CSS boja rgb(), hsl() ili oklch() od najviše 48 znakova @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a6c418346c..630106a28c 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3003,6 +3003,9 @@ digits Malayalam Malaiàlam Only Web Colors Només colors web Opacity Opacitat Show Opacity Mostra l’opacitat + Show Hex Field Mostra el camp hex + Hex or CSS color Color hex o CSS + Parse Color Analitza el color Opacity & Mask Define Knockout Shape L’opacitat i la màscara defineixen la forma d’exclusió Opacity Mask Màscara d’opacitat Opacity Mask Info Informació de la màscara d’opacitat @@ -5452,6 +5455,7 @@ digits Malayalam Malaiàlam @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` ha de ser none o oklch @msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` ha de ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() o oklch() de 48 caràcters com a màxim @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 8aa93b2912..f1203e3730 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -476,6 +476,9 @@ Fill Color Barva výplně Opacity Krytí Show Opacity Zobrazit krytí + Show Hex Field Zobrazit pole hex + Hex or CSS color Barva hex nebo CSS + Parse Color Analyzovat barvu Stroke Color Barva tahu Fill Gradient Přechod výplně Stroke Gradient Přechod tahu @@ -5027,6 +5030,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue @msg `sliders` must be none or oklch `sliders` musí být none nebo oklch @msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musí být barva hex (#rgb, #rgba, #rrggbb nebo #rrggbbaa) nebo barva CSS rgb(), hsl() nebo oklch() o nejvýše 48 znacích @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 60b81cd0b5..9e005f7f9b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3108,6 +3108,9 @@ liquify-list-end {0}, {1} {0} og {1} Fill Color Fyldfarve Opacity Opacitet Show Opacity Vis opacitet + Show Hex Field Vis hex-felt + Hex or CSS color Hex- eller CSS-farve + Parse Color Fortolk farve Stroke Color Stregfarve Fill Gradient Fyldgradient Stroke Gradient Streggradient @@ -8485,6 +8488,7 @@ mark-style Japanese Japansk @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue @msg `sliders` must be none or oklch `sliders` skal være none eller oklch @msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` skal være en hex-farve (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-farve rgb(), hsl() eller oklch() på højst 48 tegn @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 5d86acf7cf..82348d4849 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2395,6 +2395,9 @@ file-filter Templates Vorlagen Only Web Colors Nur Webfarben Opacity Deckkraft Show Opacity Deckkraft einblenden + Show Hex Field Hex-Feld einblenden + Hex or CSS color Hex- oder CSS-Farbe + Parse Color Farbe auswerten Opacity & Mask Define Knockout Shape Deckkraft und Maske definieren Aussparungsform Opacity Mask Deckkraftmaske Opacity Mask Info Informationen zur Deckkraftmaske @@ -4630,6 +4633,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein @msg `sliders` must be none or oklch `sliders` muss none oder oklch sein @msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` muss eine Hex-Farbe (#rgb, #rgba, #rrggbb oder #rrggbbaa) oder eine CSS-Farbe rgb(), hsl() oder oklch() mit höchstens 48 Zeichen sein @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 200133e4d6..40127f1383 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1975,6 +1975,9 @@ font-technology Variable Μεταβλητές Only Web Colors Μόνο χρώματα ιστού Opacity Αδιαφάνεια Show Opacity Εμφάνιση αδιαφάνειας + Show Hex Field Εμφάνιση πεδίου Hex + Hex or CSS color Χρώμα Hex ή CSS + Parse Color Ανάλυση χρώματος Opacity Mask Μάσκα αδιαφάνειας Opacity: Αδιαφάνεια: Open Άνοιγμα @@ -6352,6 +6355,7 @@ effect Points Σημεία @msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue @msg `sliders` must be none or oklch Το `sliders` πρέπει να είναι none ή oklch @msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters Το `text` πρέπει να είναι χρώμα Hex (#rgb, #rgba, #rrggbb ή #rrggbbaa) ή χρώμα CSS rgb(), hsl() ή oklch() με έως 48 χαρακτήρες @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6a4d3f7218..0de22b4365 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2436,6 +2436,9 @@ font-technology Variable Variables Only Web Colors Solo colores web Opacity Opacidad Show Opacity Mostrar opacidad + Show Hex Field Mostrar campo hex + Hex or CSS color Color hex o CSS + Parse Color Analizar color Opacity & Mask Define Knockout Shape La opacidad y la máscara definen la forma de exclusión Opacity Mask Máscara de opacidad Opacity Mask Info Información de máscara de opacidad @@ -4732,6 +4735,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` debe ser none u oklch @msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` debe ser un color hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un color CSS rgb(), hsl() u oklch() de 48 caracteres como máximo @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index ccbd667cb5..2278d0a26f 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -473,6 +473,9 @@ Fill Color Täyttöväri Opacity Peittävyys Show Opacity Näytä peittävyys + Show Hex Field Näytä heksakenttä + Hex or CSS color Heksa- tai CSS-väri + Parse Color Jäsennä väri Stroke Color Viivan väri Fill Gradient Täytön liukuväri Stroke Gradient Viivan liukuväri @@ -6362,6 +6365,7 @@ mark-style Japanese Japanilainen @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue @msg `sliders` must be none or oklch `sliders` on oltava none tai oklch @msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` on oltava heksaväri (#rgb, #rgba, #rrggbb tai #rrggbbaa) tai CSS-väri rgb(), hsl() tai oklch(), enintään 48 merkkiä @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 93c5965f9c..932b8ebe52 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2428,6 +2428,9 @@ font-technology Variable Variables Only Web Colors Couleurs Web uniquement Opacity Opacité Show Opacity Afficher l’opacité + Show Hex Field Afficher le champ hex + Hex or CSS color Couleur hex ou CSS + Parse Color Analyser la couleur Opacity & Mask Define Knockout Shape L’opacité et le masque définissent la forme de masquage Opacity Mask Masque d’opacité Opacity Mask Info Infos sur le masque d’opacité @@ -4698,6 +4701,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue @msg `sliders` must be none or oklch `sliders` doit valoir none ou oklch @msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` doit être une couleur hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou une couleur CSS rgb(), hsl() ou oklch() d’au plus 48 caractères @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index f1d0066137..3b492b1cb0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2470,6 +2470,9 @@ Only Web Colors માત્ર વેબ રંગો Opacity અપારદર્શકતા Show Opacity અપારદર્શકતા બતાવો + Show Hex Field Hex ફીલ્ડ બતાવો + Hex or CSS color Hex અથવા CSS રંગ + Parse Color રંગ પાર્સ કરો Opacity & Mask Define Knockout Shape અપારદર્શકતા અને માસ્ક નૉકઆઉટ આકાર વ્યાખ્યાયિત કરે છે Opacity Mask Info અપારદર્શકતા માસ્ક માહિતી Opacity Mask Options અપારદર્શકતા માસ્ક વિકલ્પો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 11a177f04f..7186778d0e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3277,6 +3277,9 @@ antiAlias Sharp शार्प Only Web Colors केवल वेब रंग Opacity ओपेसिटी Show Opacity ओपेसिटी दिखाएँ + Show Hex Field हेक्स फ़ील्ड दिखाएँ + Hex or CSS color हेक्स या CSS रंग + Parse Color रंग पार्स करें Opacity & Mask Define Knockout Shape ओपेसिटी एंड मास्क डिफ़ाइन नॉकआउट शेप Opacity Mask ओपेसिटी मास्क Opacity Mask Info ओपेसिटी मास्क की जानकारी @@ -6353,6 +6356,7 @@ antiAlias Sharp शार्प @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए @msg `sliders` must be none or oklch `sliders` none या oklch होना चाहिए @msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` एक हेक्स रंग (#rgb, #rgba, #rrggbb या #rrggbbaa) या अधिकतम 48 वर्णों का CSS rgb(), hsl() या oklch() रंग होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9b3584c128..1a8a386dbc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2915,6 +2915,9 @@ file-filter Templates Sablonok Only Web Colors Csak webes színek Opacity Átlátszatlanság Show Opacity Átlátszatlanság megjelenítése + Show Hex Field Hex mező megjelenítése + Hex or CSS color Hex vagy CSS szín + Parse Color Szín értelmezése Opacity & Mask Define Knockout Shape Az átlátszatlanság és a maszk adja a kiütés alakját Opacity Mask Átlátszósági maszk Opacity Mask Info Átlátszósági maszk adatai @@ -5094,6 +5097,7 @@ imageTrace Outline Körvonal @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell @msg `sliders` must be none or oklch A `sliders` értéke none vagy oklch lehet @msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`: hex szín (#rgb, #rgba, #rrggbb vagy #rrggbbaa) vagy legfeljebb 48 karakteres CSS rgb(), hsl() vagy oklch() szín kell @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4c1b4916a2..0f274ff3aa 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -431,6 +431,9 @@ Fill Color Warna isian Opacity Opasitas Show Opacity Tampilkan opasitas + Show Hex Field Tampilkan bidang hex + Hex or CSS color Warna hex atau CSS + Parse Color Urai warna Stroke Color Warna stroke Fill Gradient Gradien isian Stroke Gradient Gradien stroke @@ -5752,6 +5755,7 @@ mark-style Japanese Jepang @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue @msg `sliders` must be none or oklch `sliders` harus none atau oklch @msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` harus berupa warna hex (#rgb, #rgba, #rrggbb, atau #rrggbbaa) atau warna CSS rgb(), hsl(), atau oklch() dengan paling banyak 48 karakter @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c5774cd357..f71698cec5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2472,6 +2472,9 @@ file-filter Templates Modelli Only Web Colors Solo colori web Opacity Opacità Show Opacity Mostra opacità + Show Hex Field Mostra campo hex + Hex or CSS color Colore hex o CSS + Parse Color Analizza colore Opacity & Mask Define Knockout Shape Opacità e maschera definiscono la forma di foratura Opacity Mask Maschera di opacità Opacity Mask Info Informazioni maschera di opacità @@ -4760,6 +4763,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue @msg `sliders` must be none or oklch `sliders` deve essere none o oklch @msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve essere un colore hex (#rgb, #rgba, #rrggbb o #rrggbbaa) o un colore CSS rgb(), hsl() o oklch() di al massimo 48 caratteri @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1b72c056b4..08c223a437 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -519,6 +519,9 @@ digits Malayalam マラヤーラム数字 Make Sides Equal 辺の長さをそろえる Opacity 不透明度 Show Opacity 不透明度を表示 + Show Hex Field 16 進フィールドを表示 + Hex or CSS color 16 進または CSS カラー + Parse Color カラーを解析 Pie End Angle: 扇形の終了角度: Pie Start Angle: 扇形の開始角度: Stroke Color カラー (線) @@ -5176,6 +5179,7 @@ swatch Bright Violet ビビッドバイオレット @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください @msg `sliders` must be none or oklch `sliders` は none または oklch でなければなりません @msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` には 16 進カラー (#rgb、#rgba、#rrggbb、#rrggbbaa) または 48 文字以内の CSS の rgb()、hsl()、oklch() カラーを指定してください @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 450dad2f58..b1af817bf2 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2487,6 +2487,9 @@ Fill Color შევსების ფერი Opacity გაუმჭვირვალობა Show Opacity გაუმჭვირვალობის ჩვენება + Show Hex Field Hex ველის ჩვენება + Hex or CSS color Hex ან CSS ფერი + Parse Color ფერის გარჩევა Stroke Color კონტურის ფერი Fill Gradient შევსების გრადიენტი Stroke Gradient კონტურის გრადიენტი @@ -8098,6 +8101,7 @@ liquify-list-end {0}, {1} {0} და {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue @msg `sliders` must be none or oklch `sliders` უნდა იყოს none ან oklch @msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` უნდა იყოს hex ფერი (#rgb, #rgba, #rrggbb ან #rrggbbaa) ან CSS ფერი rgb(), hsl() ან oklch(), არაუმეტეს 48 სიმბოლოსი @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index bdf527bc42..be197ef35a 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -512,6 +512,9 @@ digits Malayalam 말라얄람어 Make Sides Equal 변 길이 같게 Opacity 불투명도 Show Opacity 불투명도 표시 + Show Hex Field 16진수 필드 표시 + Hex or CSS color 16진수 또는 CSS 색상 + Parse Color 색상 구문 분석 Pie End Angle: 파이 끝 각도: Pie Start Angle: 파이 시작 각도: Stroke Color 선 색상 @@ -5103,6 +5106,7 @@ theme Appearance 외관 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 @msg `sliders` must be none or oklch `sliders`는 none 또는 oklch여야 합니다 @msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text`은(는) 16진수 색상(#rgb, #rgba, #rrggbb 또는 #rrggbbaa)이거나 최대 48자의 CSS rgb(), hsl() 또는 oklch() 색상이어야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4e7d0ffe9a..64ec429108 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1002,6 +1002,9 @@ liquify-list-end {0}, {1} {0} en {1} Fill Color Vulkleur Opacity Dekking Show Opacity Dekking tonen + Show Hex Field Hexveld tonen + Hex or CSS color Hex- of CSS-kleur + Parse Color Kleur ontleden Stroke Color Contourkleur Fill Gradient Vulverloop Stroke Gradient Contourverloop @@ -8262,6 +8265,7 @@ mark-style Japanese Japans @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn @msg `sliders` must be none or oklch `sliders` moet none of oklch zijn @msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` moet een hexkleur (#rgb, #rgba, #rrggbb of #rrggbbaa) of een CSS-kleur rgb(), hsl() of oklch() van ten hoogste 48 tekens zijn @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2f2d0758a8..156d2c6aba 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -435,6 +435,9 @@ Fill Color Kolor wypełnienia Opacity Krycie Show Opacity Pokaż krycie + Show Hex Field Pokaż pole hex + Hex or CSS color Kolor hex lub CSS + Parse Color Analizuj kolor Stroke Color Kolor obrysu Fill Gradient Gradient wypełnienia Stroke Gradient Gradient obrysu @@ -4850,6 +4853,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue @msg `sliders` must be none or oklch `sliders` musi mieć wartość none lub oklch @msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` musi być kolorem hex (#rgb, #rgba, #rrggbb lub #rrggbbaa) albo kolorem CSS rgb(), hsl() lub oklch() o długości najwyżej 48 znaków @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index db5b532050..171f408e4f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1986,6 +1986,9 @@ antiAlias Sharp Nítido Only Web Colors Apenas Cores da Web Opacity Opacidade Show Opacity Mostrar Opacidade + Show Hex Field Mostrar Campo Hex + Hex or CSS color Cor hex ou CSS + Parse Color Interpretar Cor Opacity & Mask Define Knockout Shape Opacidade e Máscara Definem Forma de Isolamento Opacity Mask Máscara de Opacidade Opacity Mask Info Informações da Máscara de Opacidade @@ -6320,6 +6323,7 @@ mark-style Japanese Japonesas @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue @msg `sliders` must be none or oklch `sliders` deve ser none ou oklch @msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` deve ser uma cor hex (#rgb, #rgba, #rrggbb ou #rrggbbaa) ou uma cor CSS rgb(), hsl() ou oklch() de no máximo 48 caracteres @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 83a4012318..e49d353f62 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2461,6 +2461,9 @@ file-filter Templates Шаблоны Only Web Colors Только web-цвета Opacity Непрозрачность Show Opacity Показать непрозрачность + Show Hex Field Показать поле hex + Hex or CSS color Цвет hex или CSS + Parse Color Разобрать цвет Opacity & Mask Define Knockout Shape Непрозрачность и маска определяют форму вырезания Opacity Mask Непрозрачная маска Opacity Mask Info Сведения о непрозрачной маске @@ -4756,6 +4759,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue @msg `sliders` must be none or oklch `sliders` должен быть none или oklch @msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` должно быть цветом hex (#rgb, #rgba, #rrggbb или #rrggbbaa) или цветом CSS rgb(), hsl() или oklch() длиной не более 48 символов @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 362ca0a34e..6db42ffbfb 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2373,6 +2373,9 @@ font-technology Variable Variabla Only Web Colors Endast webbfärger Opacity Opacitet Show Opacity Visa opacitet + Show Hex Field Visa hexfält + Hex or CSS color Hex- eller CSS-färg + Parse Color Tolka färg Opacity & Mask Define Knockout Shape Opacitet och mask definierar utsparningsform Opacity Mask Opacitetsmask Opacity Mask Info Info om opacitetsmask @@ -6345,6 +6348,7 @@ theme Appearance Utseende @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue @msg `sliders` must be none or oklch `sliders` måste vara none eller oklch @msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` måste vara en hexfärg (#rgb, #rgba, #rrggbb eller #rrggbbaa) eller en CSS-färg rgb(), hsl() eller oklch() på högst 48 tecken @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 120b30947f..dd3e771a76 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2212,6 +2212,9 @@ font-technology Variable Değişken Only Web Colors Yalnızca Web Renkleri Opacity Opaklık Show Opacity Opaklığı Göster + Show Hex Field Hex Alanını Göster + Hex or CSS color Hex veya CSS rengi + Parse Color Rengi Ayrıştır Opacity & Mask Define Knockout Shape Opaklık ve Maske Tanımlama Nakavt Şekli Opacity Mask Opaklık Maskesi Opacity Mask Info Opaklık Maskesi Bilgisi @@ -4467,6 +4470,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır @msg `sliders` must be none or oklch `sliders` none veya oklch olmalıdır @msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` bir hex rengi (#rgb, #rgba, #rrggbb veya #rrggbbaa) ya da en fazla 48 karakterlik bir CSS rgb(), hsl() veya oklch() rengi olmalıdır @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index a33e04e9ea..b84fe99f60 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2464,6 +2464,9 @@ file-filter Templates Шаблони Only Web Colors Тільки web-кольору Opacity Непрозорість Show Opacity Показати непрозорість + Show Hex Field Показати поле hex + Hex or CSS color Колір hex або CSS + Parse Color Розібрати колір Opacity & Mask Define Knockout Shape Непрозорість та маска визначають форму вирізування Opacity Mask Маска непрозорості Opacity Mask Info Відомості про маску непрозорості @@ -4744,6 +4747,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue @msg `sliders` must be none or oklch `sliders` має бути none або oklch @msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` має бути кольором hex (#rgb, #rgba, #rrggbb або #rrggbbaa) або кольором CSS rgb(), hsl() або oklch() довжиною не більше 48 символів @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cd405b95c6..34c0991600 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2736,6 +2736,9 @@ digits Hindi Hindi Only Web Colors Chỉ màu web Opacity Độ mờ Show Opacity Hiện độ mờ + Show Hex Field Hiện trường hex + Hex or CSS color Màu hex hoặc CSS + Parse Color Phân tích màu Opacity & Mask Define Knockout Shape Độ mờ & Mặt nạ xác định hình dạng Knockout Opacity Mask Mặt nạ độ mờ Opacity Mask Info Thông tin mặt nạ độ mờ @@ -4754,6 +4757,7 @@ theme Appearance Giao diện @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue @msg `sliders` must be none or oklch `sliders` phải là none hoặc oklch @msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` phải là màu hex (#rgb, #rgba, #rrggbb hoặc #rrggbbaa) hoặc màu CSS rgb(), hsl() hoặc oklch() dài tối đa 48 ký tự @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 14b5968bf3..dead5e5573 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2325,6 +2325,9 @@ file-filter Templates 模板 Only Web Colors 仅 Web 颜色 Opacity 不透明度 Show Opacity 显示不透明度 + Show Hex Field 显示十六进制字段 + Hex or CSS color 十六进制或 CSS 颜色 + Parse Color 解析颜色 Opacity & Mask Define Knockout Shape 不透明度与蒙版定义挖空形状 Opacity Mask 不透明度蒙版 Opacity Mask Info 不透明度蒙版信息 @@ -4857,6 +4860,7 @@ imageTrace Outline 轮廓 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue @msg `sliders` must be none or oklch `sliders` 必须是 none 或 oklch @msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必须是十六进制颜色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超过 48 个字符的 CSS rgb()、hsl() 或 oklch() 颜色 @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6b98dfe118..6152ca7220 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2486,6 +2486,7 @@ file-filter Templates 範本 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue @msg `sliders` must be none or oklch `sliders` 必須是 none 或 oklch @msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 +@msg `text` must be a hex color (#rgb, #rgba, #rrggbb or #rrggbbaa) or a CSS rgb(), hsl() or oklch() color of at most 48 characters `text` 必須是十六進位顏色 (#rgb、#rgba、#rrggbb 或 #rrggbbaa),或不超過 48 個字元的 CSS rgb()、hsl() 或 oklch() 顏色 @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -3597,6 +3598,9 @@ liquify-list-end {0}, {1} {0}和{1} Only Web Colors 僅限網頁色彩 Opacity 不透明度 Show Opacity 顯示不透明度 + Show Hex Field 顯示十六進位欄位 + Hex or CSS color 十六進位或 CSS 顏色 + Parse Color 剖析顏色 Opacity & Mask Define Knockout Shape 不透明度與遮色片定義挖空形狀 Opacity Mask 不透明度遮色片 Opacity Mask Info 不透明度遮色片資訊 diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index b90a7a7301..092efd23f5 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1385,7 +1385,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); keys left out keep their values, params that are not an object, another key or a value off the list (opacity: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, sliders}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, opacity?: bool, hexField?: bool, sliders?: none|oklch} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none) or OKLCH Sliders (oklch), as OKLCH Sliders 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); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill or stroke item, as paint.setFill {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); hexField checks (true) or unchecks (false) Show Hex Field, as the panel menu does: a field under the wheel or the box that shows the color's hex digits (two more for an opacity under 100 %) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; keys left out keep their values, params that are not an object, another key or a value off the list (opacity, hexField: not true or false) are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, opacity, hexField, sliders}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index acf7ab8865..267834ab4f 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -784,6 +784,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_hex; +#[cfg(test)] mod tests_color_wheel_opacity; #[cfg(test)] mod tests_constrain; diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 200636ba80..d2f787298b 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -23,6 +23,12 @@ //! by OKLCH lightness, chroma and hue (CSS Color 4: //! ), while the working RGB space is //! sRGB. The choice is kept with the preferences too. +//! +//! Panel menu › Show Hex Field adds a field under the wheel or the box that shows the color's six +//! hex digits, and two more while the opacity that Show Opacity sets is under 100 %. It takes a hex +//! color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (`color.parse`). A +//! typed color is applied in the same way as a pick, and an alpha sets the opacity that Show +//! Opacity sets, whether or not that row shows. Where that row is gray, only the color is applied. use egui::{Color32, Rect, Stroke, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; @@ -33,7 +39,7 @@ 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::{live_run, pstate, set_pstate}; +use super::{color_json, live_run, pstate, set_pstate}; use crate::VectorcraftApp; use crate::dialogs::color_picker::Channel; use crate::theme::Tokens; @@ -86,6 +92,9 @@ pub struct Settings { /// Show Opacity: the opacity row under the wheel or the box. #[serde(deserialize_with = "deserialize_flag")] pub opacity: bool, + /// Show Hex Field: the field for a hex or CSS color under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub hex_field: bool, #[serde(deserialize_with = "deserialize_sliders")] pub sliders: Sliders, } @@ -147,11 +156,11 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { set(&mut app.ui.color_wheel, p, &cms::active())?; Ok(json!(app.ui.color_wheel)) @@ -160,7 +169,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result Result<(), String> { - const KEYS: [&str; 4] = ["view", "channel", "opacity", "sliders"]; + const KEYS: [&str; 5] = ["view", "channel", "opacity", "hexField", "sliders"]; match p { Value::Null => {} Value::Object(o) => { @@ -183,6 +192,10 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S None | Some(Value::Null) => {} Some(v) => set.opacity = v.as_bool().ok_or("`opacity` must be true or false")?, } + match p.get("hexField") { + None | Some(Value::Null) => {} + Some(v) => set.hex_field = v.as_bool().ok_or("`hexField` must be true or false")?, + } match p.get("sliders") { None | Some(Value::Null) => {} Some(v) => { @@ -197,8 +210,8 @@ pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), S Ok(()) } -/// The panel menu: Wheel View and Box View, Box Channel while the box shows, OKLCH Sliders, and -/// Show Opacity. +/// The panel menu: Wheel View and Box View, Box Channel while the box shows, OKLCH Sliders, Show +/// Opacity and Show Hex Field. 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)] { @@ -229,6 +242,9 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Show Opacity"), true, set.opacity) { command(app, &json!({ "opacity": !set.opacity })).ok(); } + if menu_item(ui, tl!("Show Hex Field"), true, set.hex_field) { + command(app, &json!({ "hexField": !set.hex_field })).ok(); + } } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, @@ -374,6 +390,81 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo } } +/// The text the hex field shows for `color` and the opacity `o` the row of Show Opacity edits +/// (`None` when it has nothing to edit): six hex digits of the document's RGB numbers, and two more +/// for an opacity under 100 %. Empty without a solid color. +pub(crate) fn hex_text(color: Option<&Color>, o: Option) -> String { + let Some(c) = color else { return String::new() }; + let mut text = super::color::hex_digits(c); + let alpha = o.map(|o| (o.clamp(0.0, 1.0) * 255.0).round() as u8).filter(|a| *a < 255); + if let Some(a) = alpha { + text.push_str(&format!("{a:02X}")); + } + text +} + +/// Apply `c`, typed into the hex field, to `tgt` in one undo step, as a pick applies a color; the +/// alpha `alpha` (0 to 1) also sets the opacity of what the row of Show Opacity edits, when it has +/// something to edit. +fn apply_typed(app: &mut VectorcraftApp, tgt: &Target, c: Color, alpha: Option) { + let alpha = alpha.filter(|_| shown_opacity(app, tgt).1).map(|a| a.clamp(0.0, 1.0)); + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.set_color(c, None); + if let Some(a) = alpha { + s.opacity = a; + } + } + super::gradient::set_stops_keeping_models(app, &stops, None, Live::Released); + } + Target::Point { index, .. } => { + let mut p = json!({"index": index, "color": color_json(&c), "stroke": !app.session.fill_active, "keepModel": true}); + if let Some(a) = alpha { + p["opacity"] = json!(a); + } + live_run(app, "Color", "paint.freeform.setPoint", p, Live::Released); + } + _ => { + let cmd = super::proxy_cmd(app, false); + let mut p = json!({"color": color_json(&c), "focus": true, "keepModel": true}); + if let Some(a) = alpha { + p["opacity"] = json!(f64::from(a) * 100.0); + } + live_run(app, "Color", cmd, p, Live::Released); + } + } +} + +/// The Show Hex Field row: a `#` and a field as wide as the row. A committed text goes through +/// `color.parse`; a text it refuses shows its error in the status bar and changes nothing. True +/// when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option<&Color>) -> bool { + let (o, live) = shown_opacity(app, tgt); + let shown = hex_text(color, live.then_some(o)); + let mut typed = None; + ui.horizontal(|ui| { + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new("#").size(15.0).color(t.text)); + let width = ui.available_width(); + typed = widgets::text_field_named(ui, "color-wheel-hex", Some(tl!("Hex or CSS color")), Some(&shown), width, 1); + }); + let Some(text) = typed else { return false }; + match app.run("color.parse", json!({ "text": text })) { + Ok(r) => { + let Ok(rgb) = serde_json::from_value::(r["color"].clone()) else { return true }; + // The document's RGB numbers, in the model a pick would store them in. + let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + let c = stored_rgb(&cms::active(), rgb, replaced(app, tgt, false).as_ref(), cmyk_doc); + let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32); + apply_typed(app, tgt, c, alpha); + } + Err(e) => app.status(e), + } + true +} + /// 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 OKLCH the slider rows asked for last, the [`Owner`] of the color they stored @@ -445,7 +536,11 @@ pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bo /// [`stored`] for a pick of display sRGB `srgb`. pub(crate) fn stored_srgb(cms: &Cms, srgb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { let [r, g, b] = cms.srgb_to_rgb(srgb); - let rgb = Color::rgb(r, g, b); + stored_rgb(cms, Color::rgb(r, g, b), was, cmyk_doc) +} + +/// [`stored`] for the RGB color `rgb` in the working RGB space. +fn stored_rgb(cms: &Cms, rgb: Color, was: Option<&Color>, cmyk_doc: bool) -> Color { let cmyk = || { let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent); Color::cmyk(c, m, y, k) @@ -631,17 +726,31 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let owner = color.map(|c| Owner::of(app, &tgt, c)); opacity_row(app, ui, &tgt, &shown); // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the - // HSB picked last stays with the new gradient. - if let (Some(c), Some(was)) = (color, owner) - && let Some((remembered, rgb, hsb)) = pstate::>(ui.ctx(), MEMORY) - && remembered == was - { + // HSB and the OKLCH picked last stay with the new gradient. + if let (Some(c), Some(was)) = (color, owner) { let now = Owner::of(app, &tgt, c); if now != was { - set_pstate(ui.ctx(), MEMORY, Some((now, rgb, hsb))); + if let Some((remembered, rgb, hsb)) = pstate::>(ui.ctx(), MEMORY) + && remembered == was + { + set_pstate(ui.ctx(), MEMORY, Some((now.clone(), rgb, hsb))); + } + if let Some((remembered, rgb, lch)) = pstate::>(ui.ctx(), OKLCH_MEMORY) + && remembered == was + { + set_pstate(ui.ctx(), OKLCH_MEMORY, Some((now, rgb, lch))); + } } } } + if app.ui.color_wheel.hex_field { + ui.add_space(4.0); + // A pick or an OKLCH edit read in the frame that commits a text was made on the color + // before the text, so it is not applied. + if hex_row(app, ui, &tgt, color.as_ref()) { + return; + } + } let behind = super::alt_held(ui); let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); if let Some((lch, phase)) = picked_lch { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 7fdfe00862..e742e25d84 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -841,7 +841,7 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap_err(), "`sliders` must be none or oklch"); let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); - assert_eq!(got, json!({"view": "box", "channel": "red", "opacity": false, "sliders": "oklch"})); + assert_eq!(got, json!({"view": "box", "channel": "red", "opacity": false, "hexField": false, "sliders": "oklch"})); let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hsl"})).unwrap_err(); assert_eq!(e, "`sliders` must be none or oklch"); assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 95459c922e..a17bbc5be2 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,11 +167,15 @@ 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", "opacity": false, "sliders": "none"})); - assert_eq!(app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), json!({"view": "box", "channel": "hue", "opacity": false, "sliders": "none"})); + let defaults = json!({"view": "wheel", "channel": "hue", "opacity": false, "hexField": false, "sliders": "none"}); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), defaults); + assert_eq!( + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(), + json!({"view": "box", "channel": "hue", "opacity": false, "hexField": false, "sliders": "none"}) + ); assert_eq!( app.run("ui.colorWheel", json!({"channel": "green"})).unwrap(), - json!({"view": "box", "channel": "green", "opacity": false, "sliders": "none"}) + json!({"view": "box", "channel": "green", "opacity": false, "hexField": false, "sliders": "none"}) ); let e = app.run("ui.colorWheel", json!({"view": "triangle"})).unwrap_err(); assert_eq!(e, "`view` must be wheel or box"); @@ -179,7 +183,7 @@ fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { 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, ..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", "opacity": false, "sliders": "none"})); + assert_eq!(ui["ui"]["color_wheel"], json!({"view": "box", "channel": "green", "opacity": false, "hexField": false, "sliders": "none"})); } /// The command's errors are translated in the catalogs that translate status and error messages, @@ -214,9 +218,9 @@ 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, opacity, sliders"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, opacity, hexField, sliders"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, opacity, sliders"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, opacity, hexField, sliders"); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs new file mode 100644 index 0000000000..ce4a1afbe6 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -0,0 +1,329 @@ +//! The Color Wheel panel's Show Hex Field drawn headless: the setting and `ui.colorWheel`, hex +//! with an alpha and CSS colors typed into the field, the opacity they set, nothing selected, a +//! selection mixing type and other art, gradient stops and freeform points, and refused text. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_engine::Session; + +use super::color_wheel::{hex_text, show}; +use crate::VectorcraftApp; + +/// An app with a selected red rectangle and Show Hex Field checked. +fn app() -> 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": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + app.run("ui.colorWheel", json!({"hexField": true})).unwrap(); + app +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 420.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +/// Types `text` over the field's text and presses Enter. +fn type_in(h: &mut Harness<'static, VectorcraftApp>, text: &str) { + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text(text); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); +} + +fn shown(h: &Harness<'static, VectorcraftApp>) -> String { + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").value().unwrap_or_default() +} + +fn rgb8(c: &Color) -> [u8; 3] { + let Color::Rgb { r, g, b } = *c else { panic!("an RGB color: {c:?}") }; + [r, g, b].map(|v| (v * 255.0).round() as u8) +} + +fn fill_color(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> Color { + app.session.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint().color().expect("a solid fill") +} + +fn selected(app: &VectorcraftApp) -> Vec { + app.session.doc().unwrap().selection.objects.clone() +} + +fn undo_count(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() +} + +/// The panel menu's Show Hex Field and `ui.colorWheel {hexField}` check and uncheck the field; a bad +/// value is an error and changes nothing. +#[test] +fn show_hex_field_is_a_setting_of_the_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["hexField"], json!(false)); + assert_eq!(app.run("ui.colorWheel", json!({"hexField": true})).unwrap()["hexField"], json!(true)); + let e = app.run("ui.colorWheel", json!({"hexField": "yes"})).unwrap_err(); + assert_eq!(e, "`hexField` must be true or false"); + assert!(app.ui.color_wheel.hex_field, "an error changes nothing"); + assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["hexField"], json!(true)); + let saved: super::color_wheel::Settings = serde_json::from_value(json!({"hexField": true, "view": "box"})).unwrap(); + assert!(saved.hex_field); + let odd: super::color_wheel::Settings = serde_json::from_value(json!({"hexField": "on"})).unwrap(); + assert!(!odd.hex_field, "a saved value this build does not know reads as off"); + let h = harness({ + let mut app = self::app(); + app.run("ui.colorWheel", json!({"hexField": false})).unwrap(); + app + }); + assert!(h.query_by_role_and_label(Role::TextInput, "Hex or CSS color").is_none(), "no field while unchecked"); +} + +/// The field shows six digits, and two more while the opacity is under 100 %. +#[test] +fn the_field_shows_the_alpha_only_under_full_opacity() { + let h = harness(app()); + assert_eq!(shown(&h), "FF0000"); + let mut app = app(); + app.run("paint.setFill", json!({"opacity": 50})).unwrap(); + let h = harness(app); + assert_eq!(shown(&h), "FF000080"); + assert_eq!(hex_text(None, Some(0.5)), ""); + assert_eq!(hex_text(Some(&Color::rgb8(0x33, 0x66, 0x99)), Some(0.999)), "336699", "an opacity that rounds to ff shows no alpha"); + assert_eq!(hex_text(Some(&Color::rgb8(0x33, 0x66, 0x99)), None), "336699"); +} + +/// With Show Opacity on, typing `#33669980` sets the fill to #336699 at 50.2 % (128 of 255) in one +/// undo step. +#[test] +fn typing_hex_with_an_alpha_sets_the_color_and_the_opacity() { + let mut app = app(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let id = selected(&app)[0]; + let before = undo_count(&app); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + assert_eq!(rgb8(&fill_color(h.state(), id)), [0x33, 0x66, 0x99]); + let o = h.state().session.proxy_opacity(false).unwrap(); + assert!((o - 0.502).abs() < 1e-4, "{o}"); + assert_eq!(undo_count(h.state()), before + 1, "one undo step"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(rgb8(&fill_color(h.state(), id)), [255, 0, 0]); + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); +} + +/// A typed color keeps the model of the color it replaces, as a pick on the wheel does: a CMYK fill +/// stays CMYK, converted through the color settings. +#[test] +fn a_typed_color_keeps_a_cmyk_fill_cmyk() { + let mut app = app(); + app.run("paint.setFill", json!({"color": {"c": 0, "m": 100, "y": 100, "k": 0}})).unwrap(); + let id = selected(&app)[0]; + let mut h = harness(app); + type_in(&mut h, "#336699"); + let cms = vectorcraft_color::cms::active(); + let want = cms.to_cmyk(&Color::rgb8(0x33, 0x66, 0x99), cms.settings().intent); + let Color::Cmyk { c, m, y, k } = fill_color(h.state(), id) else { panic!("a CMYK color: {:?}", fill_color(h.state(), id)) }; + assert_eq!([c, m, y, k], want); +} + +/// The alpha sets the opacity while the opacity row is hidden too, and text without an alpha keeps +/// the opacity. +#[test] +fn the_alpha_applies_without_the_opacity_row_and_no_alpha_keeps_the_opacity() { + let app = app(); + let id = selected(&app)[0]; + let mut h = harness(app); + type_in(&mut h, "rgb(51 102 153 / 25%)"); + assert_eq!(rgb8(&fill_color(h.state(), id)), [51, 102, 153]); + assert_eq!(h.state().session.proxy_opacity(false), Some(0.25)); + type_in(&mut h, "hsl(0 100% 50%)"); + assert_eq!(rgb8(&fill_color(h.state(), id)), [255, 0, 0]); + assert_eq!(h.state().session.proxy_opacity(false), Some(0.25), "no alpha in the text: the opacity stays"); + type_in(&mut h, "oklch(62.8% 0.2577 29.23 / 1)"); + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); +} + +/// With nothing selected, `#33669980` sets the default fill to #336699 and changes no opacity. +#[test] +fn with_nothing_selected_the_color_goes_to_the_defaults_without_the_alpha() { + let mut app = app(); + app.run("select.none", json!({})).unwrap(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + assert_eq!(h.state().session.paint.fill.color().map(|c| rgb8(&c)), Some([0x33, 0x66, 0x99])); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc, "no object changed"); +} + +/// With a rectangle and a type object with no fill item selected, `#33669980` sets both fills to +/// #336699 and the rectangle's fill opacity to 50.2 %. +#[test] +fn a_selection_mixing_type_and_art_takes_the_color_and_the_alpha_where_it_can() { + let mut app = app(); + let rect = selected(&app)[0]; + let text = app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [rect.0, text]})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let app = h.state(); + assert_eq!(rgb8(&fill_color(app, rect)), [0x33, 0x66, 0x99]); + let fill = app.session.doc().unwrap().doc.node(rect).unwrap().appearance.fill_at(None).map(|f| f.opacity); + assert!(fill.is_some_and(|o| (o - 0.502).abs() < 1e-4), "{fill:?}"); + let text_node = app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(text)).unwrap().appearance.clone(); + assert!(text_node.fill_at(None).is_none(), "the type object takes no fill item, so no alpha: {text_node:?}"); + h.state_mut().run("select.set", json!({"ids": [text]})).unwrap(); + let (fill, _) = h.state().session.proxy_paints(); + assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the type's characters take the color: {fill:?}"); +} + +/// Retyping the color and opacity the selection has, in another form, records no undo step; an +/// alpha that differs from the opacity by less than the field shows is still applied. +#[test] +fn retyping_the_shown_color_in_another_form_changes_nothing() { + let mut app = app(); + app.run("paint.setFill", json!({"opacity": 50})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + for same in ["rgb(255 0 0 / 50%)", "rgb(100% 0% 0% / 0.5)", "#f00", "hsl(0 100% 50%)"] { + type_in(&mut h, same); + assert_eq!(undo_count(h.state()), before, "{same}"); + assert!(h.state().ui.status.is_empty(), "{same}: {}", h.state().ui.status); + } + type_in(&mut h, "#00ff00"); + assert_eq!(undo_count(h.state()), before + 1, "another color is applied"); + h.state_mut().run("paint.setFill", json!({"opacity": 99.9})).unwrap(); + h.run_steps(2); + assert_eq!(shown(&h), "00FF00", "99.9 % shows no alpha"); + let before = undo_count(h.state()); + type_in(&mut h, "#00ff00ff"); + assert_eq!(undo_count(h.state()), before + 1, "the alpha ff sets 100 %"); + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); +} + +/// Retyping a gradient stop's or a freeform point's color, with or without its alpha, records no +/// step. +#[test] +fn retyping_a_stop_color_changes_nothing() { + for gradient in [json!({}), json!({"kind": "freeform"})] { + let mut app = app(); + app.run("paint.setFill", json!({ "gradient": gradient })).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let before = undo_count(h.state()); + type_in(&mut h, "#33669980"); + type_in(&mut h, "#369"); + assert_eq!(undo_count(h.state()), before, "{gradient}"); + } +} + +/// Retyping the color of a global swatch's tint unlinks the fill from the swatch in one step. +#[test] +fn retyping_a_tint_color_unlinks_the_swatch() { + let mut app = app(); + app.run("swatch.new", json!({"name": "Ink", "color": "#ff0000", "spot": true})).unwrap(); + app.run("paint.setFill", json!({"swatch": "Ink", "tint": 100})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + assert_eq!(shown(&h), "FF0000"); + type_in(&mut h, "#ff0000"); + assert_eq!(undo_count(h.state()), before + 1); + let Paint::Solid { swatch, .. } = crate::panels::current_paints(h.state()).0 else { panic!("a solid fill") }; + assert_eq!(swatch, None); +} + +/// A click on the wheel that takes the focus from an edited field applies the text, then the +/// click's pick to the target the text left: a gradient stop keeps the typed alpha. +#[test] +fn a_wheel_click_after_typing_applies_both() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").type_text("#33669980"); + h.run_steps(1); + h.get_by_label("Saturation and brightness").click(); + h.run_steps(2); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert!((stop.opacity - 0.502).abs() < 1e-4, "the typed alpha stays: {}", stop.opacity); + let hex = stop.color.to_hex(); + assert_ne!(hex, "#336699", "the click picked a color"); + let ch = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).unwrap(); + assert!(ch(5) >= ch(3) && ch(3) >= ch(1), "the pick keeps the typed hue: {hex}"); + assert_eq!(undo_count(h.state()), before + 2); +} + +/// A selected gradient stop takes the color and the alpha in one step. +#[test] +fn a_gradient_stop_takes_the_color_and_the_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[0]; + assert_eq!(stop.color.to_hex(), "#336699"); + assert!((stop.opacity - 0.502).abs() < 1e-4, "{}", stop.opacity); +} + +/// A selected freeform point takes the color and the alpha. +#[test] +fn a_freeform_point_takes_the_color_and_the_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {"kind": "freeform"}})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let f = super::gradient::shown_points(&g); + assert_eq!(f.points[0].color.to_hex(), "#336699"); + assert!((f.points[0].opacity - 0.502).abs() < 1e-4, "{}", f.points[0].opacity); +} + +/// Text `color.parse` refuses changes nothing and shows its error in the status bar. +#[test] +fn refused_text_changes_nothing_and_says_why() { + let app = app(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + for bad in ["#12345", "rgb(1, 2%, 3)", "not a color", "cmyk(0 0 0 0)"] { + type_in(&mut h, bad); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc, "{bad}"); + assert!(h.state().ui.status.contains("must be a hex color"), "{bad}: {}", h.state().ui.status); + } + assert_eq!(shown(&h), "FF0000", "the field shows the color again"); + h.state_mut().ui.status.clear(); + h.get_by_role_and_label(Role::TextInput, "Hex or CSS color").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.key_press(egui::Key::Backspace); + h.run_steps(1); + h.key_press(egui::Key::Enter); + h.run_steps(2); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc, "an emptied field"); + assert!(h.state().ui.status.contains("must be a hex color"), "an emptied field: {}", h.state().ui.status); +} + +/// The Color panel's hex field still takes only 3 or 6 digits. +#[test] +fn the_color_panels_hex_field_still_refuses_an_alpha() { + assert_eq!(super::color::parse_hex("336699").map(|c| c.to_hex()), Some("#336699".into())); + assert_eq!(super::color::parse_hex("33669980"), None); + assert_eq!(super::color::parse_hex("3698"), None); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index b794dc3c54..6f83219b72 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -216,6 +216,39 @@ fn an_opacity_edit_keeps_the_hue_picked_for_a_white_stop() { assert_eq!(ring(&h), Some(120.0), "the ring keeps the hue after the opacity edit"); } +/// The OKLCH hue picked last for a white gradient stop stays on the OKLCH Hue row after the row +/// sets the stop's opacity. +#[test] +fn an_opacity_edit_keeps_the_oklch_hue_picked_for_a_white_stop() { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ffffff"}, {"offset": 1, "color": "#0000ff"}]); + app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [10, 35], "end": [60, 35]}})).unwrap(); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 0})).unwrap(); + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 480.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + let hue_row = |h: &Harness<'static, VectorcraftApp>| { + let node = h.query_all_by_label("Hue").find(|n| n.accesskit_node().role() == Role::Slider).expect("the OKLCH Hue row"); + (node.accesskit_node().locate(), node.accesskit_node().numeric_value()) + }; + let ((target_node, target_tree), _) = hue_row(&h); + let data = Some(ActionData::NumericValue(120.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + h.run_steps(2); + assert_eq!(hue_row(&h).1, Some(120.0), "the Hue row shows the hue picked for white"); + action(&mut h, Action::SetValue, Some(ActionData::NumericValue(30.0))); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + assert!((g.gradient.stops[0].opacity - 0.3).abs() < 1e-6, "{:?}", g.gradient.stops); + assert_eq!(hue_row(&h).1, Some(120.0), "the Hue row keeps the hue after the opacity edit"); +} + /// A drag across the slider previews and ends as one undo step named Opacity. #[test] fn a_drag_is_one_undo_step() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 61112e0fa8..d0126ad9c4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -265,9 +265,10 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, opacity?, sliders?}` shows the -wheel or the box (a color field with a channel strip at its right), picks the box's channel, checks or unchecks Show -Opacity (an opacity row under the wheel or the box), and shows or hides OKLCH Sliders (`sliders: "oklch"` is an error +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, opacity?, hexField?, sliders?}` +shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, checks or +unchecks Show Opacity (an opacity row under the wheel or the box) and Show Hex Field (a field for a hex or CSS color), +and shows or hides OKLCH Sliders (`sliders: "oklch"` is an error while the working RGB space is not sRGB); it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ diff --git a/docs/mcp.md b/docs/mcp.md index ec6aba71ea..0ee7ffec55 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -656,13 +656,37 @@ selected gradient stop or the selected freeform point (the first stop or point w hides the row. The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. 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, opacity, sliders}`, and the settings are kept with the preferences. +returns `{view, channel, opacity, hexField, sliders}`, and the settings are kept with the preferences. `ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or the box), and `"none"` hides them; `"oklch"` is an error while the working RGB space is not sRGB. `color.convert {"to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. A color outside sRGB (a Lab or CMYK color, or an RGB color in a wider working RGB space) is clipped to sRGB first. +`ui.colorWheel {"hexField": true}` checks Show Hex Field, as the panel menu does, and `false` unchecks it. The field +under the wheel or the box shows the color's six hex digits, and two more for the opacity while the opacity that Show +Opacity edits is under 100 %. A text typed into it is read as `color.parse` reads it. The color is applied as a pick +on the wheel is, and an alpha in the text sets the opacity that Show Opacity edits, whether or not that row shows. +Where that row is gray (nothing selected, an object selected in a symbol instance, or a fill or stroke row on type +characters or missing), only the color is applied. Text without an alpha keeps the opacity. Text that gives the +color and opacity already there records no undo step, unless the color is a tint of a global swatch. A text `color.parse` refuses changes nothing, and its +error shows in the status bar. + +`color.parse {"text": "#33669980"}` answers `{"color": {"model": "rgb", …}, "hex": "#336699", "opacity": 50.2}`. +The text is a [hex color](https://www.w3.org/TR/css-color-4/#hex-notation) of 3, 4, 6 or 8 digits, with or without +the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-functions), +[`hsl()` or `hsla()`](https://www.w3.org/TR/css-color-4/#the-hsl-notation) or +[`oklch()`](https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch) color. The functions take the +space-separated form with an optional `/ alpha`, and `rgb()` and `hsl()` also take the comma-separated legacy form. +Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting spaces around it. A hex +color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as `#rrggbb` does in every command, and +`oklch()` gives its sRGB color, with the chroma lowered to fit sRGB as OKLCH Sliders lower it; `oklch()` is an error +while the working RGB space is not sRGB. Values are clamped where CSS clamps them when it parses them (red, green +and blue to 0 to 255, the alpha to 0 to 1, a negative saturation to 0, OKLCH lightness to 0 to 1 and a negative +chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. `opacity` is the alpha +as a percentage, or `null` when the text gives none. Any other text is an error. The color parameters of the other +commands still refuse `#rrggbbaa` and `#rgba`. + 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 portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index debd7721b1..a68ec54023 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1645,7 +1645,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. - VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. Scores and estimates are unchanged. + VectorCraft's own Show Opacity in the Color Wheel panel menu (part of #978) adds a slider and a percent field that set the opacity of what the wheel edits: the fill or stroke row (`paint.setFill {opacity}`; fill and stroke opacity can differ, as [Apply transparency to artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/apply-transparency-to-artwork.html) describes), the selected gradient stop or the selected freeform point (the first one when none is selected). The row is gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke row it would set is on type characters or missing. VectorCraft's own Show Hex Field in the same menu (`ui.colorWheel {hexField: true}`, kept with the preferences) adds a field that shows the color's six hex digits, and two more for an opacity under 100 %; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. The item is gray, and `ui.colorWheel` answers an error, while the working RGB space is not sRGB. `color.convert {to: "oklch"}` answers the same L, C and H. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. - **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").