From 47d6facb74b66fcc3055f936c8aa45c614e7c1e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 22:34:37 -0800 Subject: [PATCH 01/28] Part of #978: Show Hex Field in the Color Wheel panel takes hex with an alpha and CSS colors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Panel menu › Show Hex Field (ui.colorWheel {hexField}) adds a field under the wheel or the box. It 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. A typed color is applied in the same way as a wheel pick, in one undo step, and an alpha sets that opacity, whether or not the opacity row shows. Where the opacity 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 that gives the color and opacity already there records no undo step, unless the color is a tint of a global swatch. A click on the wheel that takes the focus from an edited field applies the text, then the click. An opacity edit of a gradient stop or point keeps the OKLCH values picked last for it, as it keeps the HSB. - crates/color/src/css.rs reads the hex, rgb(), rgba(), hsl(), hsla() and oklch() syntax of CSS Color 4, the comma-separated legacy form of rgb() and hsl() included, and clamps values where CSS clamps them when it parses them. VectorCraft's own rules on top of that: the # of a hex color may be left out, none reads as 0, an hsl() channel outside the sRGB range is clipped, an oklch() color outside sRGB takes the largest chroma that fits, and text over 48 characters is refused. - color.parse {text} answers {color, hex, opacity}; oklch() is an error while the working RGB space is not sRGB. - The Color panel's hex field and the color parameters of other commands still refuse #rrggbbaa and #rgba. Docs: docs/mcp.md, docs/control-protocol.md, docs/target-app-parity.md. --- crates/color/src/css.rs | 417 ++++++++++++++++++ crates/color/src/lib.rs | 1 + crates/engine/src/cmd/colorcmds.rs | 25 ++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/tests/colormgmt.rs | 42 ++ crates/engine/tests/color_settings.rs | 17 + crates/engine/tests/command_sweep.rs | 5 + crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 4 + crates/ui-egui/src/i18n/bs.tsv | 4 + crates/ui-egui/src/i18n/ca.tsv | 4 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/da.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fi.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 4 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ka.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/sv.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/vi.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels.rs | 2 + crates/ui-egui/src/panels/color_wheel.rs | 141 +++++- .../ui-egui/src/panels/tests_color_wheel.rs | 2 +- .../src/panels/tests_color_wheel_box.rs | 16 +- .../src/panels/tests_color_wheel_hex.rs | 329 ++++++++++++++ .../src/panels/tests_color_wheel_opacity.rs | 33 ++ docs/control-protocol.md | 7 +- docs/mcp.md | 26 +- docs/target-app-parity.md | 2 +- 46 files changed, 1151 insertions(+), 30 deletions(-) create mode 100644 crates/color/src/css.rs create mode 100644 crates/ui-egui/src/panels/tests_color_wheel_hex.rs 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"). From b7bef0a3086c11c3ac191b4a65a873e6c6544818 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 01:20:26 -0800 Subject: [PATCH 02/28] Color Wheel: the hex field keeps an opacity press, and color.parse takes only CSS whitespace - A text committed when a press on the opacity slider takes the focus is applied to the target read again, so it keeps the opacity the press set, and the field compares the text with what it showed before the press, so the text is not dropped. - color.parse takes only spaces, tabs and line breaks around the text and its arguments (https://www.w3.org/TR/css-syntax-3/#whitespace); a no-break or ideographic space makes the text an error. - The texts name the hsl() refusal for saturation and lightness so large that a channel overflows, and say the field shows the alpha when the opacity rounds to less than ff. - color.parse's params text keeps the forms of the text inside parentheses, so every_description_parses reads it as one key. - A test types a color with only a type object selected: the characters take the color and no fill item is added for the alpha. --- crates/color/src/css.rs | 30 ++++++++-- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 37 ++++++++---- .../src/panels/tests_color_wheel_hex.rs | 60 ++++++++++++++++++- docs/control-protocol.md | 3 +- docs/mcp.md | 22 +++---- docs/target-app-parity.md | 2 +- 9 files changed, 124 insertions(+), 36 deletions(-) diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 4d699854ce..6fa17e0df1 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -35,12 +35,15 @@ pub struct CssColor { /// 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 +/// to 0..=1 and chroma to 0 or more. `none` reads as 0, as CSS reads a missing component when it +/// converts a color. Spaces, tabs and line breaks may surround the text and its arguments; other +/// whitespace is not CSS whitespace and makes the text invalid. 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. +/// colors into the gamut by its own rules instead. An `hsl()` color whose saturation and lightness +/// are so large that a channel overflows to an infinity is refused. pub fn parse(text: &str) -> Option { - let text = text.trim(); + let text = css_trim(text); if text.chars().nth(MAX_CHARS).is_some() { return None; } @@ -63,6 +66,12 @@ pub fn parse(text: &str) -> Option { } } +/// `s` without the CSS whitespace (spaces, tabs and line breaks) around it +/// (). +fn css_trim(s: &str) -> &str { + s.trim_matches(|c: char| c.is_ascii_whitespace()) +} + /// `#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); @@ -107,7 +116,7 @@ fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, boo if !legacy_allowed || args.contains('/') { return None; } - let mut parts: Vec<&str> = args.split(',').map(str::trim).collect(); + let mut parts: Vec<&str> = args.split(',').map(css_trim).collect(); let alpha = if parts.len() == 4 { parts.pop() } else { None }; (parts, alpha, true) } else { @@ -117,7 +126,7 @@ fn split(args: &str, legacy_allowed: bool) -> Option<([Arg; 3], Option, boo if halves.next().is_some() { return None; } - (colors.split_ascii_whitespace().collect(), alpha.map(str::trim), false) + (colors.split_ascii_whitespace().collect(), alpha.map(css_trim), false) }; let [a, b, c] = parts.as_slice() else { return None }; let one = |s: &str| { @@ -328,6 +337,15 @@ mod tests { } } + #[test] + fn only_spaces_tabs_and_line_breaks_are_whitespace() { + assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None)); + assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128))); + for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)"] { + 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)); diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index a68eca7e5c..071f2ed3f7 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "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", + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in 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, the spaces, tabs and line breaks 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; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", always, parse_color ), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index d456e8282f..a63f637069 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, 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}", + "{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 when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; 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/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 092efd23f5..bafb8c61cc 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, 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}", + "{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 when the opacity rounds to less than ff) and takes a hex color of 3, 4, 6 or 8 digits or a CSS rgb(), hsl() or oklch() color, read as color.parse reads it, whose alpha sets the opacity Show Opacity edits when there is one to set; 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/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index d2f787298b..4843c19a63 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -25,10 +25,11 @@ //! 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. +//! hex digits, and two more when the opacity that Show Opacity sets rounds to less than `ff`. It +//! takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color +//! (`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}; @@ -392,7 +393,7 @@ 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. +/// when the opacity rounds to less than `ff`. 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); @@ -437,23 +438,30 @@ fn apply_typed(app: &mut VectorcraftApp, tgt: &Target, c: Color, alpha: Option) -> bool { +/// The text the hex field shows for `tgt` and its color, as [`hex_text`] gives it. +fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> String { let (o, live) = shown_opacity(app, tgt); - let shown = hex_text(color, live.then_some(o)); + hex_text(color, live.then_some(o)) +} + +/// The Show Hex Field row: a `#` and a field as wide as the row, showing `shown`. 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, shown: &str) -> bool { 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); + 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 target is read again, so a text committed when a press on the opacity row takes + // the focus keeps the opacity that press set. + let tgt = &wheel_target(app, ui); // 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); @@ -721,6 +729,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.add_space(4.0); picked_lch = oklch_rows(app, ui, &tgt, color, &cms); } + // The hex field compares its text with what it showed before an opacity edit of this frame, so + // a text committed when a press on the opacity row takes the focus is not dropped. + let hex = app.ui.color_wheel.hex_field.then(|| hex_shown(app, &tgt, color.as_ref())); if app.ui.color_wheel.opacity { let shown = color.unwrap_or(app.session.last_solid); let owner = color.map(|c| Owner::of(app, &tgt, c)); @@ -743,11 +754,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } } - if app.ui.color_wheel.hex_field { + if let Some(hex) = hex { 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()) { + if hex_row(app, ui, &hex) { return; } } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index ce4a1afbe6..7518cf6d2d 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -91,7 +91,7 @@ fn show_hex_field_is_a_setting_of_the_panel() { 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 %. +/// The field shows six digits, and two more when the opacity rounds to less than `ff`. #[test] fn the_field_shows_the_alpha_only_under_full_opacity() { let h = harness(app()); @@ -189,6 +189,21 @@ fn a_selection_mixing_type_and_art_takes_the_color_and_the_alpha_where_it_can() assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the type's characters take the color: {fill:?}"); } +/// With only a type object selected, where the opacity row is gray, `#33669980` sets the +/// characters' color and adds no fill item for the alpha. +#[test] +fn with_only_type_selected_the_color_applies_without_the_alpha() { + let mut app = app(); + let text = app.run("text.create", json!({"x": 10, "y": 150, "text": "Hi"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [text]})).unwrap(); + let mut h = harness(app); + type_in(&mut h, "#33669980"); + let (fill, _) = h.state().session.proxy_paints(); + assert_eq!(fill.color().map(|c| c.to_hex()), Some("#336699".into()), "the characters take the color: {fill:?}"); + let node = h.state().session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(text)).unwrap().appearance.clone(); + assert!(node.fill_at(None).is_none(), "no fill item for the alpha: {node:?}"); +} + /// 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] @@ -270,6 +285,49 @@ fn a_wheel_click_after_typing_applies_both() { assert_eq!(undo_count(h.state()), before + 2); } +/// A press on the opacity slider that takes the focus from an edited field applies the text and +/// keeps the opacity the press set: a gradient stop takes both. +#[test] +fn an_opacity_press_after_typing_keeps_both() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + 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("#336699"); + h.run_steps(1); + h.get_by_role_and_label(Role::Slider, "Opacity").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_eq!(stop.color.to_hex(), "#336699", "the text applies"); + assert!(stop.opacity < 0.9, "the press sets the opacity: {}", stop.opacity); +} + +/// The same for a solid fill: the rectangle takes the typed color and the opacity the press set. +#[test] +fn an_opacity_press_after_typing_keeps_both_on_a_solid_fill() { + let mut app = app(); + let rect = selected(&app)[0]; + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + 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("#336699"); + h.run_steps(1); + h.get_by_role_and_label(Role::Slider, "Opacity").click(); + h.run_steps(2); + let app = h.state(); + assert_eq!(rgb8(&fill_color(app, rect)), [0x33, 0x66, 0x99], "the text applies"); + 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.9), "the press sets the opacity: {fill:?}"); +} + /// A selected gradient stop takes the color and the alpha in one step. #[test] fn a_gradient_stop_takes_the_color_and_the_alpha() { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d0126ad9c4..cd7811b8c3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -268,8 +268,7 @@ pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint. 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`. +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`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, diff --git a/docs/mcp.md b/docs/mcp.md index 0ee7ffec55..80a887ab68 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -664,13 +664,13 @@ the box), and `"none"` hides them; `"oklch"` is an error while the working RGB s (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. +under the wheel or the box shows the color's six hex digits, and two more for the opacity when the opacity that Show +Opacity edits rounds to less than `ff`. 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. When +`color.parse` refuses the text, the field does not change the color and the status bar shows the error. `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 @@ -678,12 +678,14 @@ the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-f [`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 +Hues take `deg`, `grad`, `rad` and `turn`, and `none` reads as 0. The text has at most 48 characters, not counting +the spaces, tabs and line breaks around it; other whitespace makes the text an error. 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 +chroma to 0), and an `hsl()` color's red, green or blue outside 0 to 255 is clipped. An `hsl()` color whose +saturation and lightness are so large that a channel overflows to an infinity is an error. `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`. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a68ec54023..3ea05ecde0 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. 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. + 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 when the opacity rounds to less than `ff`; it takes a hex color of 3, 4, 6 or 8 digits and a CSS `rgb()`, `hsl()` or `oklch()` color (https://www.w3.org/TR/css-color-4/#hex-notation, https://www.w3.org/TR/css-color-4/#rgb-functions, https://www.w3.org/TR/css-color-4/#the-hsl-notation, https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), and an alpha sets that opacity. `color.parse {text}` answers the color, its hex and the alpha. The Color panel's hex field still takes 3 or 6 digits. Evidence: the `css` tests in `crates/color/src/css.rs`, a property test of random text among them; `parse_reads_hex_with_alpha_and_css_colors` in `crates/engine/src/tests/colormgmt.rs`; `crates/ui-egui/src/panels/tests_color_wheel_hex.rs`. Scores and estimates are unchanged. - **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"). From ca3d617531f7b1915657169aab9fb6da0d1196e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 03:50:05 -0800 Subject: [PATCH 03/28] Color Wheel: a pick in the frame of an opacity edit keeps the stop's opacity The wheel and the OKLCH rows applied a pick to the gradient stops read at the start of the frame, so an opacity edit of a stop in the same frame was written back to its old value. The panel now reads the stops again after the opacity row sets them. --- crates/ui-egui/src/panels/color_wheel.rs | 17 ++++-- .../src/panels/tests_color_wheel_opacity.rs | 55 +++++++++++++++++++ 2 files changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 4843c19a63..ff6b8a1b4d 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -365,8 +365,9 @@ fn apply_opacity(app: &mut VectorcraftApp, tgt: &Target, o: f32, phase: Live) { } /// The Show Opacity row: the Transparency panel's icon, a slider whose track shows `color` from -/// clear to solid, and a percent field. Gray when [`shown_opacity`] finds nothing to set. -fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Color) { +/// clear to solid, and a percent field. Gray when [`shown_opacity`] finds nothing to set. True when +/// it set the opacity. +fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Color) -> bool { let (o, live) = shown_opacity(app, tgt); let percent = f64::from(o) * 100.0; let mut edit: Option<(f32, Live)> = None; @@ -386,9 +387,9 @@ fn opacity_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, color: &Colo } }); }); - if let Some((v, phase)) = edit.filter(|_| live) { - apply_opacity(app, tgt, v, phase); - } + let Some((v, phase)) = edit.filter(|_| live) else { return false }; + apply_opacity(app, tgt, v, phase); + true } /// The text the hex field shows for `color` and the opacity `o` the row of Show Opacity edits @@ -732,10 +733,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The hex field compares its text with what it showed before an opacity edit of this frame, so // a text committed when a press on the opacity row takes the focus is not dropped. let hex = app.ui.color_wheel.hex_field.then(|| hex_shown(app, &tgt, color.as_ref())); + let mut opacity_set = false; if app.ui.color_wheel.opacity { let shown = color.unwrap_or(app.session.last_solid); let owner = color.map(|c| Owner::of(app, &tgt, c)); - opacity_row(app, ui, &tgt, &shown); + opacity_set = opacity_row(app, ui, &tgt, &shown); // An opacity edit of a gradient stop or point changes the gradient its owner holds, and the // HSB and the OKLCH picked last stay with the new gradient. if let (Some(c), Some(was)) = (color, owner) { @@ -762,6 +764,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } } + // A pick or an OKLCH edit read in the frame of an opacity edit goes to the stops as that edit + // left them, so the stop keeps both. + let tgt = if opacity_set { wheel_target(app, ui) } else { tgt }; 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_opacity.rs b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs index 6f83219b72..f8d2d5550c 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_opacity.rs @@ -249,6 +249,61 @@ fn an_opacity_edit_keeps_the_oklch_hue_picked_for_a_white_stop() { assert_eq!(hue_row(&h).1, Some(120.0), "the Hue row keeps the hue after the opacity edit"); } +/// Asks screen readers to set the opacity row to `opacity` and `label`'s slider to `value` in one +/// frame (`Harness::event` would give each request a frame of its own). +fn set_both(h: &mut Harness<'static, VectorcraftApp>, opacity: f64, (label, value): (&str, f64)) { + let (target_node, target_tree) = h.get_by_role_and_label(Role::Slider, "Opacity").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(opacity)); + let set_opacity = Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data }); + let node = h.query_all_by_label(label).find(|n| n.accesskit_node().role() == Role::Slider).expect("the slider"); + let (target_node, target_tree) = node.accesskit_node().locate(); + let data = Some(ActionData::NumericValue(value)); + let set_value = Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data }); + h.input_mut().events.extend([set_opacity, set_value]); + h.run_steps(2); +} + +/// A gradient stop with stops red and blue, the first selected. +fn stop_app() -> VectorcraftApp { + let mut app = app(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"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 +} + +/// An opacity edit and a pick on the ring in one frame: the stop keeps both. +#[test] +fn an_opacity_edit_and_a_ring_pick_in_one_frame_keep_both() { + let mut h = harness(stop_app()); + set_both(&mut h, 30.0, ("Hue ring", 120.0)); + 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.3).abs() < 1e-6, "the stop keeps the opacity: {:?}", g.gradient.stops); + assert_ne!(super::color::hex_digits(&stop.color), "FF0000", "the stop takes the pick: {:?}", g.gradient.stops); +} + +/// An opacity edit and an OKLCH Hue edit in one frame: the stop keeps both. +#[test] +fn an_opacity_edit_and_an_oklch_edit_in_one_frame_keep_both() { + let mut app = stop_app(); + 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); + set_both(&mut h, 30.0, ("Hue", 140.0)); + 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.3).abs() < 1e-6, "the stop keeps the opacity: {:?}", g.gradient.stops); + assert_ne!(super::color::hex_digits(&stop.color), "FF0000", "the stop takes the edit: {:?}", g.gradient.stops); +} + /// A drag across the slider previews and ends as one undo step named Opacity. #[test] fn a_drag_is_one_undo_step() { From 0941850e4959933887d58be2b5802a48151aa858 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:06:34 -0800 Subject: [PATCH 04/28] i18n: French row takes a no-break space before the colon --- crates/ui-egui/src/i18n/fr.tsv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index a160e37f5e..acf19bb533 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6697,7 +6697,7 @@ axis Y Axis Axe Y @msg `opacity` must be a number `opacity` doit être un nombre @msg `opacity` must be a number from 0 to 100 `opacity` doit être un nombre compris entre 0 et 100 @msg `opacity` must be true or false `opacity` doit valoir true ou false -@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect +@msg type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke les caractères du texte n’ont pas d’opacité propre : ajoutez un fond ou un contour avec Ajouter un nouveau fond ou Ajouter un nouveau contour dans le panneau Aspect @msg an object selected in a symbol instance has no fill or stroke opacity of its own un objet sélectionné dans une occurrence de symbole n’a pas d’opacité de fond ou de contour propre @msg no target has that fill or stroke to take the opacity aucune cible n’a ce fond ou ce contour pour recevoir l’opacité @msg `type` must be "path" or "compound" `type` doit valoir "path" ou "compound" From fdf4f77a2d547f028be908b2c4f70ad55378597b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 16:26:01 -0800 Subject: [PATCH 05/28] Color Wheel: a typed hex text stays with the object it was typed for The hex field's id now names the document, the selection, the Type tool's characters, the appearance item, the proxy and the gradient stop or freeform point. A text typed for one object is dropped when another one is targeted, even one showing the same hex, so Enter no longer applies it there. color.parse's docs list form feeds with the whitespace it accepts around the text. --- crates/color/src/css.rs | 13 +++++---- crates/engine/src/cmd/colorcmds.rs | 2 +- crates/ui-egui/src/panels/color_wheel.rs | 21 ++++++++++---- .../src/panels/tests_color_wheel_hex.rs | 29 +++++++++++++++++++ docs/mcp.md | 18 ++++++------ 5 files changed, 62 insertions(+), 21 deletions(-) diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index 6fa17e0df1..c8b1e84ab2 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -36,8 +36,8 @@ pub struct CssColor { /// [`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, as CSS reads a missing component when it -/// converts a color. Spaces, tabs and line breaks may surround the text and its arguments; other -/// whitespace is not CSS whitespace and makes the text invalid. An `hsl()` color whose red, green or +/// converts a color. Spaces, tabs, line breaks and form feeds may surround the text and its +/// arguments; other whitespace is not CSS whitespace and makes the text invalid. 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. An `hsl()` color whose saturation and lightness @@ -66,8 +66,9 @@ pub fn parse(text: &str) -> Option { } } -/// `s` without the CSS whitespace (spaces, tabs and line breaks) around it -/// (). +/// `s` without the CSS whitespace (spaces, tabs, line breaks and form feeds, which CSS reads as line +/// breaks) around it (, +/// ). fn css_trim(s: &str) -> &str { s.trim_matches(|c: char| c.is_ascii_whitespace()) } @@ -341,7 +342,9 @@ mod tests { fn only_spaces_tabs_and_line_breaks_are_whitespace() { assert_eq!(bytes("\t rgb(51,\n102 ,\t153)\r\n"), ([51, 102, 153], None)); assert_eq!(bytes("rgb(51 102 153 /\t0.5 )"), ([51, 102, 153], Some(128))); - for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)"] { + assert_eq!(bytes("\u{c}#336699\u{c}"), ([51, 102, 153], None), "CSS reads a form feed as a line break"); + assert_eq!(bytes("rgb(51\u{c}102\u{c}153)"), ([51, 102, 153], None)); + for bad in ["rgb(51,\u{a0}102,153)", "rgb(51,102,153\u{3000})", "\u{a0}#336699", "#336699\u{2003}", "rgb(0 0 0 /\u{a0}1)", "\u{b}#336699"] { assert_eq!(parse(bad), None, "{bad:?}"); } } diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 071f2ed3f7..8890f9eec9 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Parse Color", [], None, - "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in 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, the spaces, tabs and line breaks 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; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in 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, the spaces, tabs, line breaks and form feeds 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; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", always, parse_color ), diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index c6872ac689..a0f0584ef2 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -445,16 +445,25 @@ fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> Strin hex_text(color, live.then_some(o)) } -/// The Show Hex Field row: a `#` and a field as wide as the row, showing `shown`. 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, shown: &str) -> bool { +/// The hex field's id for `tgt`: it names the document, the selected objects or text characters, +/// the appearance item, the proxy and the gradient stop or freeform point, but not the color, so a +/// text typed for one of them is dropped when another one is targeted, even one showing the same hex. +fn hex_field_id(app: &VectorcraftApp, tgt: &Target) -> impl std::hash::Hash + use<> { + let o = Owner::of(app, tgt, Color::rgb8(0, 0, 0)); + ("color-wheel-hex", o.doc, o.selection, o.text_selection, o.appearance_item, o.fill, o.slot) +} + +/// The Show Hex Field row for `tgt`: a `#` and a field as wide as the row, showing `shown`. 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, shown: &str) -> bool { let mut typed = None; + let id = hex_field_id(app, tgt); 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); + typed = widgets::text_field_named(ui, id, 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 })) { @@ -760,7 +769,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { 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, &hex) { + if hex_row(app, ui, &tgt, &hex) { return; } } diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index 7518cf6d2d..e53a7d203e 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -285,6 +285,35 @@ fn a_wheel_click_after_typing_applies_both() { assert_eq!(undo_count(h.state()), before + 2); } +/// A text typed for one rectangle is dropped when the selection changes to another showing the same +/// hex: Enter then changes neither of them. +#[test] +fn a_text_typed_for_one_object_does_not_go_to_another_with_the_same_hex() { + let mut app = app(); + let a = selected(&app)[0]; + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let b = selected(&app)[0]; + app.run("select.set", json!({"ids": [a]})).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.state_mut().run("select.set", json!({"ids": [b]})).unwrap(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + for id in [a, b] { + assert_eq!(rgb8(&fill_color(h.state(), id)), [255, 0, 0]); + } + assert_eq!(h.state().session.proxy_opacity(false), Some(1.0)); + assert_eq!(undo_count(h.state()), before, "nothing was applied"); +} + /// A press on the opacity slider that takes the focus from an edited field applies the text and /// keeps the opacity the press set: a gradient stop takes both. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 258f173cd8..b383cff868 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -701,15 +701,15 @@ the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-f [`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 -the spaces, tabs and line breaks around it; other whitespace makes the text an error. 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. An `hsl()` color whose -saturation and lightness are so large that a channel overflows to an infinity is an error. `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`. +the spaces, tabs, line breaks and form feeds around it; other whitespace, such as a vertical tab or a no-break space, +makes the text an error. 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. An `hsl()` color whose saturation and lightness are so large that a channel overflows to an infinity is an +error. `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 From 29a379ad5eaba6b20513eb83ccda1ea23818bcd2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:17:19 -0800 Subject: [PATCH 06/28] Color Wheel: a click that commits a typed hex keeps both edits - A click on the wheel, the box or an OKLCH row whose press and release come in the frame that commits the hex field's text is applied after the text, at the components the text gave; a text that leaves the color as it was keeps the remembered hue. - A click on the opacity row that commits a text with an alpha keeps the opacity the click set. - The field passes its text to color.parse as typed, so a no-break space is refused as color.parse refuses it. - A text typed for one object of a symbol instance is dropped when another object of the same instance is selected. - Tests cover explicit null for every ui.colorWheel key and check that a gray OKLCH row returns no edit. --- crates/ui-egui/src/panels/color_wheel.rs | 107 ++++++++++++----- .../ui-egui/src/panels/tests_color_wheel.rs | 24 +++- .../src/panels/tests_color_wheel_hex.rs | 111 ++++++++++++++++++ 3 files changed, 207 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 126f5abfec..95847e2c51 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -307,9 +307,9 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { } /// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with -/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, +/// markers when `marked`. Returns what a click, a drag, a key or a screen reader's action picks, /// and its phase. -fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<(Picked, Live)> { let (z, x, y) = box_pos(ch, hsb); let mut pick = None; ui.horizontal_top(|ui| { @@ -317,21 +317,50 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { - pick = Some((box_pick(ch, z, x, y, hsb), phase)); + pick = Some((Picked::Field(ch, x, y), phase)); } // The hue strip shows the whole spectrum; the others change only their own component. let track = |z: f32| widgets::hsb32(if ch == Channel::Hue { [z * 360.0, 1.0, 1.0] } else { box_pick(ch, z, x, y, hsb) }); let (v, suffix, max) = strip_number(ch, hsb); let shown = SliderValue::field(v, 0.0..=max, suffix, 0); match widgets::channel_slider_stepped(ui, "color-wheel-strip", ch.name(), Some(shown), z, marked, vec2(STRIP, size), &track) { - (Some(z), phase, _) => pick = Some((box_pick(ch, z, x, y, hsb), phase)), - (None, _, Some(v)) => pick = Some((box_pick(ch, (v / max) as f32, x, y, hsb), Live::Released)), + (Some(z), phase, _) => pick = Some((Picked::Strip(ch, z), phase)), + (None, _, Some(v)) => pick = Some((Picked::Strip(ch, (v / max) as f32), Live::Released)), _ => {} } }); pick } +/// What a press, a drag, a key or a screen reader's action sets on the wheel or the box: the +/// components it gives, the others coming from the HSB it is applied to ([`Picked::hsb`]). +#[derive(Clone, Copy)] +enum Picked { + /// The hue ring's hue. + Hue(f32), + /// The square's saturation and brightness. + Square(f32, f32), + /// The box's field point (x across, y down) in channel `ch`. + Field(Channel, f32, f32), + /// The box's strip value in channel `ch`. + Strip(Channel, f32), +} + +impl Picked { + /// The HSB this pick gives on a color showing HSB `was`. + fn hsb(self, was: [f32; 3]) -> [f32; 3] { + match self { + Picked::Hue(h) => [h, was[1], was[2]], + Picked::Square(s, b) => [was[0], s, b], + Picked::Field(ch, x, y) => box_pick(ch, box_pos(ch, was).0, x, y, was), + Picked::Strip(ch, z) => { + let (_, x, y) = box_pos(ch, was); + box_pick(ch, z, x, y, was) + } + } + } +} + /// The opacity (0 to 1) the row shows for `tgt` and whether the row can set it: the selected /// gradient stop's or freeform point's (the first when none is selected, as [`wheel_target`] /// picks it), else that of the fill or stroke item @@ -461,24 +490,28 @@ fn hex_shown(app: &VectorcraftApp, tgt: &Target, color: Option<&Color>) -> Strin } /// The hex field's id for `tgt`: it names the document, the selected objects or text characters, -/// the appearance item, the proxy and the gradient stop or freeform point, but not the color, so a -/// text typed for one of them is dropped when another one is targeted, even one showing the same hex. +/// the object selected in a symbol instance, the appearance item, the proxy and the gradient stop or +/// freeform point, but not the color, so a text typed for one of them is dropped when another one is +/// targeted, even one showing the same hex. fn hex_field_id(app: &VectorcraftApp, tgt: &Target) -> impl std::hash::Hash + use<> { let o = Owner::of(app, tgt, Color::rgb8(0, 0, 0)); - ("color-wheel-hex", o.doc, o.selection, o.text_selection, o.appearance_item, o.fill, o.slot) + let part = app.session.active().and_then(|d| d.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone()))); + ("color-wheel-hex", o.doc, o.selection, part, o.text_selection, o.appearance_item, o.fill, o.slot) } /// The Show Hex Field row for `tgt`: a `#` and a field as wide as the row, showing `shown`. 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, shown: &str) -> bool { +/// committed text goes through `color.parse` as typed; a text it refuses shows its error in the +/// status bar and changes nothing. The text's alpha is not applied when `opacity_set` (the opacity +/// row set the opacity in this frame), so a press on that row that commits the text keeps the +/// opacity it set. True when a text was committed. +fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str, opacity_set: bool) -> bool { let mut typed = None; let id = hex_field_id(app, tgt); 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, id, Some(tl!("Hex or CSS color")), Some(shown), width, 1); + typed = widgets::exact_text_field_named(ui, id, Some(tl!("Hex or CSS color")), shown, width); }); let Some(text) = typed else { return false }; match app.run("color.parse", json!({ "text": text })) { @@ -490,7 +523,7 @@ fn hex_row(app: &mut VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> // 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); + let alpha = r["opacity"].as_f64().map(|o| (o / 100.0) as f32).filter(|_| !opacity_set); apply_typed(app, tgt, c, alpha); } Err(e) => app.status(e), @@ -701,8 +734,9 @@ pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { /// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the /// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no /// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow -/// key, a screen reader or a field asks for, and its phase. -pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { +/// key, a screen reader or a field asks for, the index of the row that set it (0 for L, 1 for C, 2 +/// for H) and its phase. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], usize, Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some() && cms.rgb_is_srgb(); let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { @@ -749,13 +783,13 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); } if let Some(x) = dragged { - out = Some((at(x), phase)); + out = Some((at(x), i, phase)); } if let Some(k) = keyed { - out = Some((with(i, k), Live::Released)); + out = Some((with(i, k), i, Live::Released)); } if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { - out = Some((with(i, f), Live::Released)); + out = Some((with(i, f), i, Live::Released)); } }); } @@ -774,7 +808,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); - let mut pick: Option<([f32; 3], Live)> = None; + let mut pick: Option<(Picked, Live)> = None; ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(44.0); @@ -794,7 +828,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let name = tl!("Saturation and brightness"); let (field, field_phase) = widgets::color_field(&mut field_ui, "field", (name, axes), square.size(), (hsb[1], 1.0 - hsb[2]), marked, &at); if let Some((h, phase)) = ring.hue { - pick = Some(([h, hsb[1], hsb[2]], phase)); + pick = Some((Picked::Hue(h), phase)); } // A press between the square and the ring picks the closest point of the square, which // takes the keyboard focus. @@ -802,10 +836,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let field_id = widgets::id_with(field_ui.scope_id(), "field"); field_ui.memory_mut(|m| m.request_focus(field_id)); let f = |v: f32, lo: f32, len: f32| ((v - lo) / len).clamp(0.0, 1.0); - pick = Some(([hsb[0], f(p.x, square.left(), square.width()), 1.0 - f(p.y, square.top(), square.height())], phase)); + pick = Some((Picked::Square(f(p.x, square.left(), square.width()), 1.0 - f(p.y, square.top(), square.height())), phase)); } if let Some((x, y)) = field { - pick = Some(([hsb[0], x, 1.0 - y], field_phase)); + pick = Some((Picked::Square(x, 1.0 - y), field_phase)); } }); if app.ui.color_wheel.vision { @@ -843,20 +877,28 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } } + let mut committed = false; if let Some(hex) = hex { 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, &hex) { - return; - } + committed = hex_row(app, ui, &tgt, &hex, opacity_set); } - // A pick or an OKLCH edit read in the frame of an opacity edit goes to the stops as that edit - // left them, so the stop keeps both. - let tgt = if opacity_set { wheel_target(app, ui) } else { tgt }; + // A pick or an OKLCH edit read in the frame of an opacity edit or of a text commit goes to the + // target as that edit or text left it, so a stop keeps both. After a text commit that changed + // the color, the components the pick or the row does not set come from the color the text + // applied; a text that left the color as it was keeps the remembered hue. + let tgt = if opacity_set || committed { wheel_target(app, ui) } else { tgt }; + let now = tgt.color().filter(|c| committed && Some(*c) != color); 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 { + if let Some((asked, row, phase)) = picked_lch { + let lch = match now { + Some(c) => { + let mut lch = oklab::to_oklch(cms.display_rgb(&c)); + lch[row] = asked[row]; + lch + } + None => asked, + }; let (srgb, _) = oklab::from_oklch(lch[0], lch[1], lch[2]); let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); @@ -865,7 +907,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } return; } - let Some((hsb, phase)) = pick else { return }; + let Some((picked, phase)) = pick else { return }; + let hsb = picked.hsb(now.map_or(hsb, |c| display_hsb(&cms, &c))); let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index bae909218f..d820aab5e9 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -803,20 +803,23 @@ fn oklch_sliders_need_srgb_as_the_working_space() { assert_eq!(settings.sliders, Sliders::Oklch); set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap(); assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space"); + let asked = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let seen = asked.clone(); let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( move |ui, app: &mut VectorcraftApp| { let tgt = super::color::wheel_target(app, ui); let color = tgt.color(); - let _ = oklch_rows(app, ui, &tgt, color, &p3); + if oklch_rows(app, ui, &tgt, color, &p3).is_some() { + seen.store(true, std::sync::atomic::Ordering::Relaxed); + } }, app(json!("#ff0000")), ); h.run_steps(2); assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); - let undo = undo_len(h.state()); let rail = oklch_slider(&h, "Lightness").rect(); click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); - assert_eq!(undo_len(h.state()), undo, "a gray row picks nothing"); + assert!(!asked.load(std::sync::atomic::Ordering::Relaxed), "a gray row asks for no OKLCH"); } /// The rows show what they asked for while the color displays as it did, and the color's own @@ -861,3 +864,18 @@ fn ui_color_wheel_sets_and_reads_the_sliders() { 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"); } + +/// An explicit null for any `ui.colorWheel` key keeps that key's value, as leaving the key out does, +/// and the other keys of the same call still apply. +#[test] +fn ui_color_wheel_keeps_a_key_given_as_null() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let set = json!({"view": "box", "channel": "red", "opacity": true, "hexField": true, "sliders": "oklch", "vision": true}); + let all = app.run("ui.colorWheel", set.clone()).unwrap(); + assert_eq!(all, set); + for key in ["view", "channel", "opacity", "hexField", "sliders", "vision"] { + assert_eq!(app.run("ui.colorWheel", json!({ key: null })).unwrap(), all, "{key}: null"); + } + let got = app.run("ui.colorWheel", json!({"view": null, "channel": "blue", "opacity": null, "hexField": false})).unwrap(); + assert_eq!(got, json!({"view": "box", "channel": "blue", "opacity": true, "hexField": false, "sliders": "oklch", "vision": true})); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e53a7d203e..cef02c5e23 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -314,6 +314,117 @@ fn a_text_typed_for_one_object_does_not_go_to_another_with_the_same_hex() { assert_eq!(undo_count(h.state()), before, "nothing was applied"); } +/// Selects the field's text and types `text` over it, without committing it. +fn type_pending(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); +} + +/// A click at `pos` whose press and release come in one frame. +fn quick_click(h: &mut Harness<'static, VectorcraftApp>, pos: egui::Pos2) { + h.event(egui::Event::PointerMoved(pos)); + h.run_steps(1); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + h.input_mut().events.extend([button(true), button(false)]); + h.run_steps(2); +} + +/// A click on the square in one frame that takes the focus from an edited field applies the text, +/// then the click's saturation and brightness at the hue the text gave: a gradient stop keeps the +/// typed alpha. +#[test] +fn a_wheel_click_in_one_frame_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); + type_pending(&mut h, "#33669980"); + let square = h.get_by_label("Saturation and brightness").rect(); + quick_click(&mut h, square.right_top() + vec2(-1.0, 1.0)); + 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) > 0xf0 && ch(1) < 0x10 && ch(3) > 0x60 && ch(3) < 0xa0, "the pick keeps the typed hue: {hex}"); + assert_eq!(undo_count(h.state()), before + 2); +} + +/// A text that leaves a white as it was, committed by a click on the square in one frame, keeps the +/// hue the white was picked from: the click's saturation brings that hue back. +#[test] +fn a_click_that_commits_the_same_white_keeps_the_remembered_hue() { + let mut app = app(); + let rect = selected(&app)[0]; + app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap(); + let mut h = harness(app); + let square = h.get_by_label("Saturation and brightness").rect(); + quick_click(&mut h, square.left_top()); + assert_eq!(rgb8(&fill_color(h.state(), rect)), [255, 255, 255], "the square picks white"); + type_pending(&mut h, "#ffffff"); + quick_click(&mut h, square.right_top() + vec2(-1.0, 1.0)); + let [r, g, b] = rgb8(&fill_color(h.state(), rect)); + assert!(g > 0xf0 && r < 0x10 && b < 0x10, "the green comes back: {r:02x}{g:02x}{b:02x}"); +} + +/// A press on the opacity slider in one frame that takes the focus from a field holding hex with an +/// alpha applies the typed color and keeps the opacity the press set, not the typed alpha. +#[test] +fn an_opacity_click_in_one_frame_keeps_its_opacity_over_a_typed_alpha() { + let mut app = app(); + app.run("paint.setFill", json!({"gradient": {}})).unwrap(); + app.run("ui.colorWheel", json!({"opacity": true})).unwrap(); + let mut h = harness(app); + type_pending(&mut h, "#33669900"); + let rail = h.get_by_role_and_label(Role::Slider, "Opacity").rect(); + quick_click(&mut h, rail.center()); + 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", "the text applies"); + assert!(stop.opacity > 0.2 && stop.opacity < 0.8, "the press sets the opacity: {}", stop.opacity); +} + +/// A text typed for one object of a dynamic symbol instance is dropped when another object of the +/// same instance showing the same hex is selected: Enter then changes neither of them. +#[test] +fn a_text_typed_for_one_object_of_a_symbol_instance_does_not_go_to_another() { + let mut app = app(); + let a = selected(&app)[0]; + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + let b = selected(&app)[0]; + let inst = app.run("symbol.new", json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.selectPart", json!({"id": inst, "path": [0]})).unwrap(); + let before = undo_count(&app); + let mut h = harness(app); + type_pending(&mut h, "#336699"); + h.state_mut().run("symbol.instance.selectPart", json!({"id": inst, "path": [1]})).unwrap(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(2); + let Paint::Solid { color, .. } = crate::panels::current_paints(h.state()).0 else { panic!("a solid fill") }; + assert_eq!(rgb8(&color), [255, 0, 0], "the second object keeps its color"); + assert_eq!(undo_count(h.state()), before, "nothing was applied"); +} + +/// A text with a character `color.parse` does not read as whitespace (a no-break space) is refused, +/// as `color.parse` refuses it, and changes nothing. +#[test] +fn a_no_break_space_in_the_text_is_refused() { + let app = app(); + let doc = app.session.doc().unwrap().doc.clone(); + let mut h = harness(app); + type_in(&mut h, "\u{a0}#336699"); + assert_eq!(*h.state().session.doc().unwrap().doc, *doc); + assert!(!h.state().ui.status.is_empty(), "the status bar says why"); + assert!(h.state_mut().run("color.parse", json!({"text": "\u{a0}#336699"})).is_err()); +} + /// A press on the opacity slider that takes the focus from an edited field applies the text and /// keeps the opacity the press set: a gradient stop takes both. #[test] From 7533a81e226c40bab844488d28a0ee3bc9aa45b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 05:46:34 -0800 Subject: [PATCH 07/28] Color Wheel: opacity edits target and count what the command changes - A null `id` or `ids` names no object, so while the Type tool has characters selected the paint still goes to those characters. - An opacity for selected characters is refused before the typing session ends, so the session and its undo step stay as they are. - With an opacity alone, `objects` counts only the objects that took it. - `paint.proxies` reads a targeted layer's visible, unlocked art, as the commands do, so a locked object's fill no longer enables the control. - A field commit on one OKLCH row keeps a value clicked or dragged on another row in the same frame, and a drag in progress stays in progress. --- crates/engine/src/cmd/paint.rs | 40 ++++++--- crates/engine/src/tests/paintopacity.rs | 83 +++++++++++++++++++ crates/ui-egui/src/panels/color_wheel.rs | 39 +++++++-- .../ui-egui/src/panels/tests_color_wheel.rs | 37 ++++++++- docs/mcp.md | 5 +- 5 files changed, 179 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index e5ca789aec..16cd564668 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors; the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no item, and no ids or id other than null, are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -257,7 +257,8 @@ impl Session { let targets = super::graph::series_group_marks_where(&st.doc, subjects, |n| n.extras().series_index.is_some()); return targets.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, active)); } - let leaves = super::leaf_targets(self, subjects).ok()?; + // The command's targets: a targeted layer stands for its visible, unlocked art. + let leaves = super::paint_targets(self, &Value::Null).ok()?; leaves.iter().filter(editable).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None)) } @@ -537,6 +538,11 @@ fn opacity_param(p: &Value, cmd: &str) -> Result> { } } +/// Whether `p` gives `key` a value other than null. +fn names(p: &Value, key: &str) -> bool { + p.get(key).is_some_and(|v| !v.is_null()) +} + /// The error for an `opacity` that would go to type characters, which have no opacity of their own. fn characters_have_no_opacity(cmd: &str) -> EngineError { bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke") @@ -565,10 +571,15 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; - // Characters selected with the Type tool take the paint, not the whole type object (#1063). - if p.get("ids").is_none() - && p.get("id").is_none() - && p.get("item").is_none() + // Characters selected with the Type tool take the paint, not the whole type object (#1063). A + // null `ids` or `id` names no object, as the targets read it. + let on_characters = !names(p, "ids") && !names(p, "id") && p.get("item").is_none(); + // An opacity for the characters is refused before their typing session ends, so the session + // and its undo step stay as they are. + if on_characters && opacity.is_some() && super::textedit::selected_range(s).is_some_and(|(_, a, b)| a != b) { + return Err(characters_have_no_opacity(cmd)); + } + if on_characters && let Some((id, a, b)) = super::textedit::editing_range(s)? && a != b { @@ -687,8 +698,8 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity // The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep // for their characters; a row edit is kept with the label's rows. let characters = std::cell::RefCell::new(Vec::new()); - // Whether a target took the opacity, and whether one would have given it to its characters. - let (took_opacity, characters_skipped) = (std::cell::Cell::new(false), std::cell::Cell::new(false)); + // The targets that took the opacity, and whether one would have given it to its characters. + let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false)); let paint_one = |n: &mut Node, index: Option, paint: &Paint| -> Result<()> { if index.is_none() && matches!(n.kind, NodeKind::Text(_)) { characters.borrow_mut().push(n.id); @@ -764,7 +775,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity for i in points { if let Some(q) = m.points.get_mut(*i) { q.opacity = o; - took_opacity.set(true); + took_opacity.borrow_mut().insert(n.id); } } return; @@ -773,7 +784,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) }; if let Some(item) = item { *item = o; - took_opacity.set(true); + took_opacity.borrow_mut().insert(n.id); } }; // The objects counted: with a design's art, those with a row equal to the art's. @@ -796,7 +807,7 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity }, |before, d, changed| { // An opacity that no target took is an error, which also takes back the paint given with it. - if opacity.is_some() && !took_opacity.get() { + if opacity.is_some() && took_opacity.borrow().is_empty() { if characters_skipped.get() { return Err(characters_have_no_opacity(cmd)); } @@ -829,14 +840,17 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity paint_new_art(s, paint, fill); s.remember_paint(paint); } - Ok(json!({"objects": ids.iter().collect::>().len()})) + // An opacity alone counts only the objects that took it. + let took = took_opacity.into_inner(); + let counted: std::collections::BTreeSet<_> = ids.iter().filter(|id| paint.is_some() || took.contains(*id)).collect(); + Ok(json!({"objects": counted.len()})) } /// The instance whose object is selected with Direct Selection, and that object's path /// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands /// then change that object. A bad `target` or `aligned` is refused as it is for any other selection. fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result)>> { - if p.get("ids").is_some() || p.get("id").is_some() || p.get("item").is_some() { + if names(p, "ids") || names(p, "id") || p.get("item").is_some() { return Ok(None); } let part = super::brushsym::selected_part(s)?; diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index e733bbab1c..41874ddfc3 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -234,6 +234,89 @@ fn with_characters_selected_an_id_takes_the_opacity() { assert_eq!(node(&s, t), before, "the characters keep their paint"); } +/// While the Type tool has characters selected, a null `id` or `ids` names no object: the paint goes +/// to the selected characters only, as without the key. +#[test] +fn with_characters_selected_a_null_id_paints_the_characters() { + let runs = |key: Option<&str>| { + let mut s = session(); + let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hello"})).unwrap(); + let t = NodeId(r["id"].as_u64().unwrap()); + select(&mut s, &[t]); + select_characters(&mut s, t); + let mut p = json!({"color": "#ff0000"}); + if let Some(key) = key { + p[key] = Value::Null; + } + s.execute("paint.setFill", &p).unwrap(); + match &node(&s, t).kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + } + }; + let characters = runs(None); + assert!(characters.len() > 1, "only the selected characters take the paint"); + for key in ["id", "ids"] { + assert_eq!(runs(Some(key)), characters, "{key}: null"); + } +} + +/// An opacity for characters selected while the Type tool is typing is refused before the typing +/// session ends: the session goes on, and no undo step is recorded. +#[test] +fn an_opacity_for_characters_leaves_the_typing_session_running() { + let mut s = session(); + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap(); + } + s.tool_text("Hello", v).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 2})); + assert!(crate::cmd::typing_in_progress(&s)); + let undo = undo_labels(&s).len(); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert!(crate::cmd::typing_in_progress(&s), "the typing session goes on"); + assert_eq!(undo_labels(&s).len(), undo, "no undo step"); +} + +/// With an opacity alone, the reply counts only the objects that took it: a selected object without +/// that fill item is left out, and one already at that opacity still counts. With a paint, every +/// target counts. +#[test] +fn an_opacity_alone_counts_the_objects_that_took_it() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + assert!(node(&s, a).appearance.fill().is_none()); + select(&mut s, &[a, b]); + assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1); + assert_eq!(s.execute("paint.setFill", &json!({"opacity": 40})).unwrap()["objects"], 1, "already at 40%"); + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap()["objects"], 2); +} + +/// With a layer targeted, `paint.proxies` reads the art the command edits: a locked object's fill +/// row does not count, so the proxy answers null when the edit finds no fill to take the opacity. +#[test] +fn a_targeted_layers_proxy_leaves_out_locked_art() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[b]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + select(&mut s, &[a]); + s.execute("object.lock", &json!({})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}"); + s.execute("object.unlockAll", &json!({})).unwrap(); + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the unlocked fill counts"); +} + /// A type object whose characters take the paint is left alone beside a rectangle that takes the /// opacity, with no error; alone, it answers the characters error. #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 95847e2c51..663e802c9f 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -729,14 +729,32 @@ pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { (max_chroma / CHROMA_FULL).clamp(0.0, 1.0) as f32 } +/// The OKLCH rows' edits of one frame with row `i`'s edit added: row `i` takes its value from +/// `asked`, on top of `out` (the other rows' edits so far, or none on top of `lch`). A drag on one +/// row stays in progress when another row's field commits in the same frame. +pub(crate) fn oklch_row_edit( + out: Option<([f64; 3], [bool; 3], Live)>, + lch: [f64; 3], + asked: [f64; 3], + i: usize, + phase: Live, +) -> ([f64; 3], [bool; 3], Live) { + let (mut base, mut rows, was) = out.unwrap_or((lch, [false; 3], phase)); + base[i] = asked[i]; + rows[i] = true; + let phase = if matches!(was, Live::Dragging) { Live::Dragging } else { phase }; + (base, rows, phase) +} + /// The L, C and H rows of OKLCH Sliders for the target's `color` through `cms`: lightness from 0 to /// 100 %, chroma from 0 to 100 % of 0.4 (as CSS reads a chroma percentage) and hue from 0 to 360°. /// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the /// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no /// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow -/// key, a screen reader or a field asks for, the index of the row that set it (0 for L, 1 for C, 2 -/// for H) and its phase. -pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], usize, Live)> { +/// key, a screen reader or a field asks for, which rows set it (L, C and H in that order) and the +/// phase of the last edit. A field that commits when a click on another row takes its focus keeps +/// its value along with the click's. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], [bool; 3], Live)> { let t = Tokens::get(ui.ctx()); let enabled = color.is_some() && cms.rgb_is_srgb(); let lch = match (color, pstate::>(ui.ctx(), OKLCH_MEMORY)) { @@ -757,7 +775,8 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: } out }; - let mut out = None; + let mut out: Option<([f64; 3], [bool; 3], Live)> = None; + let mut set = |asked: [f64; 3], i: usize, phase: Live| out = Some(oklch_row_edit(out, lch, asked, i, phase)); ui.add_enabled_ui(enabled, |ui| { let field_w = 48.0; let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); @@ -783,13 +802,13 @@ pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); } if let Some(x) = dragged { - out = Some((at(x), i, phase)); + set(at(x), i, phase); } if let Some(k) = keyed { - out = Some((with(i, k), i, Live::Released)); + set(with(i, k), i, Live::Released); } if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { - out = Some((with(i, f), i, Live::Released)); + set(with(i, f), i, Live::Released); } }); } @@ -890,11 +909,13 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let now = tgt.color().filter(|c| committed && Some(*c) != color); 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((asked, row, phase)) = picked_lch { + if let Some((asked, rows, phase)) = picked_lch { let lch = match now { Some(c) => { let mut lch = oklab::to_oklch(cms.display_rgb(&c)); - lch[row] = asked[row]; + for row in (0..3).filter(|r| rows[*r]) { + lch[row] = asked[row]; + } lch } None => asked, diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index d820aab5e9..8124aa5ded 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -12,9 +12,10 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::Session; use super::color_wheel::{ - ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_oklch, set, show, stored, + ID, Settings, Sliders, chroma_tick, display_hsb, oklch_row_edit, oklch_rows, oklch_track, remembered_hsb, remembered_oklch, set, show, stored, }; use crate::VectorcraftApp; +use crate::widgets::Live; /// An app with a selected rectangle filled with `fill`. fn app(fill: serde_json::Value) -> VectorcraftApp { @@ -646,6 +647,40 @@ fn a_drag_on_lightness_keeps_the_chroma_asked_for() { assert!((l2 - l0).abs() < 0.01 && (c2 - c0).abs() < 0.01, "{:?} → {:?}", [l0, c0], [l2, c2]); } +/// A lightness typed in the L field and committed by a click on the C rail in one frame keeps both +/// edits: the color takes the typed L and the clicked C. +#[test] +fn a_typed_lightness_committed_by_a_click_on_chroma_keeps_both() { + let mut h = oklch_harness(app(json!("#ff0000"))); + let h0 = fill_oklch(h.state())[2]; + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Lightness").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.run_steps(1); + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Lightness").type_text("50"); + h.run_steps(1); + let rail = oklch_slider(&h, "Chroma").rect(); + quick_click(&mut h, on_rail(rail, 0.2)); + let [l, c, hue] = fill_oklch(h.state()); + assert!((l - 0.5).abs() < 0.01, "the typed lightness stays: {l}"); + assert!((c - 0.08).abs() < 0.01, "the click sets the chroma: {c}"); + assert!((hue - h0).abs() < 1.0, "the hue stays: {h0} → {hue}"); +} + +/// When a drag on one OKLCH row and a field commit on another come in one frame, the frame's edit +/// keeps both values and the drag stays in progress, in either order. +#[test] +fn a_field_commit_beside_a_drag_keeps_the_drag_going() { + let lch = [0.6, 0.2, 30.0]; + let drag = |out| oklch_row_edit(out, lch, [0.8, 0.0, 0.0], 0, Live::Dragging); + let field = |out| oklch_row_edit(out, lch, [0.0, 0.0, 200.0], 2, Live::Released); + for (out, order) in [(field(Some(drag(None))), "drag first"), (drag(Some(field(None))), "field first")] { + assert_eq!(out.0, [0.8, 0.2, 200.0], "{order}"); + assert_eq!(out.1, [true, false, true], "{order}"); + assert!(matches!(out.2, Live::Dragging), "{order}"); + } +} + /// A press on a row gives it the keyboard focus, and → raises it by one unit as one undo step. /// Each row reports its range and the adjust actions to screen readers. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 58f96d804a..3f1c509728 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -888,8 +888,9 @@ its kind (`paint.proxies`) and the Gradient tool's annotator then show that row. `inspect_document` reports it as `paint.appearanceItem`. `paint.setFill` and `paint.setStroke` also take `opacity` (0 to 100, a percentage as in `transparency.set`), which sets the opacity of the fill or stroke row they paint, with or without a new paint, as one undo step. An opacity that no target takes is an error and also leaves the paint -undone. `paint.proxies` answers it as `fillOpacity` and `strokeOpacity`, from the first selected object that has -that row. It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool +undone. With an opacity alone, the reply's `objects` counts only the objects that took it. `paint.proxies` answers +it as `fillOpacity` and `strokeOpacity`, from the first selected object that has that row. With a layer targeted, +it reads the layer's visible, unlocked art, as the commands do. It answers null with nothing selected, for an object selected in a symbol instance, while the Type tool has characters selected, and when only type characters (which have no opacity of their own) or objects without that row are selected. Live effects take the same `item` to apply to one fill or stroke instead of the whole object: `run_command effect.apply {"effect": "path.offsetPath", "item": 0}`, and From f47ebd9887fcaa64e58c55a78efb2d09fd041ca6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 06:31:19 -0800 Subject: [PATCH 08/28] Color: a bad target is refused for a picked object with a null id With an object of a dynamic symbol instance selected, `id: null` or `ids: null` reached the item check, which stops at those keys before it reads `target`, so a bad `target` changed the object. The target is now read first. --- crates/engine/src/cmd/paint.rs | 2 ++ crates/engine/src/tests/paintopacity.rs | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 16cd564668..f0fbb91ff1 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -855,6 +855,8 @@ fn selected_part_target(s: &Session, p: &Value, cmd: &str) -> Result Date: Thu, 19 Nov 2026 17:38:15 -0800 Subject: [PATCH 09/28] Rerun CI From 97599b5a50a086b8c4f1a860a8b2ad41649e28ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 18:32:24 -0800 Subject: [PATCH 10/28] Color: color.parse says it reads a subset of CSS without calc() The help, the color module docs and docs/mcp.md state that a function's arguments are literal numbers, percentages, angles and none, and that calc(), var(), color-mix(), other nested functions, named colors and the other color functions and spaces are errors. --- crates/color/src/css.rs | 5 +++++ crates/engine/src/cmd/colorcmds.rs | 2 +- docs/mcp.md | 5 ++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/color/src/css.rs b/crates/color/src/css.rs index c8b1e84ab2..24c274846b 100644 --- a/crates/color/src/css.rs +++ b/crates/color/src/css.rs @@ -7,6 +7,11 @@ //! take the comma-separated legacy form (). //! Hues take the angle units of CSS Values 4 (). A hex //! color may leave out its `#`. +//! +//! The module reads a subset of CSS. A function's arguments are literal numbers, percentages, +//! angles and `none`. A parenthesis inside the arguments makes the text invalid, so `calc()`, +//! `var()`, `color-mix()`, relative color syntax and every other nested function are refused, as are +//! named colors and the other color spaces and functions (`hwb()`, `lab()`, `oklab()`, `color()`). use crate::oklab::{self, CHROMA_FULL}; diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs index 8890f9eec9..0a68310ecd 100644 --- a/crates/engine/src/cmd/colorcmds.rs +++ b/crates/engine/src/cmd/colorcmds.rs @@ -141,7 +141,7 @@ pub fn specs() -> Vec { "Parse Color", [], None, - "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in 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, the spaces, tabs, line breaks and form feeds 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; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", + "{text: a hex color or a CSS color (a hex color is #rgb, #rgba, #rrggbb or #rrggbbaa, and the # may be left out; a CSS color is rgb() or rgba() or hsl() or hsla(), space-separated with an optional / alpha or in 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; this is a subset of CSS: a function's arguments are literal numbers, percentages, angles (deg, grad, rad or turn) and none, so calc(), var(), color-mix() and every other function, named colors and the other color spaces are errors; at most 48 characters, the spaces, tabs, line breaks and form feeds 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; an hsl() color whose saturation and lightness are so large that a channel overflows to an infinity is an error, as is any other text, and so is oklch() while the working RGB space is not sRGB", always, parse_color ), diff --git a/docs/mcp.md b/docs/mcp.md index af8b76524b..11aece8afe 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -739,7 +739,10 @@ the `#`, or a CSS [`rgb()` or `rgba()`](https://www.w3.org/TR/css-color-4/#rgb-f 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 the spaces, tabs, line breaks and form feeds around it; other whitespace, such as a vertical tab or a no-break space, -makes the text an error. A hex color, `rgb()` and `hsl()` give their numbers as the document's RGB numbers, as +makes the text an error. The command reads a subset of CSS: a function's arguments are literal numbers, percentages, +angles and `none`, so `calc()`, `var()`, `color-mix()`, relative color syntax and every other nested function are +errors, as are named colors and the functions and color spaces not listed above (`hwb()`, `lab()`, `oklab()` and +`color()`). 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 From 6898eed99f232ff3410c10625aef6f0d33c5d296 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 19 Nov 2026 20:35:13 -0800 Subject: [PATCH 11/28] Color: paint.setFill refuses a bad target when an id names the object paint.setFill and paint.setStroke read `target` and `aligned` before choosing their targets, so a bad value is refused when `id` or `ids` names an object and while the Type tool has characters selected, as it already was for other selections. --- crates/engine/src/cmd/paint.rs | 4 +++ crates/engine/src/tests/paintopacity.rs | 33 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 4b20947a86..f5c4983b62 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -636,6 +636,10 @@ fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option, opacity let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; let bucket = bucket_color_params(s, p, cmd)?; let p = bucket.as_ref().unwrap_or(p); + // A bad `target` or `aligned` is refused for every kind of target: `item_target` reads no + // `target` once `id` or `ids` names an object, and selected characters read neither. + super::appearance::aligned(p, cmd)?; + super::appearance::targets_contents(p)?; let focus = switch_or(p, "focus", true, cmd)?; // An opacity alone places no gradient, so `span` may only be "object" with it. let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?; diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs index 53d72b0e5d..5b980f9803 100644 --- a/crates/engine/src/tests/paintopacity.rs +++ b/crates/engine/src/tests/paintopacity.rs @@ -427,6 +427,39 @@ fn an_object_in_a_symbol_instance_refuses_a_bad_target() { assert_ne!(*s.doc().unwrap().doc, *doc); } +/// A bad `target` is refused when `id` or `ids` names an object, and a bad `target` or `aligned` +/// while the Type tool has characters selected; each leaves the document alone. A good `target` +/// with an `id` still paints the object. +#[test] +fn a_bad_target_is_refused_with_an_id_or_selected_characters() { + let mut s = session(); + let r = rect(&mut s, 10.0); + select(&mut s, &[r]); + let doc = s.doc().unwrap().doc.clone(); + for cmd in ["paint.setFill", "paint.setStroke"] { + for p in [ + json!({"color": "#ff0000", "target": "content", "id": r.0}), + json!({"color": "#ff0000", "target": "content", "ids": [r.0]}), + json!({"opacity": 40, "target": "content", "id": r.0}), + json!({"opacity": 40, "target": "content", "ids": [r.0]}), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(e.to_string().contains("`target` must be"), "{cmd} {p}: {e}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{cmd} {p}"); + } + } + assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff0000", "target": "object", "id": r.0})).unwrap()["objects"], 1); + assert_ne!(*s.doc().unwrap().doc, *doc); + let t = text(&mut s); + select(&mut s, &[t]); + select_characters(&mut s, t); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"color": "#ff0000", "target": "content"}), json!({"color": "#ff0000", "aligned": "yes"})] { + assert!(s.execute("paint.setFill", &p).is_err(), "{p}"); + assert_eq!(*s.doc().unwrap().doc, *doc, "{p}"); + } +} + /// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows /// it; the object's fill item and the other points stay as they were. #[test] From 2f868a6ab4fdf7c6361a9a29d85881d05893cac0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:24:51 -0800 Subject: [PATCH 12/28] Brushes: Pattern Brush Options' Scale follows the pen's pressure, tilt, bearing, rotation and wheel A pattern brush's scale can now follow Pressure, Tilt, Bearing, Rotation or Stylus Wheel, with a second scale beside the first, as an Art brush's Width does. Pattern Brush Options and Options of Selected Object show the mode menu and the second scale on the Scale row, and brush.new, brush.options and brush.objectOptions take `scale_mode` and `scale_max`. Each side, start and end tile is as tall as the scale at each point of the stroke and as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit, Add Space to Fit and Approximate Path fit the tiles of each run as they are measured where they land. A stroke without the input draws at the scale half way between the two. A brush with a fixed scale draws as before, and brushes without the new fields save without them. Options of Selected Object keeps each path's own second scale when only the scale or the mode changes, for pattern scales and art widths. Docs: docs/mcp.md, docs/target-app-parity.md, docs/hardware-parity.md. --- crates/brush/src/lib.rs | 37 ++- crates/brush/src/tests.rs | 180 ++++++++++++ crates/brush/src/warp.rs | 266 +++++++++++++++++- crates/engine/src/cmd/brushsym.rs | 4 +- crates/engine/src/cmd/brushsym/brushes.rs | 33 ++- crates/engine/src/tests/brushsym.rs | 64 +++++ crates/mcp/src/ui_catalog.rs | 4 +- .../ui-egui/src/dialogs/brush_art_options.rs | 75 +++-- .../src/dialogs/brush_options/tests.rs | 88 ++++++ crates/ui-egui/src/menus/ui_commands.rs | 4 +- docs/hardware-parity.md | 2 +- docs/mcp.md | 15 +- docs/target-app-parity.md | 3 +- 13 files changed, 722 insertions(+), 53 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index d3dd3b6b38..30f5d6667e 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -549,6 +549,15 @@ pub struct PatternBrush { pub end_swatch: Option, /// Scale in percent. pub scale: f64, + /// How the scale varies along a stroke: `None` (Fixed) always `scale`; a mode that follows the + /// pen goes from `scale` to [`Self::scale_max`] over the ranges [`Variation`] gives, as an Art + /// brush's width does ([`ArtBrush::width_mode`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_mode: Option, + /// The second scale (%) of a mode that follows the pen: at the heaviest pressure, upright, at + /// 180° or at the wheel's far end (`scale` without one). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scale_max: Option, /// Space between tiles in percent of the tile width. pub spacing: f64, pub fit: PatternFit, @@ -561,6 +570,15 @@ impl PatternBrush { /// The ranges of the scale and of the spacing (%). pub const SCALE_RANGE: (f64, f64) = (1.0, 10000.0); pub const SPACING_RANGE: (f64, f64) = (0.0, 10000.0); + + /// The scales (%) where the pen reads 0 and 1 for the scale's mode (the lightest and the + /// heaviest pressure, for Pressure): `scale` for both unless the scale follows the pen. + pub fn scale_range(&self) -> (f64, f64) { + match self.scale_mode { + Some(m) if m.follows_pen() => (self.scale, self.scale_max.unwrap_or(self.scale)), + _ => (self.scale, self.scale), + } + } } impl Default for PatternBrush { @@ -584,6 +602,8 @@ impl Default for PatternBrush { end_frame: None, end_swatch: None, scale: 100.0, + scale_mode: None, + scale_max: None, spacing: 0.0, fit: PatternFit::Stretch, flip_along: false, @@ -767,6 +787,11 @@ impl Brush { } BrushKind::Pattern(p) => { p.scale = within(p.scale, PatternBrush::SCALE_RANGE, 100.0); + // The scale follows the pen (its pressure, tilt, bearing, rotation or wheel) or stays fixed. + if !p.scale_mode.is_some_and(Variation::follows_pen) { + p.scale_mode = None; + } + p.scale_max = p.scale_max.map(|s| within(s, PatternBrush::SCALE_RANGE, p.scale)); p.spacing = within(p.spacing, PatternBrush::SPACING_RANGE, 0.0); for frame in [&mut p.side_frame, &mut p.outer_corner_frame, &mut p.inner_corner_frame, &mut p.start_frame, &mut p.end_frame] { if frame.is_some_and(|f| !valid_tile_frame(f)) { @@ -819,6 +844,8 @@ struct ArtOptions { #[derive(Serialize, Deserialize)] struct PatternOptions { scale: f64, + scale_mode: Option, + scale_max: Option, spacing: f64, fit: PatternFit, flip_along: bool, @@ -835,7 +862,7 @@ impl BrushKind { BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"], BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"], BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"], - BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"], + BrushKind::Pattern(_) => &["scale", "scale_mode", "scale_max", "spacing", "fit", "flip_along", "flip_across", "colorization"], BrushKind::Bristle(_) => &[], } } @@ -870,6 +897,8 @@ impl BrushKind { }), BrushKind::Pattern(p) => serde_json::to_value(PatternOptions { scale: p.scale, + scale_mode: p.scale_mode, + scale_max: p.scale_max, spacing: p.spacing, fit: p.fit, flip_along: p.flip_along, @@ -898,8 +927,8 @@ impl BrushKind { } BrushKind::Pattern(p) => { let o: PatternOptions = serde_json::from_value(v)?; - (p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) = - (o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization); + (p.scale, p.scale_mode, p.scale_max, p.spacing) = (o.scale, o.scale_mode, o.scale_max, o.spacing); + (p.fit, p.flip_along, p.flip_across, p.colorization) = (o.fit, o.flip_along, o.flip_across, o.colorization); } BrushKind::Bristle(_) => {} } @@ -1123,7 +1152,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), - BrushKind::Pattern(p) => warp::pattern(p, bp, w), + BrushKind::Pattern(p) => warp::pattern(p, bp, w, stroke), }; let colorization = brush.kind.colorization(); for n in &mut out { diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 2b1449eddf..cec39f9477 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2015,6 +2015,186 @@ fn art_brush_width_follows_tilt_bearing_and_rotation() { assert_eq!(modes, [Some(Variation::Tilt), Some(Variation::Bearing), Some(Variation::Rotation), None]); } +/// A pattern brush with `scale`, `scale_mode` and `scale_max`, its 10 × 4 pt side tile on `fit`. +fn scaled_pattern(fit: PatternFit, corners: bool, scale: f64, mode: Option, max: Option) -> Brush { + let mut b = pattern_brush(fit, corners); + if let BrushKind::Pattern(p) = &mut b.kind { + (p.scale, p.scale_mode, p.scale_max) = (scale, mode, max); + } + b +} + +/// The bounds of each piece, left to right. +fn piece_spans(out: &[Node]) -> Vec { + let mut spans: Vec = out.iter().filter_map(Node::geometric_bounds).collect(); + spans.sort_by(|a, b| a.x0.total_cmp(&b.x0)); + spans +} + +/// Pattern Brush Options: with Scale on Pressure the tiles go from Scale at the lightest pen +/// pressure to the second scale at the heaviest, taller and longer along the stroke where the pen +/// pressed harder, and each Fit still fits them to the path. +#[test] +fn pattern_brush_scale_follows_the_pressure() { + let bp = line(0.0, 0.0, 200.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + // 4 pt tall tiles at 50 %: 1 pt either side at the lightest; at 300 %: 6 pt at the heaviest. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + assert!(near(half_width(&out, 0.0, 1.0), 1.0, 0.1), "{}", half_width(&out, 0.0, 1.0)); + assert!(near(half_width(&out, 199.0, 200.0), 6.0, 0.2), "{}", half_width(&out, 199.0, 200.0)); + assert!(near(half_width(&out, 99.0, 101.0), 3.5, 0.2), "{}", half_width(&out, 99.0, 101.0)); + // Stretch to Fit fills the path, and the tiles grow longer along it. + let spans = piece_spans(&out); + assert!(near(bounds(&out).x0, 0.0, 1e-6) && near(bounds(&out).x1, 200.0, 1e-6), "{:?}", bounds(&out)); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{spans:?}"); + assert!(spans.last().unwrap().width() > 4.0 * spans[0].width(), "{spans:?}"); + // The stroke weight scales it. + let out = + draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &StrokeLayer { width: 2.0, ..ramp.clone() }); + assert!(near(half_width(&out, 199.0, 200.0), 12.0, 0.4), "{}", half_width(&out, 199.0, 200.0)); + // Without recorded pressure, half way between the two scales. + let out = draw(&scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)), &stroke(1.0)); + assert!(near(bounds(&out).height(), 7.0, 1e-6), "{:?}", bounds(&out)); + // With an even pressure, Add Space with spacing places as many tiles as the one scale that + // pressure gives: the spacing counts when the tiles are counted again. + let even = pressed(vec![(0.0, 0.5), (1.0, 0.5)]); + let spaced = |mode: Option, max: Option| { + let mut b = scaled_pattern(PatternFit::AddSpace, false, if max.is_some() { 50.0 } else { 100.0 }, mode, max); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 100.0; + } + piece_spans(&draw(&b, &even)).len() + }; + assert_eq!(spaced(Some(Variation::Pressure), Some(150.0)), spaced(None, None)); + // With spacing, Stretch to Fit still fills the path and Approximate Path still centers the + // tiles, with the gaps between them counted and none after the last. + for fit in [PatternFit::Stretch, PatternFit::Approximate] { + let mut b = scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.spacing = 50.0; + } + let spans = piece_spans(&draw(&b, &ramp)); + let (first, last) = (spans[0], spans[spans.len() - 1]); + assert!(spans.len() > 1 && near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{fit:?}: {spans:?}"); + if fit == PatternFit::Stretch { + assert!(near(first.x0, 0.0, 1e-6) && near(last.x1, 200.0, 1e-6), "{spans:?}"); + } + } + // Add Space to Fit keeps the tiles apart within the path; Approximate Path centers them on it. + for fit in [PatternFit::AddSpace, PatternFit::Approximate] { + let out = draw(&scaled_pattern(fit, false, 50.0, Some(Variation::Pressure), Some(300.0)), &ramp); + let spans = piece_spans(&out); + assert!(spans.len() > 1 && spans.windows(2).all(|w| w[1].x0 >= w[0].x1 - 1e-6), "{fit:?}: {spans:?}"); + assert!(spans.windows(2).all(|w| w[1].width() > w[0].width()), "{fit:?}: {spans:?}"); + let (first, last) = (spans[0], spans[spans.len() - 1]); + if fit == PatternFit::AddSpace { + assert!(first.x0 >= -1e-6 && last.x1 <= 200.0 + 1e-6, "{spans:?}"); + } else { + assert!(near((first.x0 + last.x1) / 2.0, 100.0, 0.01), "{spans:?}"); + } + } +} + +/// Pattern Brush Options: Scale on Tilt, Bearing, Rotation or Stylus Wheel reads only its own +/// input, half way without it; Fixed, a mode without a second scale and equal scales draw as a +/// brush without the setting does. +#[test] +fn pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel() { + let bp = line(0.0, 0.0, 100.0, 0.0); + let draw = |b: &Brush, st: &StrokeLayer| stroke_pieces(&Document::new(1.0, 1.0), b, &bp, st); + let brush = |mode: Variation| scaled_pattern(PatternFit::Stretch, false, 50.0, Some(mode), Some(300.0)); + let wheel = |v: f64| StrokeLayer { wheel: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, v), (1.0, v)] }), ..stroke(1.0) }; + // 4 pt tiles: 2 pt tall at 50 %, 12 pt at 300 %. + for (mode, st, height) in [ + (Variation::Tilt, posed(Some(0.0), None, None), 12.0), + (Variation::Tilt, posed(Some(1.0), None, None), 2.0), + (Variation::Bearing, posed(Some(0.5), Some(90.0), None), 9.5), + (Variation::Rotation, posed(None, None, Some(-90.0)), 4.5), + (Variation::StylusWheel, wheel(1.0), 12.0), + (Variation::StylusWheel, wheel(0.0), 2.0), + // Without its own input, half way. + (Variation::Tilt, posed(None, Some(90.0), Some(90.0)), 7.0), + (Variation::Bearing, posed(Some(0.0), None, Some(90.0)), 7.0), + (Variation::Rotation, posed(Some(0.0), Some(90.0), None), 7.0), + (Variation::StylusWheel, pressed(vec![(0.0, 1.0), (1.0, 1.0)]), 7.0), + (Variation::Pressure, posed(Some(0.0), Some(90.0), Some(90.0)), 7.0), + ] { + let h = bounds(&draw(&brush(mode), &st)).height(); + assert!(near(h, height, 1e-6), "{mode:?}: {h}"); + } + // Fixed, a mode without a second scale, and a second scale equal to the first draw what the + // brush draws without them. + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let plain = draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &ramp); + for (mode, max) in [(None, Some(300.0)), (Some(Variation::Pressure), None), (Some(Variation::Pressure), Some(50.0))] { + assert_eq!(draw(&scaled_pattern(PatternFit::Stretch, true, 50.0, mode, max), &ramp), plain, "{mode:?} {max:?}"); + } + let saved = serde_json::to_value(scaled_pattern(PatternFit::Stretch, false, 50.0, None, None)).unwrap(); + assert!(saved.get("scale_mode").is_none() && saved.get("scale_max").is_none(), "{saved}"); + // A mode the scale does not take is read as Fixed, and the second scale is kept within range. + let lib = parse_library(&serde_json::json!([ + {"name": "a", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "random", "scale_max": 1e308}, + {"name": "b", "type": "pattern", "side": rect_art(10.0, 4.0), "scale_mode": "stylusWheel", "scale_max": 0.0}, + ])); + let [BrushKind::Pattern(a), BrushKind::Pattern(b)] = [&lib[0].kind, &lib[1].kind] else { panic!("{lib:?}") }; + assert_eq!((a.scale_mode, a.scale_max, b.scale_mode, b.scale_max), (None, Some(10000.0), Some(Variation::StylusWheel), Some(1.0))); + // A stroke sets its own mode and second scale. + let mut own = serde_json::Map::new(); + own.insert("scale_mode".into(), serde_json::json!("pressure")); + own.insert("scale_max".into(), serde_json::json!(300.0)); + let edited = scaled_pattern(PatternFit::Stretch, false, 100.0, None, None).with_stroke_options(&own).unwrap(); + assert!(matches!(&edited.kind, BrushKind::Pattern(p) if p.scale_range() == (100.0, 300.0)), "{edited:?}"); +} + +/// A pattern brush whose scale follows the pen keeps its start, end and corner tiles at the scale +/// where they are, on open and closed paths, and stays finite at the ends of the scale's range. +#[test] +fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() { + let ramp = pressed(vec![(0.0, 0.0), (1.0, 1.0)]); + let doc = Document::new(1.0, 1.0); + // Start and end tiles, 6 × 4 pt: the start tile at the light end is smaller than the end tile. + let mut ends = scaled_pattern(PatternFit::Stretch, false, 50.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut ends.kind { + (p.start, p.end) = (Some(rect_art(6.0, 4.0)), Some(rect_art(6.0, 4.0))); + } + let out = stroke_pieces(&doc, &ends, &line(0.0, 0.0, 200.0, 0.0), &ramp); + let (start, end) = (out[0].geometric_bounds().unwrap(), out[1].geometric_bounds().unwrap()); + assert!(near(start.x0, 0.0, 1e-6) && near(end.x1, 200.0, 1e-6), "{start:?} {end:?}"); + assert!(start.width() < 3.5 && end.width() > 17.0 && start.height() < end.height() / 4.0, "{start:?} {end:?}"); + // A closed rectangle with corner tiles, on each Fit, and the scale's range at its ends. + let mut rect = BezPath::new(); + rect.move_to((0.0, 0.0)); + rect.line_to((100.0, 0.0)); + rect.line_to((100.0, 60.0)); + rect.line_to((0.0, 60.0)); + rect.close_path(); + for fit in [PatternFit::Stretch, PatternFit::AddSpace, PatternFit::Approximate] { + for (scale, max) in [(50.0, 300.0), (1.0, 10000.0), (10000.0, 1.0)] { + for bp in [&rect, &line(0.0, 0.0, 3.0, 0.0)] { + let b = scaled_pattern(fit, true, scale, Some(Variation::Pressure), Some(max)); + let out = stroke_pieces(&doc, &b, bp, &ramp); + assert!(!out.is_empty(), "{fit:?} {scale} {max}"); + let r = bounds(&out); + assert!([r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()), "{fit:?} {scale} {max}: {r:?}"); + } + } + } + // On the rectangle the corner tiles grow with the pressure: the first corner's tile is smaller + // than the last one's. + let b = scaled_pattern(PatternFit::Stretch, true, 50.0, Some(Variation::Pressure), Some(300.0)); + let out = stroke_pieces(&doc, &b, &rect, &ramp); + let fixed = stroke_pieces(&doc, &scaled_pattern(PatternFit::Stretch, true, 50.0, None, None), &rect, &ramp); + assert_ne!(out, fixed); + let corner = |n: &Node| n.geometric_bounds().map_or(0.0, |r| r.width().max(r.height())); + let corners: Vec = out.iter().take(4).map(corner).collect(); + assert!(corners[0] < corners[3], "{corners:?}"); + // The side tiles start half the corner tile beside them away from the corner: 1.5 pt from the + // first corner, where the 6 pt corner tile is drawn at 50 %, not half the largest corner tile. + let first_side = out.get(4).and_then(Node::geometric_bounds); + assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index edf0ac0567..240a5e14eb 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -646,6 +646,227 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti bend(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), cross) } +/// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies +/// (`marks`: the arc lengths of the recorded pen samples, between which the scale runs in a +/// straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it is +/// too when the scale is the same at both ends of the span and at every sample within it. +fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option { + let mid = k((s0 + s1) / 2.0); + let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && marks.iter().filter(|&&s| s > s0 && s < s1).all(|&s| k(s) == mid); + if mid <= 0.0 || marks.is_none_or(even) { + return tile_on(t, tile, s0, s1, mid); + } + bend_widened(t, &tile.0, tile.1, AlongMap::linear(tile.1.width(), s0, s1), mid, &|s| k(s) / mid) +} + +/// The most side tiles a run of a pattern brush places. +const MAX_TILES: usize = 20000; + +/// How many times a pattern brush whose scale varies measures its side tiles again where the fit +/// puts them. +const REFITS: usize = 3; + +/// How many times a pattern brush whose scale varies halves the range a start or end tile's +/// length lies in. +const END_SOLVE_STEPS: usize = 48; + +/// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along +/// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and +/// how many tiles fit whole and what fraction of the next one fits after them. The tiles include +/// that next one when there is room for part of it. +fn varied_tiles(a: f64, avail: f64, natural: &dyn Fn(f64) -> (f64, f64)) -> (Vec<(f64, f64)>, f64) { + let mut tiles = vec![]; + let mut pos = 0.0; + while tiles.len() < MAX_TILES { + let (w, g) = natural(a + pos); + if !(w > 1e-9 && w.is_finite() && g.is_finite() && g >= 0.0) { + break; + } + tiles.push((w, g)); + if pos + w > avail { + let whole = (tiles.len() - 1) as f64; + return (tiles, whole + ((avail - pos + g) / (w + g)).clamp(0.0, 1.0)); + } + pos += w + g; + } + let whole = tiles.len() as f64; + (tiles, whole) +} + +/// The size factor of a pattern brush's tiles at `weight` where its scale's pen input is `p` +/// (0 at the first scale, 1 at the second). +fn pattern_scale_at(pb: &PatternBrush, weight: f64, p: f64) -> f64 { + let (light, heavy) = pb.scale_range(); + weight * (light + (heavy - light) * p).max(1.0) / 100.0 +} + +/// A pattern brush's size factor on `stroke` at `weight`, and whether it varies along the stroke. +/// A stroke with no recording of the input the scale follows is drawn at one scale, the one that +/// input's missing value gives. +fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, bool) { + let (light, heavy) = pb.scale_range(); + match pb.scale_mode { + Some(m) if light != heavy && pen_recorded(stroke, m) => (weight * pb.scale.max(1.0) / 100.0, true), + Some(m) if light != heavy => (pattern_scale_at(pb, weight, PenAt::of(stroke, 0.0).control(m).unwrap_or(0.5)), false), + _ => (weight * pb.scale.max(1.0) / 100.0, false), + } +} + +/// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at +/// the middle of the tile when it is `w` long: the length that is as long as the scale at its own +/// middle, found by halving the range from 0 to `room`. A tile that needs more than `room` gets +/// the length it needs at `room`, longer than `room`. +fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64) -> f64 { + let length = |w: f64| width * k_mid(w); + let first = length(0.0); + if length(first) == first || room.is_nan() || room <= 0.0 { + return first; + } + if length(room) > room { + return length(room); + } + let (mut short, mut long) = (0.0, room); + for _ in 0..END_SOLVE_STEPS { + let mid = (short + long) / 2.0; + if length(mid) > mid { + short = mid; + } else { + long = mid; + } + } + long +} + +/// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its +/// arc length, and again a track's length on, for runs of a closed track that wrap round. +fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { + let points = match mode { + Variation::Fixed | Variation::Random => None, + Variation::Pressure => stroke.pressure.as_ref().map(|p| &p.points), + Variation::Tilt => stroke.tilt.as_ref().map(|p| &p.points), + Variation::Bearing => stroke.bearing.as_ref().map(|p| &p.points), + Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points), + Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points), + }; + points.into_iter().flatten().flat_map(|&(f, _)| [f * l, f * l + l]).collect() +} + +/// Whether `stroke` recorded the pen input `mode` follows. +fn pen_recorded(stroke: &StrokeLayer, mode: Variation) -> bool { + match mode { + Variation::Fixed | Variation::Random => false, + Variation::Pressure => stroke.pressure.is_some(), + Variation::Tilt => stroke.tilt.is_some(), + Variation::Bearing => stroke.bearing.is_some(), + Variation::Rotation => stroke.rotation.is_some(), + Variation::StylusWheel => stroke.wheel.is_some(), + } +} + +/// Leaves out or adds tiles at the end of `tiles` (each a length and the gap after it) once they +/// have been measured again: with `add_space` as many as fit in `avail` with the gaps between +/// them, at least one, otherwise the count whose lengths and gaps between them come nearest to +/// `avail`. An added tile is +/// `natural(s)` long at `s` from the run's start. +fn recount(tiles: &mut Vec<(f64, f64)>, avail: f64, add_space: bool, natural: &dyn Fn(f64) -> (f64, f64)) { + let mut length: f64 = tiles.iter().map(|t| t.0).sum(); + let mut gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + // How much of the run the tiles and the spacing between them take. + let run = |length: f64, gaps: f64| length + gaps; + while let [.., (_, before), (w, _)] = tiles.as_slice() { + let (w, before) = (*w, *before); + let (now, without) = (run(length, gaps), run(length - w, gaps - before)); + let drop = if add_space { now > avail } else { (without - avail).abs() < (now - avail).abs() }; + if !drop { + break; + } + tiles.pop(); + length -= w; + gaps -= before; + } + while tiles.len() < MAX_TILES { + let last_gap = tiles.last().map_or(0.0, |t| t.1); + let now = run(length, gaps); + let (w, g) = natural(run(length, gaps + last_gap)); + if w.is_nan() || w <= 1e-9 { + break; + } + let with = run(length + w, gaps + last_gap); + let add = if add_space { with <= avail } else { (with - avail).abs() < (now - avail).abs() }; + if !add { + break; + } + tiles.push((w, g)); + length += w; + gaps += last_gap; + } +} + +/// A pattern brush's side tiles on the run `avail` long from `a` of `t` (`marks` as +/// [`tile_scaled`] takes them), at the scale `k(s)` at +/// arc length `s` ([`varied_tiles`]), fitted as `pb.fit` says: Stretch scales the lengths and gaps +/// to fill the run, Add Space keeps the lengths and shares out what is left between the tiles +/// (around a lone tile), and Approximate keeps both and centers the tiles on the run. +fn varied_side_tiles( + out: &mut Budget, + t: &Track, + pb: &PatternBrush, + side: &(Node, Rect), + (a, avail): (f64, f64), + k: &dyn Fn(f64) -> f64, + marks: &[f64], +) { + let tw = side.1.width(); + // Each side tile and the gap after it as long as the scale at the tile's middle. + let natural = |s: f64| { + let w = tw * k(s + tw * k(s) / 2.0); + (w, w * pb.spacing.max(0.0) / 100.0) + }; + let (tiles, count) = varied_tiles(a, avail, &natural); + let n = match pb.fit { + PatternFit::AddSpace => count.floor(), + PatternFit::Stretch | PatternFit::Approximate => count.round(), + } + .max(1.0) as usize; + let mut tiles = tiles[..n.min(tiles.len())].to_vec(); + // How far the fit stretches the tiles and gaps, where the first tile starts, and the space + // between tiles when the fit sets it. + let fitted = |tiles: &[(f64, f64)]| { + let length: f64 = tiles.iter().map(|t| t.0).sum(); + // The gaps between the tiles: after every tile but the last. + let gaps: f64 = tiles.split_last().map_or(0.0, |(_, before)| before.iter().map(|t| t.1).sum()); + match pb.fit { + PatternFit::Stretch => (avail / (length + gaps), 0.0, None), + PatternFit::AddSpace if tiles.len() > 1 => (1.0, 0.0, Some(((avail - length) / (tiles.len() - 1) as f64).max(0.0))), + PatternFit::AddSpace => (1.0, (avail - tiles.first().map_or(0.0, |t| t.0)) / 2.0, None), + PatternFit::Approximate => (1.0, (avail - length - gaps) / 2.0, None), + } + }; + // The fit moves the tiles from where they were measured, so each is measured again at the + // middle of where the fit puts it, and the fit worked out again, a few times over. + for _ in 0..REFITS { + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for tile in &mut tiles { + let placed = tile.0 * stretch; + let w = tw * k(s0 + placed / 2.0); + s0 += placed + space.unwrap_or(tile.1 * stretch); + *tile = (w, w * pb.spacing.max(0.0) / 100.0); + } + recount(&mut tiles, avail, pb.fit == PatternFit::AddSpace, &|s| natural(a + s)); + } + let (stretch, lead, space) = fitted(&tiles); + let mut s0 = a + lead; + for &(w, g) in &tiles { + let w = w * stretch; + out.take(tile_scaled(t, side, s0, s0 + w, k, Some(marks))); + if out.full() { + break; + } + s0 += w + space.unwrap_or(g * stretch); + } +} + /// What a pattern brush draws at a corner: corner tile art (oriented, with its bounds), or what /// [`CornerSource`] gives. #[derive(Clone, Copy)] @@ -800,10 +1021,15 @@ fn masked(n: Node, quad: &[Point], p: Point, towards: Vec2) -> Option { Some(Node::new(NodeId(0), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(n)], clip: true })) } -pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec { +/// A pattern brush's tiles along `bp`. With a scale that follows the pen (its pressure, tilt, +/// bearing, rotation or wheel), the tiles are as tall as what `stroke` recorded at each point gives +/// (half way without a recording), each tile and the gap after it as long as the scale at its +/// middle, and each corner tile at the scale at its corner. +pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &StrokeLayer) -> Vec { let orient = |n: &Node, frame| oriented_tile(n, frame, pb.flip_along, pb.flip_across); let Some(side) = orient(&pb.side, pb.side_frame) else { return vec![] }; - let k = weight * pb.scale.max(1.0) / 100.0; + let scale_at = |p: f64| pattern_scale_at(pb, weight, p); + let (k, varies) = pattern_scale(pb, weight, stroke); let outer = pb.outer_corner.as_ref().and_then(|n| orient(n, pb.outer_corner_frame)); let inner = pb.inner_corner.as_ref().and_then(|n| orient(n, pb.inner_corner_frame)); let start = pb.start.as_ref().and_then(|n| orient(n, pb.start_frame)); @@ -822,6 +1048,16 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if l <= 1e-9 { continue; } + // The scale at arc length `s` of the track; a run past the start of a closed track wraps + // round to it, and on an open track a point past either end takes the scale at that end. + let ks = |s: f64| { + if !varies { + return k; + } + let at = (if t.closed && s > l { s - l } else { s }).clamp(0.0, l); + scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5)) + }; + let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l)); let corners = t.corner_positions(); // Corner tiles, centred on the corner and turned to the bisector. The path on each side of // a corner is shortened by `trims` (`None`: half the widest corner tile art). @@ -845,17 +1081,18 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec }; before.min(after) }; - for (ci, &(i, _)) in corners.iter().enumerate() { + for (ci, &(i, at)) in corners.iter().enumerate() { if out.full() { break; } + let kc = ks(at); let (a, b) = t.in_out(i); // Turning towards the left normal puts the tile's +y side on the inside. let tile = if a.cross(b) > 0.0 { inner_tile.or(outer.as_ref().map(Corner::Art)) } else { outer_tile.or(inner.as_ref().map(Corner::Art)) }; let (art, bb) = match tile { Some(Corner::Art(tile)) => tile, Some(Corner::Source(source)) => { - let (pieces, trim) = auto_corner(&t, i, source, &side, k, room(ci)); + let (pieces, trim) = auto_corner(&t, i, source, &side, kc, room(ci)); for n in pieces { out.take(Some(n)); } @@ -867,8 +1104,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec continue; } }; - trims.push(None); - corner_half = corner_half.max(bb.width() * k / 2.0); + // With a scale that varies, each corner's tile is its own size, so the path beside it + // is shortened by half of that tile. + trims.push(varies.then_some(bb.width() * kc / 2.0)); + corner_half = corner_half.max(bb.width() * kc / 2.0); // Inner and outer corner art is the corner that joins a side tile on its right to one // below it, so its arms point along +x and +y (as the flips leave them). The tile is // turned so that the line halving its arms lies on the line halving the sides at the @@ -878,7 +1117,7 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec let arms = Vec2::new(if pb.flip_along { -1.0 } else { 1.0 }, if pb.flip_across { -1.0 } else { 1.0 }); let sides = b - a; let angle = sides.y.atan2(sides.x) - arms.y.atan2(arms.x); - let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(k) * Affine::translate(-bb.center().to_vec2()); + let xf = Affine::translate(t.verts[i].to_vec2()) * Affine::rotate(angle) * Affine::scale(kc) * Affine::translate(-bb.center().to_vec2()); let mut n = art.clone(); n.transform(xf, true); out.take(Some(n)); @@ -911,9 +1150,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri == 0 && let Some(st) = &start { - let w = st.1.width() * k; + // As long as the scale at its middle. + let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0)); if b - a > w { - out.take(tile_on(&t, st, a, a + w, k)); + out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref())); a += w; } } @@ -921,9 +1161,9 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec && ri + 1 == nruns && let Some(en) = &end { - let w = en.1.width() * k; + let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0)); if b - a > w { - out.take(tile_on(&t, en, b - w, b, k)); + out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref())); b -= w; } } @@ -931,6 +1171,10 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64) -> Vec if avail <= 1e-6 { continue; } + if let Some(marks) = &marks { + varied_side_tiles(&mut out, &t, pb, &side, (a, avail), &ks, marks); + continue; + } let unit = tw + gap; match pb.fit { PatternFit::Stretch => { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index fbd4512fa3..5653b42bb6 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -170,7 +170,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; stylusWheel from value − variation at one end of an airbrush pen's finger wheel to value + variation at the other; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation|stylusWheel for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°; stylusWheel: a at one end of an airbrush pen's finger wheel to b at the other), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; stylusWheel: width at one end of the finger wheel to width_max at the other; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, scale_mode: null (fixed)|pressure|tilt|bearing|rotation|stylusWheel, scale_max 1..10000% (the tiles go from scale to scale_max over the same pen ranges as an art brush's width; half way on a stroke drawn without that input; each tile's height follows the stroke, its length and the gap after it take the scale at its middle, and a corner tile takes the scale at its corner), spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -179,7 +179,7 @@ pub fn specs() -> Vec { "Options of Selected Object…", [], None, - "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", + "{ids?|id?, params?: {…the fields brush.options takes that a path can set for itself: calligraphic angle (counter-clockwise from level), roundness, size, variation, modes; scatter size, spacing, scatter, rotation (counter-clockwise), modes, rotation_relative_to_path, colorization; art width, width_mode, width_max, flip_along, flip_across, overlap, colorization; pattern scale, scale_mode, scale_max, spacing, fit, flip_along, flip_across, colorization (values outside their ranges are clamped; a colorization object changes only the fields it gives; a null item of an array such as size: [40, null] keeps each stroke's own item, else the brush's)}, reset?: bool} set the brush settings of the brushed strokes of the selected paths on those strokes only, leaving the brush and its other strokes as they are (the Brushes panel's Options of Selected Object); params add to each stroke's own settings, a mode params does not set (no modes, or a null item) stays the one each stroke draws with when a changed variation or range would change it, a setting equal to the brush's own value is dropped, and reset: true clears them so the strokes draw the brush again; without params or reset nothing changes; one undo step, none when nothing changes. The brushes' own edits (brush.options) still reach the settings a stroke does not set, applying a brush (brush.apply, stroke.setAdvanced or a brush.freehand extend with another brush) or removing it clears them, and a renamed brush keeps them. Refused with nothing painted with a brush selected, for paths painted with brushes of different types, for a bristle brush, for a field the type does not take and for a value of the wrong kind → {ids: the brushed paths, changed: the paths whose settings changed, options: the first stroke's own settings}", has_doc, brush_object_options ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index b0ab4366d2..cb5ac44c40 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -580,7 +580,7 @@ pub(super) fn brush_object_options(s: &mut Session, p: &Value) -> Result merged.insert(k.clone(), next); } keep_drawn_modes(b, &was, ¶ms, &mut merged); - keep_largest_width(b, &was, ¶ms, &mut merged); + keep_second_value(b, &was, ¶ms, &mut merged); b.stroke_options_that_differ(&merged).map_err(|e| bad(C, e))? }; options.get_or_insert_with(|| next.clone()); @@ -643,27 +643,34 @@ fn keep_drawn_modes( merged.insert("modes".into(), Value::Array(kept)); } -/// Keep the largest width a stroke of art brush `b` draws with (with its own settings `was`) when -/// `params` sets `width` and no `width_max`. Without a `width_max` of its own the largest width is -/// the width, so without this a changed width would also change the largest width. -fn keep_largest_width( +/// Keep the second value a stroke of brush `b` draws with (with its own settings `was`) when +/// `params` sets the first and not the second: an art brush's `width` and `width_max`, a pattern +/// brush's `scale` and `scale_max`. Without a second value of its own the second value is the +/// first, so without this a changed first value would also change the second. +fn keep_second_value( b: &Brush, was: &serde_json::Map, params: &serde_json::Map, merged: &mut serde_json::Map, ) { - if params.get("width").is_none_or(Value::is_null) || params.get("width_max").is_some_and(|m| !m.is_null()) { + let (first, second) = match b.kind { + BrushKind::Art(_) => ("width", "width_max"), + BrushKind::Pattern(_) => ("scale", "scale_max"), + _ => return, + }; + if params.get(first).is_none_or(Value::is_null) || params.get(second).is_some_and(|m| !m.is_null()) { return; } - let art = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { - Some(BrushKind::Art(a)) => Some(a), + // The first value, the second value of its own, and whether the value follows the pen. + let values = |o: &serde_json::Map| match b.with_stroke_options(o).ok().map(|b| b.kind) { + Some(BrushKind::Art(a)) => Some((a.width, a.width_max, a.width_mode.is_some_and(|m| m.follows_pen()))), + Some(BrushKind::Pattern(p)) => Some((p.scale, p.scale_max, p.scale_mode.is_some_and(|m| m.follows_pen()))), _ => None, }; - let (Some(before), Some(after)) = (art(was), art(merged)) else { return }; - let follows_pen = |a: &brush::ArtBrush| a.width_mode.is_some_and(|m| m.follows_pen()); - // Only a width that followed the pen has a largest width, and only one that still does uses it. - if before.width_max.is_none() && follows_pen(&before) && follows_pen(&after) && after.width != before.width { - merged.insert("width_max".into(), json!(before.width)); + let (Some(before), Some(after)) = (values(was), values(merged)) else { return }; + // Only a value that followed the pen has a second value, and only one that still does uses it. + if before.1.is_none() && before.2 && after.2 && after.0 != before.0 { + merged.insert(second.into(), json!(before.0)); } } diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 1d53214ec9..9a1039405a 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -242,6 +242,70 @@ fn options_of_selected_object_keep_each_paths_largest_width_when_the_width_chang assert_eq!((arrow_width_range(&s, a), arrow_width_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); } +/// The scales (%) the first stroke of `id`, painted with Stitches, draws with where the pen reads 0 +/// and 1. +fn stitches_scale_range(s: &Session, id: NodeId) -> (f64, f64) { + let lib = vectorcraft_brush::library(&s.doc().unwrap().doc); + let b = lib.iter().find(|b| b.name == "Stitches").unwrap(); + match b.with_stroke_options(own_options(s, id).as_object().unwrap()).unwrap().kind { + vectorcraft_brush::BrushKind::Pattern(p) => p.scale_range(), + k => panic!("not a pattern brush: {k:?}"), + } +} + +#[test] +fn options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes() { + let mut s = session(); + let a = line(&mut s); + let b = line(&mut s); + s.execute("brush.apply", &json!({"name": "Stitches", "ids": [a.0, b.0]})).unwrap(); + // Both scales follow the pressure; the first path's second scale is its scale, the second + // path's is its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100, "scale_mode": "pressure"}})).unwrap(); + s.execute("brush.objectOptions", &json!({"ids": [b.0], "params": {"scale": 100, "scale_mode": "pressure", "scale_max": 150}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((100.0, 100.0), (100.0, 150.0))); + // The scale the path has already changes nothing. + let steps = undo_steps(&s); + assert_eq!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale": 100}})).unwrap()["changed"], json!([])); + assert_eq!(own_options(&s, a), json!({"scale_mode": "pressure"})); + assert_eq!(undo_steps(&s), steps); + // A new first scale leaves each path's second scale as it was. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 50}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((50.0, 100.0), (50.0, 150.0))); + // A second scale the params give is set on each path, and the brush keeps its own. + s.execute("brush.objectOptions", &json!({"ids": [a.0, b.0], "params": {"scale": 40, "scale_max": 120}})).unwrap(); + assert_eq!((stitches_scale_range(&s, a), stitches_scale_range(&s, b)), ((40.0, 120.0), (40.0, 120.0))); + let def = s.execute("brush.get", &json!({"name": "Stitches"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + // A mode that is not one is refused, and nothing changes. + let steps = undo_steps(&s); + assert!(s.execute("brush.objectOptions", &json!({"ids": [a.0], "params": {"scale_mode": "sideways"}})).is_err()); + assert_eq!(undo_steps(&s), steps); +} + +/// Pattern Brush Options' Scale mode and second scale go through `brush.new`, `brush.options` +/// and `brush.get`; a partial edit keeps the other fields, and Fixed leaves both out. +#[test] +fn pattern_brush_scale_mode_goes_through_the_brush_commands() { + let mut s = session(); + let side = rect(&mut s, 0.0, 0.0, 40.0, 8.0); + let params = json!({"scale": 50, "scale_mode": "tilt", "scale_max": 300}); + s.execute("brush.new", &json!({"type": "pattern", "name": "Rail", "params": params, "ids": [side.0]})).unwrap(); + let get = |s: &mut Session| s.execute("brush.get", &json!({"name": "Rail"})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(300.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_max": 200, "spacing": 10}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(50.0), &json!("tilt"), &json!(200.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "stylusWheel", "scale_max": 1e9}})).unwrap(); + let def = get(&mut s); + assert_eq!((&def["scale_mode"], &def["scale_max"]), (&json!("stylusWheel"), &json!(10000.0))); + s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": null, "scale_max": null}})).unwrap(); + let def = get(&mut s); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!(s.execute("brush.options", &json!({"name": "Rail", "params": {"scale_mode": "sideways"}})).is_err()); +} + #[test] fn options_of_selected_object_go_when_a_freehand_stroke_changes_the_brush() { let mut s = session(); diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index c3dbf78293..ed77fbb415 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1115,13 +1115,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 8054553d22..8b9f577ad8 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -14,7 +14,9 @@ //! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, //! `overlap` (bend on each run between sharp corners). -//! Pattern: `scale`, `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, +//! Pattern: `scale`, `scaleMax` (the scale at the heaviest pen pressure, upright, at 180° or at +//! the wheel's far end, %), `scaleMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation` | +//! `stylusWheel`), `spacing` (%), `fit` (`stretch` | `addSpace` | `approximate`), `flipAlong`, //! `flipAcross`, `outerCornerTile` and `innerCornerTile` (`original`: the corner art the brush //! draws there | `none` | `autoCentered` | `autoBetween` | `autoSliced` | `autoOverlap`: a tile //! made from the side tile), @@ -208,6 +210,8 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { } BrushKind::Pattern(p) => { f.insert("scale".into(), json!(p.scale)); + f.insert("scaleMode".into(), json!(p.scale_mode.unwrap_or_default().id())); + f.insert("scaleMax".into(), json!(p.scale_range().1)); f.insert("spacing".into(), json!(p.spacing)); f.insert("fit".into(), json!(id_of(&p.fit))); f.insert("flipAlong".into(), json!(p.flip_along)); @@ -261,6 +265,47 @@ fn art_width_mode(d: &Dialog) -> Variation { Variation::parse(&d.str("widthMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) } +/// How a pattern brush's scale varies: Fixed, or with the pen's pressure, tilt, bearing, rotation +/// or wheel. +fn pattern_scale_mode(d: &Dialog) -> Variation { + Variation::parse(&d.str("scaleMode")).filter(|m| m.follows_pen()).unwrap_or(Variation::Fixed) +} + +/// The second value (`max_key`, the definition's `def_max`) of a value that follows the pen (`key`, +/// the same in the definition), for `brush.options` params. `null` in Options of Selected Object +/// when the path it opened with has no second value and the second value has not been changed from +/// the value it opened with, so each selected path keeps its own. +fn second_value(d: &Dialog, (key, max_key, def_max): (&str, &str, &str), range: (f64, f64)) -> Value { + let v = clamped(d, max_key, range); + let def = d.fields.get("__def"); + let opened = def.and_then(|def| def.get(key)).and_then(Value::as_f64); + let unset = def.and_then(|def| def.get(def_max)).is_none_or(Value::is_null); + if d.bool(super::brush_options::OBJECT) && unset && opened == Some(v) { Value::Null } else { json!(v) } +} + +/// The second value field `max_key` (enabled only for a mode that follows the pen) and the +/// [`PEN_SIZE_MODES`] menu `mode_key` of a row labeled `label` (an art brush's Width, a pattern +/// brush's Scale), at `mode`. Screen readers call them `label` and Maximum, and `label` and Mode. +fn pen_mode_controls(ui: &mut egui::Ui, d: &mut Dialog, label: &str, (max_key, mode_key): (&str, &str), range: (f64, f64), mode: Variation) { + let max_name = format!("{label} {}", tl!("Maximum")); + ui.add_enabled_ui(mode.follows_pen(), |ui| { + let v = clamped(d, max_key, range); + if let Some(v) = widgets::range_field_named(ui, ("brush-art-value", max_key), Some(&max_name), v, range.0..=range.1, "%", 0, 72.0) { + d.fields.insert(max_key.into(), json!(v)); + } + }); + let mode_name = format!("{label} {}", tl!("Mode")); + let labels = PEN_SIZE_MODES.map(Variation::label); + let picked = widgets::dropdown_named(ui, ("brush-pen-mode", mode_key), Some(&mode_name), mode.label(), &labels, 104.0); + if let Some(m) = picked.and_then(|i| PEN_SIZE_MODES.get(i)) { + d.fields.insert(mode_key.into(), json!(m.id())); + } +} + +/// The modes an art brush's width and a pattern brush's scale offer, in menu order. +const PEN_SIZE_MODES: [Variation; 6] = + [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; + /// `brush.options` params from the fields. pub(super) fn params(d: &Dialog) -> Value { let mut p = match d.str("__type").as_str() { @@ -287,7 +332,7 @@ pub(super) fn params(d: &Dialog) -> Value { json!({ "width": clamped(d, "width", ArtBrush::WIDTH_RANGE), "width_mode": if pen { json!(mode.id()) } else { Value::Null }, - "width_max": if pen { json!(clamped(d, "widthMax", ArtBrush::WIDTH_RANGE)) } else { Value::Null }, + "width_max": if pen { second_value(d, ("width", "widthMax", "width_max"), ArtBrush::WIDTH_RANGE) } else { Value::Null }, "scale": serde_json::to_value(scale).unwrap_or_default(), "direction": id_of(&parse_field::(d, "direction")), "flip_along": d.bool("flipAlong"), @@ -296,8 +341,12 @@ pub(super) fn params(d: &Dialog) -> Value { }) } _ => { + let mode = pattern_scale_mode(d); + let pen = mode.follows_pen(); let mut p = json!({ "scale": clamped(d, "scale", PatternBrush::SCALE_RANGE), + "scale_mode": if pen { json!(mode.id()) } else { Value::Null }, + "scale_max": if pen { second_value(d, ("scale", "scaleMax", "scale_max"), PatternBrush::SCALE_RANGE) } else { Value::Null }, "spacing": clamped(d, "spacing", PatternBrush::SPACING_RANGE), "fit": id_of(&parse_field::(d, "fit")), "flip_along": d.bool("flipAlong"), @@ -410,13 +459,6 @@ fn number(ui: &mut egui::Ui, d: &mut Dialog, key: &str, range: (f64, f64), suffi }); } -/// A row labeled `label` with a slider and a whole-number field (%) bound to `d.fields[key]`, both -/// kept within `range`; screen readers call the slider `label`. -fn slider_row(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, range: (f64, f64)) { - let rail = Tokens::get(ui.ctx()).input_border; - widgets::label_row(ui, label, LABEL_W, |ui| super::form::slider_field_named(ui, d, key, label, range.0..=range.1, "%", &|_| rail)); -} - /// A row of radio buttons bound to the string field `key`: (value, label). fn radios(ui: &mut egui::Ui, d: &mut Dialog, key: &str, options: &[(&str, &str)]) { let cur = d.str(key); @@ -472,12 +514,7 @@ fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { let range = ArtBrush::WIDTH_RANGE; widgets::label_row(ui, tl!("Width:"), LABEL_W, |ui| { super::form::slider_field_named(ui, d, "width", tl!("Width:"), range.0..=range.1, "%", &|_| rail); - let mode = art_width_mode(d); - number(ui, d, "widthMax", range, "%", mode.follows_pen()); - let modes = [Variation::Fixed, Variation::Pressure, Variation::Tilt, Variation::Bearing, Variation::Rotation, Variation::StylusWheel]; - if let Some(m) = widgets::dropdown(ui, "brush-art-width-mode", mode.label(), &modes.map(Variation::label), 104.0).and_then(|i| modes.get(i)) { - d.fields.insert("widthMode".into(), json!(m.id())); - } + pen_mode_controls(ui, d, tl!("Width:"), ("widthMax", "widthMode"), range, art_width_mode(d)); }); // A path sets its own width, flips, overlap and colorization, not how the art scales or runs. if d.bool(super::brush_options::OBJECT) { @@ -543,7 +580,13 @@ fn arrow_button(ui: &mut egui::Ui, dir: Direction, selected: bool, tip: &str) -> } fn pattern_body(ui: &mut egui::Ui, d: &mut Dialog) { - slider_row(ui, d, "scale", tl!("Scale:"), PatternBrush::SCALE_RANGE); + // Scale, then the second scale (only when the scale follows the pen) and how it varies. + let rail = Tokens::get(ui.ctx()).input_border; + let range = PatternBrush::SCALE_RANGE; + widgets::label_row(ui, tl!("Scale:"), LABEL_W, |ui| { + super::form::slider_field_named(ui, d, "scale", tl!("Scale:"), range.0..=range.1, "%", &|_| rail); + pen_mode_controls(ui, d, tl!("Scale:"), ("scaleMax", "scaleMode"), range, pattern_scale_mode(d)); + }); widgets::label_row(ui, tl!("Spacing:"), LABEL_W, |ui| number(ui, d, "spacing", PatternBrush::SPACING_RANGE, "%", true)); ui.add_space(6.0); // The tiles belong to the brush; a path sets its own scale, spacing, flips, fit and colorization. diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index de59668708..e57008e2c4 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -323,6 +323,53 @@ fn art_options_width_follows_tilt_bearing_and_rotation() { } } +/// Pattern Brush Options' Scale menu: Pressure, Tilt, Bearing, Rotation and Stylus Wheel each take +/// a second scale, a stroke drawn without the pen's input is half way between the two, and the +/// dialog shows the mode set when it opens again; Fixed drops the second scale. +#[test] +fn pattern_options_scale_follows_the_pen() { + let mut app = app(); + let (id, before) = brushed(&mut app, "Diamonds"); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("scaleMode"), d.f64("scaleMax", 0.0)), ("fixed".into(), 100.0)); + assert!(shown(&mut app).contains("Fixed")); + // Screen readers name the second scale and the menu after the Scale row. + let nodes = crate::widgets::accessibility_tests::tree(|ui| super::super::show(&mut app, ui.ctx())); + assert!(nodes.iter().any(|n| n.label() == Some("Scale: Mode") && n.role() == egui::accesskit::Role::ComboBox), "a menu named Scale: Mode"); + assert!(nodes.iter().any(|n| n.label() == Some("Scale: Maximum")), "a field named Scale: Maximum"); + super::super::cancel(&mut app); + for (mode, label) in + [("pressure", "Pressure"), ("tilt", "Tilt"), ("bearing", "Bearing"), ("rotation", "Rotation"), ("stylusWheel", "Stylus Wheel")] + { + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scaleMode": mode, "scaleMax": 300})); + assert!(shown(&mut app).contains(label), "{mode}"); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert_eq!((&def["scale"], &def["scale_mode"], &def["scale_max"]), (&json!(100.0), &json!(mode), &json!(300.0)), "{mode}"); + // A stroke drawn without the pen's input is half way: 200 %. + let after = drawn_height(&app, id); + assert!((after - 2.0 * before).abs() < 0.01 * before, "{mode}: {before} then {after}"); + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("scaleMode"), d.f64("scaleMax", 0.0)), (mode.into(), 300.0), "{mode}"); + super::super::cancel(&mut app); + } + // A second scale past the range is kept within it. + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scaleMode": "pressure", "scaleMax": 1e9})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale_max"], json!(10000.0)); + // Fixed drops the second scale, and the stroke draws as it did. + app.run("ui.brushOptions", json!({"name": "Diamonds"})).unwrap(); + set(&mut app, json!({"scaleMode": "fixed"})); + super::super::confirm(&mut app).unwrap(); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("scale_mode").is_none() && def.get("scale_max").is_none(), "{def}"); + assert!((drawn_height(&app, id) - before).abs() < 1e-6); +} + /// A context with the app's fonts and theme, for [`frame`]. fn ctx() -> egui::Context { let ctx = egui::Context::default(); @@ -933,6 +980,47 @@ fn options_of_selected_object_set_one_paths_art_brush_settings() { assert_eq!(own_options(&app, a), json!({"width": 50.0})); } +/// Options of Selected Object for a pattern brush sets one path's Scale mode and second scale; the +/// brush and the other path keep theirs. +#[test] +fn options_of_selected_object_set_one_paths_pattern_scale_mode() { + let mut app = app(); + let a = brushed_line(&mut app, 50.0, "Diamonds"); + let b = brushed_line(&mut app, 100.0, "Diamonds"); + select(&mut app, &[a]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + assert!(shown(&mut app).contains("Scale:")); + set(&mut app, json!({"scaleMode": "tilt", "scaleMax": 250})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale_mode": "tilt", "scale_max": 250.0})); + assert_eq!(own_options(&app, b), json!({})); + let def = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + assert!(def.get("scale_mode").is_none(), "{def}"); + // Opened again, it shows the path's own mode and second scale. + app.run("ui.brushObjectOptions", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("scaleMode"), d.f64("scaleMax", 0.0)), ("tilt".into(), 250.0)); + super::super::cancel(&mut app); + // With paths of different scales selected, choosing a mode alone leaves each path's scale and + // second scale its own: the first path's scale is not given to the second path as its second + // scale. + app.run("brush.objectOptions", json!({"ids": [a], "params": {"scale": 50, "scale_mode": null, "scale_max": null}})).unwrap(); + app.run("brush.objectOptions", json!({"ids": [b], "params": {"scale": 80}})).unwrap(); + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scaleMode": "pressure"})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale": 50.0, "scale_mode": "pressure"})); + assert_eq!(own_options(&app, b), json!({"scale": 80.0, "scale_mode": "pressure"})); + // A changed Scale alone keeps each path's own second scale: its old scale. + select(&mut app, &[a, b]); + app.run("ui.brushObjectOptions", json!({})).unwrap(); + set(&mut app, json!({"scale": 60})); + super::super::confirm(&mut app).unwrap(); + assert_eq!(own_options(&app, a), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 50.0})); + assert_eq!(own_options(&app, b), json!({"scale": 60.0, "scale_mode": "pressure", "scale_max": 80.0})); +} + #[test] fn options_of_selected_object_change_only_the_values_edited_on_each_path() { let mut app = app(); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index d2c72aae40..ff59d0accc 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1116,13 +1116,13 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, scaleMax %, scaleMode: fixed|pressure|tilt|bearing|rotation|stylusWheel, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", "Options of Selected Object…", "", - "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", + "{} open the Brushes panel menu's Options of Selected Object (dialog `brushOptions` with `__object`): the Brush Options of the brush that the first selected brushed path paints with, at that path's own settings, without the name field; Art shows width, widthMax/widthMode, flipAlong, flipAcross and overlap, and Pattern scale, scaleMax/scaleMode, spacing, flipAlong, flipAcross and fit, each with colorization; OK runs brush.objectOptions on the brushed paths selected when it opened, with the values changed since it opened (one end of a range or one colorization field changed leaves each path's other values as they are), and the brush stays as it is. An error with nothing painted with a brush selected, for paths painted with brushes of different types and for a bristle brush", ), ( "ui.graphicStyleOptions", diff --git a/docs/hardware-parity.md b/docs/hardware-parity.md index 37eae066c5..0c3a73b8cc 100644 --- a/docs/hardware-parity.md +++ b/docs/hardware-parity.md @@ -22,7 +22,7 @@ It reads the pen's tilt and barrel rotation on macOS and on Linux under X11 and | Hybrid-graphics GPU choice | automatic | power-saving GPU by default, Preferences › Graphics Processor | same; DX12 then OpenGL; no Vulkan unless asked (#545, #806) | the desktop's GPU | browser | done | | Restart on another GPU when the first fails to present | — | yes (#502, #964) | yes | yes | restart on lost device (#369) | done | | Pen pressure | yes (Wacom, Windows Ink, macOS tablet events) | yes, read from AppKit's tablet events before the window gets them (winit reports none), each move of a stroke with its own pressure, mouse event coalescing off (#852; not yet tried on a Mac) | yes (pointer force via `WM_POINTER`) | under X11 and XWayland (Preferences › Performance › Linux Display Server, #1151, #2028; Automatic uses XWayland when a pen is attached on a Wayland session, #4967), read from XInput2 raw events (#764); **no** on native Wayland, where winit reports none and the pen may not reach the window (#491) | browser pointer events, with coalesced events; Apple Pencil on iPad (hover, palm rejection: fingers navigate after a pen contact until reload) | partial: 2–4 h for Wayland (winit 0.31), plus a check on a Mac | -| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Pattern and Bristle brushes do not use them (an Art brush's Width follows them); 3–6 h (#372) | +| Pen tilt, bearing, barrel rotation (6D Art Pen) | yes, drives brushes | read from AppKit's tablet events (tilt, and the barrel rotation of a pen that reports one); Calligraphic and Scatter brushes vary with them (#764; not yet tried on a Mac) | with Windows Ink, read from the pen's `POINTER_PEN_INFO` (tilt and barrel rotation where its pen mask says the pen reports them); Calligraphic and Scatter brushes vary with them (#372; not yet tried with a pen) | under X11 and XWayland, read from XInput2 raw events; Calligraphic and Scatter brushes vary with them (#764); **no** on native Wayland | no | partial: native Wayland and the web read none, and Bristle brushes do not use them (an Art brush's Width and a Pattern brush's Scale follow them); 3–6 h (#372) | | Pen eraser end | yes | the eraser end (AppKit's tablet proximity events) selects the Eraser tool and the tip brings back the tool used before, as on Linux (#852; not yet tried on a Mac) | with Windows Ink, an inverted pen or its eraser button (`PEN_FLAG_INVERTED`, `PEN_FLAG_ERASER` in the pen's pointer messages) selects the Eraser tool and the tip brings back the tool used before, as on Linux (not yet tried with a pen) | under X11 and XWayland, the eraser end selects the Eraser tool and the tip brings back the tool used before (#764); **no** on native Wayland | a press of the eraser end (Pointer Events eraser button, `button` 5) selects the Eraser tool, and that press erases; a press of the tip brings back the tool used before; Pointer Events report no end while the pen hovers | partial | | Touch gestures (pinch zoom, two-finger pan, rotate view, Touch workspace) | yes (Windows touch, Surface) | trackpad pinch, scroll and rotate | pinch, pan (a second finger cancels the first finger's tool press, #4198); two-finger tap undo, three-finger redo (#585); in the Touch workspace a two-finger tap switches between the Selection tool and the last drawing tool | same where winit reports touch | eframe until the first pen contact, then Pointer Events (pen and fingers told apart); long press opens the context menu | partial: touch workspace and touch-screen rotation missing, 3–5 h | | Trackpad (smooth scroll, pinch) | yes | yes | precision touchpads | yes | yes | done | diff --git a/docs/mcp.md b/docs/mcp.md index e7abf476a9..695528aed5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4127,13 +4127,15 @@ already walks Image Trace. Short agent entry points: level), `roundness`, `size`, `variation` and `modes`; scatter `size`, `spacing`, `scatter`, `rotation` (counter-clockwise), `modes`, `rotation_relative_to_path` and `colorization`; art `width`, `width_mode`, `width_max`, `flip_along`, `flip_across`, - `overlap` and `colorization`; pattern `scale`, `spacing`, `fit`, `flip_along`, `flip_across` and `colorization`. + `overlap` and `colorization`; pattern `scale`, `scale_mode`, `scale_max`, `spacing`, `fit`, `flip_along`, + `flip_across` and `colorization`. Values outside their ranges are clamped as in `brush.options`, a `colorization` object changes only the fields it gives, a `null` item of an array (`size: [40, null]`) keeps each path's own item, else the brush's, and a setting equal to the brush's own value is dropped. The dialog sends only the items and fields changed in it, so editing one end of a range leaves each selected path's other end as it was. A mode that `params` does not set (no `modes`, or a `null` item) stays the one each path draws with, so a changed calligraphic variation or scatter range does not change it. An art `width` without a `width_max` keeps the largest width of each path whose width follows the pen, + a pattern `scale` without a `scale_max` (omitted or `null`) keeps the second scale of each path whose scale follows the pen, and a calligraphic path's `modes: null` (modes that follow its values) stays when another value changes. The dialog changes nothing when another document has become the active one. `reset: true` clears a path's settings. The command refuses `params` together with `reset`, a selection with no brushed path, paths whose brushes are of different @@ -4169,6 +4171,17 @@ already walks Image Trace. Short agent entry points: desktop app reads the wheel from XInput2 (`Abs Wheel`) under X11 and from AppKit (`tangentialPressure`) on macOS; it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation code 3. +- Pattern brush scale from the pen: a pattern brush's `scale_mode` (`brush.new`, `brush.options`, + `brush.objectOptions`; left out or `null` for Fixed) takes `pressure`, `tilt`, `bearing`, `rotation` and + `stylusWheel`, and `scale_max` (1..10000%) is the second scale. The tiles go from `scale` where the pen reads 0 to + `scale_max` where it reads 1, over the ranges an Art brush's `width_mode` uses, and half way on a stroke drawn + without that input; without a `scale_max` both ends are `scale`. Each side, start and end tile is as tall as the + scale at each point of the stroke, and the tile and the gap after it are as long as the scale at the tile's + middle. A corner tile takes the scale at its corner. Stretch to Fit then stretches the tiles and gaps of each run + to fill it, Add Space to Fit shares the space left between the tiles, and Approximate Path centers the tiles on + the run. Another mode, such as `random`, is read as Fixed. A brush with a fixed scale draws as before, and a + brush or stroke without the new fields saves without them. `.ai` files do not read or write the pattern scale's + mode. - Freehand Fidelity: the `fidelity` of `path.freehand` and `brush.freehand` is in points, 1.5 pt when left out. A value must be from 0.000015625 pt (0.01 / 640) to 100 / 0.0313 pt (about 3194.89 pt), and a value outside that range is rejected with an error. The Pencil and the Paintbrush give Fidelity in screen pixels, 0.01 to 100 px, and send it diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 57ac87a396..13a9b41558 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2053,7 +2053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel for Pattern brushes and on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Pattern and Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). @@ -2061,6 +2061,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). The menu also offers Stylus Wheel (next item). + Pattern Brush Options' Scale has a menu of Fixed, Pressure, Tilt, Bearing, Rotation and Stylus Wheel with a second scale beside it, in the library brush's dialog and in Options of Selected Object, from the pen tablet options the Pattern brush options section of the help page (, archived copy) lists for Scale (`brush.options` and `brush.objectOptions` `scale_mode` and `scale_max`). The tiles go from Scale where the pen reads 0 to the second scale where it reads 1, over the same ranges as Art Brush Options' Width, and half way on a stroke without that input. Each side, start and end tile is as tall as the scale at each point of the stroke, and the tile is as long as the scale at its middle; a corner tile takes the scale at its corner. Stretch to Fit stretches the tiles and gaps of each run to fill it, Add Space to Fit shares out what is left between the tiles, and Approximate Path centers them on the run. The help page does not say how the pen maps to the scale or how the tiles are measured along the stroke, so those rules are VectorCraft's own. A brush with a fixed scale draws as before. `.ai` files do not read or write the pattern scale's mode, and the Width tool does not turn the pen's data into width points. Evidence: `tests::pattern_brush_scale_follows_the_pressure`, `tests::pattern_brush_scale_follows_tilt_bearing_rotation_and_the_wheel`, `tests::pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles` (vectorcraft-brush), `tests::brushsym::options_of_selected_object_keep_each_paths_second_scale_when_the_scale_changes`, `tests::brushsym::pattern_brush_scale_mode_goes_through_the_brush_commands` (vectorcraft-engine), `dialogs::brush_options::tests::pattern_options_scale_follows_the_pen`, `dialogs::brush_options::tests::options_of_selected_object_set_one_paths_pattern_scale_mode` (vectorcraft-ui-egui). - **Airbrush stylus wheel:** Calligraphic and Scatter Brush Options offer Stylus Wheel for Size, and Art Brush Options for Width, as the help page lists it (). The Paintbrush records where an airbrush pen's finger wheel is set along each stroke (kept with the path, saved, joined when a stroke continues a path, and interpolated by blends). A Calligraphic Size goes from size − variation at one end of the wheel's travel to size + variation at the other, a Scatter Size from its first value to its second, and an Art Width from Width to the second width; a stroke without a wheel draws the value half way. The direction of travel and the half-way value for a stroke without a wheel are VectorCraft's own rules. On Linux under X11 and XWayland the app reads the wheel from XInput2's `Abs Wheel` valuator, and on macOS from AppKit's `tangentialPressure`; Windows pointer messages have no field for it, and the web build does not read it yet. `path.freehand` points take it seventh and `pointer_gesture` events take `wheel`, and `.ai` brush definitions read and write it as variation code 3. Evidence: `tests::the_stylus_wheel_varies_sizes_and_widths` (vectorcraft-brush), `tests_brushsym::freehand_points_record_the_stylus_wheel` (vectorcraft-engine), `more_brush_settings_are_read_back` and `a_calligraphic_brushs_pen_channels_come_in_by_their_codes` (vectorcraft-eps), `tablet::tests::an_airbrush_wheel_goes_into_the_feed` and `mac_tablet::tests::an_airbrush_wheel_goes_into_the_feed` (vectorcraft). Scatter, Art and Pattern Brush Options have the Tips button for Colorization that the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes, beside Method. It opens Colorization Tips, which shows each method's name and what it does beside a sample of the brush, as OK would make it, painted with that method on a blue stroke; Hue Shift's sample uses the dialog's Key Color. `ui.dialog.set {field: "tips", value: true}` opens it. Screen readers name the button, the popover and each sample. Hue Shift set by `brush.new` or `brush.options` without a key color takes the color the art's fills and strokes use most, as Brush Options already offers it, following the Brushes page, where the key color defaults to the color that stands out most in the art (). The page does not state how prominence is measured. Counting the fills and strokes that use each solid color, with the first one found winning a tie and black for art with no solid color, is VectorCraft's own rule. A `brush.options` edit that gives only the method keeps the brush's key color, and one that gives only an art brush's start guide keeps its end guide. Evidence: `tests_brushsym::hue_shift_without_a_key_takes_the_most_used_art_color`, `tests_brushsym::art_brush_options_keep_the_scale_fields_an_edit_leaves_out`. From c1cdd03b5ce67c1f6a5c06ba5e4c2bc5199c9e1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 22:24:06 -0800 Subject: [PATCH 13/28] Docs: macOS pen pressure is read; only a check on a Mac with a tablet remains --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 13a9b41558..d47ad77c98 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2053,7 +2053,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a gradient stop or a freeform gradient point selected, Alt-clicking a color swatch in the Swatches panel recolors it instead of the inactive Fill or Stroke. - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with the one-sided three-point PCHIP slope at the profile's ends and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined where the width bends, and leaning on dense path flattening) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within a tenth of the flattening tolerance (0.001 pt at the default 0.01 pt) rather than one cubic per flatten step, so exports stay close to a uniform stroke's path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel on Windows and the web, pen pressure on macOS where the windowing layer reports none, and tilt, bearing and rotation for Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: Stylus Wheel on Windows and the web, a check of pen pressure on a Mac with a tablet, and tilt, bearing and rotation for Bristle brushes and on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). From 479202931b163aa1d9ff64fd2a6faad6ac000b7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:40:48 -0800 Subject: [PATCH 14/28] Brushes: pen-driven pattern start and end tiles fit where the scale falls back A start or end tile whose scale follows the pen was left out when it did not fit at the length the scale at the middle of the whole run gives, even where a shorter length fits because the scale rises and falls along the stroke. The length is now the shortest one up to the run's length that is as long as the scale at its own middle: evenly spaced lengths and the lengths whose middle falls on a recorded pen sample are tried in order, and the range where the tile starts to fit is halved. On a closed path, a point before the path's start now takes the scale recorded where Track::frame draws it, near the end of the stroke, as a point past the end already did. A tile that Approximate Path starts before the start took the scale at the start before. --- crates/brush/src/tests.rs | 54 +++++++++++++++++++++++++++++++++++++++ crates/brush/src/warp.rs | 42 ++++++++++++++++++++---------- 2 files changed, 82 insertions(+), 14 deletions(-) diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index cec39f9477..0bb297e425 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2195,6 +2195,60 @@ fn pattern_brush_scale_from_the_pen_places_start_end_and_corner_tiles() { assert!(first_side.is_some_and(|r| near(r.x0, 1.5, 1e-3)), "{first_side:?}"); } +/// A start or end tile whose scale follows the pen is placed where it is as long as the scale at +/// its middle, even when the scale rises again further along and the tile would not fit at the +/// whole run's length. +#[test] +fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_falls_back() { + let doc = Document::new(1.0, 1.0); + let bp = line(0.0, 0.0, 100.0, 0.0); + // From 100 % to 10000 %: 300 % from 5 to 20 pt, 10000 % from 50 pt on; mirrored for the end. + let q = 2.0 / 99.0; + for (start, points, span) in [ + (true, vec![(0.0, 0.0), (0.05, q), (0.2, q), (0.5, 1.0), (1.0, 1.0)], (0.0, 18.0)), + (false, vec![(0.0, 1.0), (0.5, 1.0), (0.8, q), (0.95, q), (1.0, 0.0)], (82.0, 100.0)), + ] { + let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(10000.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + let tile = Some(rect_art(6.0, 4.0)); + (p.start, p.end) = if start { (tile, None) } else { (None, tile) }; + } + // The 6 pt tile at 300 %: 18 pt long, its middle where the scale is 300 %. + let out = stroke_pieces(&doc, &b, &bp, &pressed(points)); + let r = out.first().and_then(Node::geometric_bounds); + assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); + } +} + +/// On a closed path, a tile that Approximate Path starts before the path's start takes the scale +/// recorded at the end of the stroke there, where the tile is drawn. +#[test] +fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() { + let doc = Document::new(1.0, 1.0); + let b = scaled_pattern(PatternFit::Approximate, false, 50.0, Some(Variation::Pressure), Some(300.0)); + // Light over the first 90 % of the stroke, heavy at its end. + let st = pressed(vec![(0.0, 0.0), (0.9, 0.0), (1.0, 1.0)]); + let mut before = 0; + for r in (100..=120).map(f64::from) { + // A circle of radius `r` as 720 sides, from (r, 0) on towards +y. + let mut bp = BezPath::new(); + bp.move_to((r, 0.0)); + for i in 1..720 { + let a = std::f64::consts::TAU * f64::from(i) / 720.0; + bp.line_to((r * a.cos(), r * a.sin())); + } + bp.close_path(); + let out = stroke_pieces(&doc, &b, &bp, &st); + let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("{r}: no tiles") }; + if first.y0 < -0.5 { + // The 4 pt tall tile is 2 pt tall at the light 50 % and nearly 12 pt at the heavy end. + before += 1; + assert!(first.x1 > r + 3.0, "{r}: {first:?}"); + } + } + assert!(before > 0, "no first tile starts before the path's start"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 240a5e14eb..9b027cfc03 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -670,6 +670,10 @@ const REFITS: usize = 3; /// length lies in. const END_SOLVE_STEPS: usize = 48; +/// How many evenly spaced lengths a pattern brush whose scale varies tries for a start or end +/// tile before it halves the range the tile's length lies in. +const END_SCAN_STEPS: usize = 64; + /// The side tiles of a pattern brush on a run `avail` long from `a` when the scale varies along /// it: each tile's length and the gap after it, as `natural` gives them at the tile's start, and /// how many tiles fit whole and what fraction of the next one fits after them. The tiles include @@ -713,19 +717,25 @@ fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, } /// The length of a start or end tile `width` wide at its art's size, at the scale `k_mid(w)` at -/// the middle of the tile when it is `w` long: the length that is as long as the scale at its own -/// middle, found by halving the range from 0 to `room`. A tile that needs more than `room` gets -/// the length it needs at `room`, longer than `room`. -fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64) -> f64 { +/// the middle of the tile when it is `w` long: the shortest length that is as long as the scale at +/// its own middle. The scale can rise and fall along the stroke, so the lengths up to `room` are +/// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded +/// pen sample), and the range between the last one the tile is too long for and the first one it +/// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`, +/// longer than `room`. +fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: &[f64]) -> f64 { let length = |w: f64| width * k_mid(w); let first = length(0.0); if length(first) == first || room.is_nan() || room <= 0.0 { return first; } - if length(room) > room { + let mut tries: Vec = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect(); + tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room)); + tries.sort_by(f64::total_cmp); + let Some(i) = tries.iter().position(|&w| length(w) <= w) else { return length(room); - } - let (mut short, mut long) = (0.0, room); + }; + let (mut short, mut long) = (if i == 0 { 0.0 } else { tries[i - 1] }, tries[i]); for _ in 0..END_SOLVE_STEPS { let mid = (short + long) / 2.0; if length(mid) > mid { @@ -738,7 +748,8 @@ fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64) -> f64 { } /// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its -/// arc length, and again a track's length on, for runs of a closed track that wrap round. +/// arc length, and again a track's length before and after it, for tiles of a closed track that +/// wrap round. fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { let points = match mode { Variation::Fixed | Variation::Random => None, @@ -748,7 +759,7 @@ fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points), Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points), }; - points.into_iter().flatten().flat_map(|&(f, _)| [f * l, f * l + l]).collect() + points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect() } /// Whether `stroke` recorded the pen input `mode` follows. @@ -1048,13 +1059,14 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &Str if l <= 1e-9 { continue; } - // The scale at arc length `s` of the track; a run past the start of a closed track wraps - // round to it, and on an open track a point past either end takes the scale at that end. + // The scale at arc length `s` of the track; on a closed track a point before its start or + // past its end wraps round as `Track::frame` places it (its end itself keeps the scale at + // the end), and on an open track a point past either end takes the scale at that end. let ks = |s: f64| { if !varies { return k; } - let at = (if t.closed && s > l { s - l } else { s }).clamp(0.0, l); + let at = if t.closed && !(0.0..=l).contains(&s) { s.rem_euclid(l) } else { s.clamp(0.0, l) }; scale_at(pb.scale_mode.and_then(|m| PenAt::of(stroke, at / l).control(m)).unwrap_or(0.5)) }; let marks = pb.scale_mode.filter(|_| varies).map(|m| pen_marks(stroke, m, l)); @@ -1151,7 +1163,8 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &Str && let Some(st) = &start { // As long as the scale at its middle. - let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0)); + let breaks: Vec = marks.iter().flatten().map(|&m| 2.0 * (m - a)).collect(); + let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), &breaks); if b - a > w { out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref())); a += w; @@ -1161,7 +1174,8 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &Str && ri + 1 == nruns && let Some(en) = &end { - let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0)); + let breaks: Vec = marks.iter().flatten().map(|&m| 2.0 * (b - m)).collect(); + let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), &breaks); if b - a > w { out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref())); b -= w; From 8dbb3c3f7288c4f94137f5cd1d9011484ccda6ae Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:53:10 -0800 Subject: [PATCH 15/28] Brushes: a pen-driven pattern tile checks only the pen samples within it The check for whether a pattern tile's scale is the same along all of it looked at every recorded pen sample on the track for each tile, so a long stroke with many samples and small tiles took work in proportion to the tiles times the samples. The samples are kept in order, and each tile looks up only the ones within its span. --- crates/brush/src/warp.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index 9b027cfc03..b61b16dd81 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -647,12 +647,18 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti } /// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies -/// (`marks`: the arc lengths of the recorded pen samples, between which the scale runs in a -/// straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it is -/// too when the scale is the same at both ends of the span and at every sample within it. +/// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs +/// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it +/// is too when the scale is the same at both ends of the span and at every sample within it. fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option { let mid = k((s0 + s1) / 2.0); - let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && marks.iter().filter(|&&s| s > s0 && s < s1).all(|&s| k(s) == mid); + // Only the samples within the span are looked at. + let within = |marks: &[f64]| { + let from = marks.partition_point(|&s| s <= s0); + let to = from + marks[from..].partition_point(|&s| s < s1); + marks[from..to].iter().all(|&s| k(s) == mid) + }; + let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks); if mid <= 0.0 || marks.is_none_or(even) { return tile_on(t, tile, s0, s1, mid); } @@ -749,7 +755,7 @@ fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: &[ /// Where along a track `l` long `stroke` recorded the pen input `mode` follows: each sample at its /// arc length, and again a track's length before and after it, for tiles of a closed track that -/// wrap round. +/// wrap round, in order. fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { let points = match mode { Variation::Fixed | Variation::Random => None, @@ -759,7 +765,9 @@ fn pen_marks(stroke: &StrokeLayer, mode: Variation, l: f64) -> Vec { Variation::Rotation => stroke.rotation.as_ref().map(|p| &p.points), Variation::StylusWheel => stroke.wheel.as_ref().map(|p| &p.points), }; - points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect() + let mut marks: Vec = points.into_iter().flatten().flat_map(|&(f, _)| [f * l - l, f * l, f * l + l]).collect(); + marks.sort_by(f64::total_cmp); + marks } /// Whether `stroke` recorded the pen input `mode` follows. From 452cfe4d4a3e5c4ce46c8e01e50a0c5fe9b938b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:20:09 -0800 Subject: [PATCH 16/28] Brushes: pen-driven pattern tiles follow the scale across a closed path's start A side tile over a closed path's start was drawn at one scale when the scale at its ends, its middle and each pen sample within it was the same, even where the scale recorded at the end of the stroke differed from the one at its start. Such a tile now also needs the same scale at the stroke's start and end before it is drawn at one scale. A start or end tile no longer takes the length the scale gives at its first length's middle when that length matches. The search over the lengths up to the run now runs whenever the scale follows the pen, so a tile that fits at a shorter length is placed there. --- crates/brush/src/tests.rs | 57 +++++++++++++++++++++++++++++++++++++++ crates/brush/src/warp.rs | 27 ++++++++++++------- 2 files changed, 74 insertions(+), 10 deletions(-) diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index 0bb297e425..15b8f252aa 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -2218,6 +2218,22 @@ fn pattern_brush_scale_from_the_pen_fits_start_and_end_tiles_where_the_scale_fal let r = out.first().and_then(Node::geometric_bounds); assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); } + // 400 % at the start, 100 % from 15 to 20 pt, 400 % from 40 pt on, mirrored for the end: a 30 pt + // tile at 100 % fits at its middle, although at the scale at its first length's middle it is as + // long as that length. + for (start, points, span) in [ + (true, vec![(0.0, 1.0), (0.15, 0.0), (0.2, 0.0), (0.4, 1.0), (1.0, 1.0)], (0.0, 30.0)), + (false, vec![(0.0, 1.0), (0.6, 1.0), (0.8, 0.0), (0.85, 0.0), (1.0, 1.0)], (70.0, 100.0)), + ] { + let mut b = scaled_pattern(PatternFit::Stretch, false, 100.0, Some(Variation::Pressure), Some(400.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + let tile = Some(rect_art(30.0, 4.0)); + (p.start, p.end) = if start { (tile, None) } else { (None, tile) }; + } + let out = stroke_pieces(&doc, &b, &bp, &pressed(points)); + let r = out.first().and_then(Node::geometric_bounds); + assert!(r.is_some_and(|r| near(r.x0, span.0, 1e-6) && near(r.x1, span.1, 1e-6)), "start {start}: {r:?}"); + } } /// On a closed path, a tile that Approximate Path starts before the path's start takes the scale @@ -2249,6 +2265,47 @@ fn pattern_brush_scale_from_the_pen_wraps_before_a_closed_paths_start() { assert!(before > 0, "no first tile starts before the path's start"); } +/// On a closed path, a tile over the path's start follows the scale on both sides of the start, +/// even when the scale is the same at the tile's ends, its middle and every pen sample within it. +#[test] +fn pattern_brush_scale_from_the_pen_changes_where_a_closed_path_wraps_round() { + let doc = Document::new(1.0, 1.0); + let mut b = scaled_pattern(PatternFit::Approximate, false, 100.0, Some(Variation::Pressure), Some(300.0)); + if let BrushKind::Pattern(p) = &mut b.kind { + p.side = rect_art(54.0, 4.0); + } + // A closed path 256 pt long without corners, from (0, 0) along +x: its sides in each quarter + // turn, and the same turned three more times. + let quarter = [(28.0, 0.0), (12.0, 5.0), (4.0, 3.0), (3.0, 4.0), (5.0, 12.0)]; + let mut bp = BezPath::new(); + let mut at = (0.0, 0.0); + bp.move_to(at); + for turn in 0..4 { + for &(x, y) in &quarter { + let (dx, dy) = match turn { + 0 => (x, y), + 1 => (-y, x), + 2 => (-x, -y), + _ => (y, -x), + }; + at = (at.0 + dx, at.1 + dy); + if at != (0.0, 0.0) { + bp.line_to(at); + } + } + } + bp.close_path(); + // 100 % up to 4 pt before the end, rising to 300 % at the end. Approximate Path places five + // 54 pt tiles, the first from 7 pt before the start: at 100 % at both its ends, its middle and + // the samples at 4 pt before the start and at the start, but larger from 4 pt before it. + let st = pressed(vec![(0.0, 0.0), (252.0 / 256.0, 0.0), (1.0, 1.0)]); + let out = stroke_pieces(&doc, &b, &bp, &st); + let Some(first) = out.first().and_then(Node::geometric_bounds) else { panic!("no tiles") }; + // The 4 pt tall tile is 2 pt either side of the path at 100 %, and 5 pt at 1 pt before the + // start, where the scale is 250 %. + assert!(first.y0 < -3.5, "{first:?}"); +} + /// Definitions from files and commands are kept within their ranges. #[test] fn sanitize_keeps_values_within_their_ranges() { diff --git a/crates/brush/src/warp.rs b/crates/brush/src/warp.rs index b61b16dd81..06d9655b21 100644 --- a/crates/brush/src/warp.rs +++ b/crates/brush/src/warp.rs @@ -649,7 +649,8 @@ fn tile_on(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, cross: f64) -> Opti /// A tile placed on [s0, s1] of the track, `k(s)` across at arc length `s` when the scale varies /// (`marks`: the arc lengths of the recorded pen samples in order, between which the scale runs /// in a straight line), else `k` at the middle of the span across all of it ([`tile_on`]), as it -/// is too when the scale is the same at both ends of the span and at every sample within it. +/// is too when the scale is the same at both ends of the span, at every sample within it and, at +/// a closed track's start within it, on both sides of the start. fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) -> f64, marks: Option<&[f64]>) -> Option { let mid = k((s0 + s1) / 2.0); // Only the samples within the span are looked at. @@ -658,7 +659,12 @@ fn tile_scaled(t: &Track, tile: &(Node, Rect), s0: f64, s1: f64, k: &dyn Fn(f64) let to = from + marks[from..].partition_point(|&s| s < s1); marks[from..to].iter().all(|&s| k(s) == mid) }; - let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks); + // A closed track's scale goes from the one at its end to the one at its start where it wraps + // round, so a span over its start (or a track's length before or after it) takes both. + let l = t.len(); + let seam = t.closed && l > 0.0 && (s0 / l).ceil() <= (s1 / l).floor(); + let ends = || !seam || (k(0.0) == mid && k(l) == mid); + let even = |marks: &[f64]| k(s0) == mid && k(s1) == mid && within(marks) && ends(); if mid <= 0.0 || marks.is_none_or(even) { return tile_on(t, tile, s0, s1, mid); } @@ -728,13 +734,14 @@ fn pattern_scale(pb: &PatternBrush, weight: f64, stroke: &StrokeLayer) -> (f64, /// tried in order (evenly spaced ones, and `breaks`, the lengths whose middle falls on a recorded /// pen sample), and the range between the last one the tile is too long for and the first one it /// fits is halved. A tile that fits at no length up to `room` gets the length it needs at `room`, -/// longer than `room`. -fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: &[f64]) -> f64 { +/// longer than `room`. `breaks` is `None` when the scale is the same along the whole track, and +/// the tile then takes its length at that scale. +fn end_tile_length(width: f64, room: f64, k_mid: &dyn Fn(f64) -> f64, breaks: Option<&[f64]>) -> f64 { let length = |w: f64| width * k_mid(w); let first = length(0.0); - if length(first) == first || room.is_nan() || room <= 0.0 { + let Some(breaks) = breaks.filter(|_| !room.is_nan() && room > 0.0) else { return first; - } + }; let mut tries: Vec = (1..=END_SCAN_STEPS).map(|i| room * i as f64 / END_SCAN_STEPS as f64).collect(); tries.extend(breaks.iter().copied().filter(|&w| w > 0.0 && w < room)); tries.sort_by(f64::total_cmp); @@ -1171,8 +1178,8 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &Str && let Some(st) = &start { // As long as the scale at its middle. - let breaks: Vec = marks.iter().flatten().map(|&m| 2.0 * (m - a)).collect(); - let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), &breaks); + let breaks: Option> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (m - a)).collect()); + let w = end_tile_length(st.1.width(), b - a, &|w| ks(a + w / 2.0), breaks.as_deref()); if b - a > w { out.take(tile_scaled(&t, st, a, a + w, &ks, marks.as_deref())); a += w; @@ -1182,8 +1189,8 @@ pub(crate) fn pattern(pb: &PatternBrush, bp: &BezPath, weight: f64, stroke: &Str && ri + 1 == nruns && let Some(en) = &end { - let breaks: Vec = marks.iter().flatten().map(|&m| 2.0 * (b - m)).collect(); - let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), &breaks); + let breaks: Option> = marks.as_ref().map(|m| m.iter().map(|&m| 2.0 * (b - m)).collect()); + let w = end_tile_length(en.1.width(), b - a, &|w| ks(b - w / 2.0), breaks.as_deref()); if b - a > w { out.take(tile_scaled(&t, en, b - w, b, &ks, marks.as_deref())); b -= w; From f0a5396e4140bf0a904bce16c19db27a1600be40 Mon Sep 17 00:00:00 2001 From: ViktorBystrov72 <18964918+ViktorBystrov72@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:16:11 +0500 Subject: [PATCH 17/28] Declare the PDF/X-4 identification namespace on the XMP description (#9134) --- crates/pdf/src/pdfx.rs | 8 ++++++-- crates/pdf/src/tests/pdfx.rs | 8 +++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index a8f85a2873..d1741227f9 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -89,11 +89,15 @@ pub(crate) fn xmp(pdf: &[u8], xref: &Xref, root: (usize, usize), patch: &mut Pat let xml = data.checked_add(length).and_then(|e| obj.get(data..e)).ok_or_else(bad)?; let mut edits: Vec<(usize, usize, Vec)> = vec![]; if let Some((version, _)) = pdfx_ids(standard).filter(|_| standard == Standard::PdfX4) { - // Into the writer's description, whose namespaces declare the `pdf` and `xmpMM` prefixes. + // The writer wraps its properties in one outer description. Declare `pdfxid` there with + // the other namespaces, so validators can find the version property without attributes. + let description = b"").ok_or_else(bad)?; + edits.push((open, open, br#" xmlns:pdfxid="http://www.npes.org/pdfx/ns/id/""#.to_vec())); let trapped = if trapped { "True" } else { "False" }; let props = format!( - "{version}{trapped}1" + "{version}{trapped}1" ); edits.push((close, close, props.into_bytes())); // When the packet has no `` element, this adds one after the writer's diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index f7cf8ff56a..0647f8855e 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -120,7 +120,13 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() { // The metadata agrees with the header; PDF/X-4 names its standard there too. let xmp_version = if standard == Standard::PdfX4 { "1.6" } else { "1.3" }; assert!(t.contains(&format!("{xmp_version}")), "{standard:?}"); - assert_eq!(t.contains("PDF/X-4<"), standard == Standard::PdfX4); + let xmp = xmp_packet(&r.bytes); + let (_, description) = xmp.rsplit_once("').expect("the end of the opening tag"); + let is_pdfx4 = standard == Standard::PdfX4; + // Validators expect the version property to inherit its namespace from the description. + assert_eq!(attributes.contains(r#"xmlns:pdfxid="http://www.npes.org/pdfx/ns/id/""#), is_pdfx4, "{standard:?}: {attributes}"); + assert_eq!(xmp_value(&xmp, "pdfxid:GTS_PDFXVersion"), is_pdfx4.then_some("PDF/X-4"), "{standard:?}"); assert_eq!(t.contains("False"), standard == Standard::PdfX4); assert!(!t.contains("/Encrypt"), "{standard:?}"); // The file reads back. From 49755faf39faa785f28cc7aa31288ce01da40f9b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 18:50:35 -0800 Subject: [PATCH 18/28] Color Wheel: retyping the hex field's text keeps the opacity it shows The field shows an opacity as two alpha digits, so 50% shows as 80. Committing that text unchanged applied 128/255 and recorded an undo step. Text that matches the field now applies the opacity the field shows, so a single object keeps it exactly and the other selected objects take it. Any other text, such as rgb(255 0 0 / 50.4%), still applies its own alpha. --- crates/ui-egui/src/panels/color_wheel.rs | 16 ++++++---- .../src/panels/tests_color_wheel_hex.rs | 29 +++++++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 675ca6ad89..f32641a7ac 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -1324,8 +1324,10 @@ fn hex_row(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, shown: &str) -> Opti /// Apply the hex field's committed `text`: it goes through `color.parse` as typed, and a text it /// refuses shows its error in the status bar and changes nothing. The text's alpha is not applied /// when `opacity_set` (the opacity row set the opacity in this frame), so a press on that row that -/// commits the text keeps the opacity it set. -fn apply_text(app: &mut VectorcraftApp, ui: &Ui, text: &str, opacity_set: bool) { +/// commits the text keeps the opacity it set. When the text is the one the field shows +/// (`retyped`), its alpha stands for the opacity the field shows, not the value its two digits +/// round to, so retyping it leaves that opacity as it was. +fn apply_text(app: &mut VectorcraftApp, ui: &Ui, text: &str, opacity_set: bool, retyped: bool) { match app.run("color.parse", json!({ "text": text })) { Ok(r) => { let Ok(rgb) = serde_json::from_value::(r["color"].clone()) else { return }; @@ -1334,6 +1336,7 @@ fn apply_text(app: &mut VectorcraftApp, ui: &Ui, text: &str, opacity_set: bool) 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).filter(|_| !opacity_set); + let alpha = alpha.map(|a| if retyped { shown_opacity(app, &tgt).0 } else { a }); apply_typed(app, &tgt, c, alpha); } Err(e) => app.status(e), @@ -1448,13 +1451,16 @@ fn show_with(app: &mut VectorcraftApp, panel: &mut WheelUi, ui: &mut Ui) { }; let typed = hex.and_then(|hex| { ui.add_space(4.0); - hex_row(app, ui, &tgt, &hex) + hex_row(app, ui, &tgt, &hex).map(|text| { + let shown = text.strip_prefix('#').unwrap_or(&text).eq_ignore_ascii_case(&hex); + (text, shown) + }) }); // A text committed by a press on the wheel, the box or the opacity row is applied first; the // opacity edit then goes to the target as the text left it, and a pick to the target as both // left it, so a stop keeps all of them. - if let Some(text) = &typed { - apply_text(app, ui, text, opacity_edit.is_some()); + if let Some((text, shown)) = &typed { + apply_text(app, ui, text, opacity_edit.is_some(), *shown); } let tgt = if typed.is_some() { wheel_target(app, ui) } else { tgt }; if let Some(edit) = &opacity_edit { diff --git a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs index e90c0d2953..735df1b0fd 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_hex.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_hex.rs @@ -272,6 +272,15 @@ fn retyping_the_shown_color_in_another_form_changes_nothing() { assert_eq!(undo_count(&p.app()), before, "{same}"); assert!(p.app().ui.status.is_empty(), "{same}: {}", p.app().ui.status); } + let text = shown(&p); + assert_eq!(text, "FF000080"); + type_in(&mut p, &text); + assert_eq!(undo_count(&p.app()), before, "the shown text"); + assert_eq!(p.app().session.proxy_opacity(false), Some(0.5), "the shown alpha keeps 50 %"); + type_in(&mut p, "rgb(255 0 0 / 50.4%)"); + assert_eq!(undo_count(&p.app()), before + 1, "an alpha with the same two digits is applied"); + assert!(p.app().session.proxy_opacity(false).is_some_and(|o| (o - 0.504).abs() < 1e-4)); + let before = undo_count(&p.app()); type_in(&mut p, "#00ff00"); assert_eq!(undo_count(&p.app()), before + 1, "another color is applied"); p.run("paint.setFill", json!({"opacity": 99.9})); @@ -282,6 +291,26 @@ fn retyping_the_shown_color_in_another_form_changes_nothing() { assert_eq!(p.app().session.proxy_opacity(false), Some(1.0)); } +/// Retyping the shown text with two objects selected gives the second the first one's opacity, the +/// one the field shows, and leaves the first's as it was. +#[test] +fn retyping_the_shown_alpha_gives_the_selection_the_shown_opacity() { + let mut app = app(); + let first = selected(&app)[0]; + app.run("paint.setFill", json!({"opacity": 50})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 50})).unwrap(); + let second = selected(&app)[0]; + app.run("paint.setFill", json!({"color": "#ff0000", "opacity": 80})).unwrap(); + app.run("select.set", json!({"ids": [first, second]})).unwrap(); + let mut p = panel(app); + let text = shown(&p); + assert_eq!(text, "FF000080"); + type_in(&mut p, &text); + let opacity = |id| p.app().session.doc().unwrap().doc.node(id).unwrap().appearance.fill_at(None).map(|f| f.opacity); + assert_eq!(opacity(first), Some(0.5), "the first keeps 50 %"); + assert_eq!(opacity(second), Some(0.5), "the second takes 50 %"); +} + /// Retyping a gradient stop's or a freeform point's color, with or without its alpha, records no /// step. #[test] From e45b922802e401d3cdd77dda2d00347aa4ee8cd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:58:24 -0800 Subject: [PATCH 19/28] Scripts: app.redraw returns without changing the documents A script that called app.redraw() stopped with an error, because app had no such member. The call now returns undefined and adds no undo step. A run works on its own copy of the documents, and the app draws the documents as they were before the run until the run ends, so the call has nothing new to draw. --- crates/engine/src/script/dom.rs | 8 ++++++++ crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- docs/mcp.md | 6 ++++-- docs/target-app-parity.md | 1 + 5 files changed, 32 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cb901014b5..37bf1c614a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -714,6 +714,13 @@ fn path_key(p: &str) -> String { if windows { p.to_lowercase() } else { p } } +/// `app.redraw()`: returns without changing anything. The app draws a frame between the run's +/// slices on its own, and it draws the documents as they were before the run until the run ends, +/// so there is nothing for the call to draw. It adds no undo step. +fn app_redraw(_: &Host, _: &[Data]) -> Answer { + Ok(Data::Undefined) +} + /// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is /// compared as text with the documents' files and is not resolved; a document whose file the /// automation read roots do not allow does not count, and that check can look the file up on disk. @@ -1948,6 +1955,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("redraw", method(l, app_redraw)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 60e3a71521..95cbcc526c 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -245,6 +245,24 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { assert_eq!(kept(&s), None); } +/// `app.redraw()` returns `undefined` and leaves the art and the undo history as they were. +#[test] +fn redraw_returns_and_changes_nothing() { + let (mut s, a, _) = doc(); + let (art, steps, opacity) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s), s.active().unwrap().doc.node(a).unwrap().opacity); + assert_eq!(log(&mut s, "vc.log(typeof app.redraw()); vc.log(app.redraw(1, 'x') === undefined);"), vec![json!("undefined"), json!(true)]); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); + assert_eq!(undo_steps(&s), steps); + // In a run in the app, edits before and after the calls still end as one undo step. + s.script_frames = true; + let source = "var i = app.activeDocument.pageItems[0]; i.opacity = 40; app.redraw(); i.opacity = 30; app.redraw();"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap()["running"], true); + let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap_or_else(|| panic!("the run did not end")); + ended.unwrap(); + assert!(s.active().unwrap().doc.node(a).unwrap().opacity < opacity); + assert_eq!(undo_steps(&s), steps + 1); +} + /// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. #[test] fn assigning_the_reported_opacity_changes_nothing() { diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index d9b6b87103..051b755cf9 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -81,7 +81,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + redraw selection typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..70c22283ff 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,7 +2622,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)` and `app.redraw()`. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -2692,7 +2692,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with - `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, + `..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined` + and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the + run until the run ends, with or without the call. Some members the Application, Document and PageItem pages list, such as `Document.layers`, `PageItem.blendingMode`, `PageItem.rotate` and `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..2ffff38673 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 25ee85d03d55671d2742228b67c5e4bf42bce733 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:51:25 -0800 Subject: [PATCH 20/28] Scripts: the app.redraw test checks the top item's opacity after the second edit --- crates/engine/src/tests/script_dom.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0a3fa2ea6d..a265b9b001 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -263,8 +263,8 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { /// `app.redraw()` returns `undefined` and leaves the art and the undo history as they were. #[test] fn redraw_returns_and_changes_nothing() { - let (mut s, a, _) = doc(); - let (art, steps, opacity) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s), s.active().unwrap().doc.node(a).unwrap().opacity); + let (mut s, _, top) = doc(); + let (art, steps) = (format!("{:?}", s.active().unwrap().doc.layers), undo_steps(&s)); assert_eq!(log(&mut s, "vc.log(typeof app.redraw()); vc.log(app.redraw(1, 'x') === undefined);"), vec![json!("undefined"), json!(true)]); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), art); assert_eq!(undo_steps(&s), steps); @@ -274,7 +274,8 @@ fn redraw_returns_and_changes_nothing() { assert_eq!(s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap()["running"], true); let ended = (0..10_000).find_map(|_| s.script_pump()).unwrap_or_else(|| panic!("the run did not end")); ended.unwrap(); - assert!(s.active().unwrap().doc.node(a).unwrap().opacity < opacity); + // The edit after the first call landed too: the opacity is below the 40% set before it. + assert!(s.active().unwrap().doc.node(top).unwrap().opacity < 0.4); assert_eq!(undo_steps(&s), steps + 1); } From 893f2d7520eee205657f86d45dbe49dcbaebb1a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:17:12 -0800 Subject: [PATCH 21/28] Docs: a left-out pattern brush scale_mode keeps the current mode on edits brush.new without a scale_mode makes a Fixed brush. brush.options without one keeps the brush's mode, and brush.objectOptions without one keeps each path's mode; null sets Fixed in all three. --- docs/mcp.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 0fa9a68ba2..7136e9c36d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4284,8 +4284,10 @@ already walks Image Trace. Short agent entry points: it does not read it on Windows or in the web build. `.ai` brush definitions read and write the wheel as variation code 3. - Pattern brush scale from the pen: a pattern brush's `scale_mode` (`brush.new`, `brush.options`, - `brush.objectOptions`; left out or `null` for Fixed) takes `pressure`, `tilt`, `bearing`, `rotation` and - `stylusWheel`, and `scale_max` (1..10000%) is the second scale. The tiles go from `scale` where the pen reads 0 to + `brush.objectOptions`; `null` for Fixed) takes `pressure`, `tilt`, `bearing`, `rotation` and + `stylusWheel`, and `scale_max` (1..10000%) is the second scale. `brush.new` without a `scale_mode` makes a + Fixed brush; `brush.options` without one keeps the brush's mode, and `brush.objectOptions` without one keeps + each path's mode. The tiles go from `scale` where the pen reads 0 to `scale_max` where it reads 1, over the ranges an Art brush's `width_mode` uses, and half way on a stroke drawn without that input; without a `scale_max` both ends are `scale`. Each side, start and end tile is as tall as the scale at each point of the stroke, and the tile and the gap after it are as long as the scale at the tile's From 1f231d14da7096ecb20fc076c05323a07c8050fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 18:45:22 -0800 Subject: [PATCH 22/28] Tests: Brush Options access names come from the dialogs' shared app frame access_names settles the dialog and reads the accessibility update from crate::dialogs::tests::frame, as the Art Brush Direction test does, instead of running its own frame. --- .../ui-egui/src/dialogs/brush_options/tests.rs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 9662550797..d8b88e9595 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -278,16 +278,13 @@ fn ok_redraws_the_strokes_painted_with_the_brush() { assert!((drawn_height(&app, id) - before).abs() < 1e-6); } -/// The names screen readers read in the open dialogs, from one 1200 × 900 frame's access tree. +/// The names screen readers read in the open dialogs, from the access tree of an app frame drawn +/// once the dialog has settled. fn access_names(app: &mut VectorcraftApp) -> Vec { - use egui::{Pos2, Rect}; - let ctx = ctx(app); - let dialogs = app.dialogs().expect("a window"); - let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1200.0, 900.0))), ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| dialogs.with(|host| host.run(ui))); - out.textures_delta.clear(); - let update = out.platform_output.accesskit_update.expect("an accessibility tree"); - update.nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_string).collect() + crate::dialogs::tests::settle(app); + let out = crate::dialogs::tests::frame(app, vec![]); + let nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + nodes.iter().filter_map(|(_, node)| node.label()).map(str::to_string).collect() } /// Pattern Brush Options' Scale menu: Pressure, Tilt, Bearing, Rotation and Stylus Wheel each take @@ -301,7 +298,6 @@ fn pattern_options_scale_follows_the_pen() { let f = fields_of(&app); assert_eq!((f.text("scaleMode"), f.number("scaleMax")), (Some("fixed"), Some(100.0))); // Screen readers name the second scale and the menu after the Scale row. - access_names(&mut app); let names = access_names(&mut app); for name in ["Scale: Maximum", "Scale: Mode"] { assert!(names.iter().any(|n| n == name), "{name} in {names:?}"); @@ -340,7 +336,6 @@ fn pattern_options_scale_follows_the_pen() { fn art_options_name_the_second_width_and_its_menu() { let mut app = app(); open(&mut app, "Tapered Stroke"); - access_names(&mut app); let names = access_names(&mut app); for name in ["Width: Maximum", "Width: Mode"] { assert!(names.iter().any(|n| n == name), "{name} in {names:?}"); From 335a033f306f19f15026be0e3249d0278f5b6640 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:11:24 -0800 Subject: [PATCH 23/28] Paintbrush: a Pattern brush with Scale on Stylus Wheel reads the wheel On Windows the Paintbrush opens the Wintab context only while its brush varies with the wheel. The check counted Calligraphic, Scatter and Art brushes and left out Pattern brushes, so a Pattern brush whose Scale is on Stylus Wheel recorded no wheel there. A Pattern brush now counts when its scale is on Stylus Wheel and its two scales differ. --- crates/tools/src/symbolism.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 9d6fe2e887..828aff4e01 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -440,7 +440,8 @@ impl Tool for BrushPaintTool { } /// The brush it paints with varies with the wheel: a Calligraphic brush with a value on Stylus /// Wheel and a variation other than 0, a Scatter brush with a value on it whose two values - /// differ, or an Art brush whose width is on it with two different widths. + /// differ, an Art brush whose width is on it with two different widths, or a Pattern brush + /// whose scale is on it with two different scales. fn reads_wheel(&self, cx: &ToolContext) -> bool { use vectorcraft_brush::{BrushKind, Variation}; let wheel = |mode: Variation| mode == Variation::StylusWheel; @@ -449,7 +450,8 @@ impl Tool for BrushPaintTool { BrushKind::Calligraphic(c) => c.modes().into_iter().zip(c.variation).any(|(m, v)| wheel(m) && v != 0.0), BrushKind::Scatter(s) => s.modes().into_iter().zip(s.values()).any(|(m, (a, b))| wheel(m) && a != b), BrushKind::Art(a) => a.width_mode.is_some_and(wheel) && a.width_range().0 != a.width_range().1, - BrushKind::Pattern(_) | BrushKind::Bristle(_) => false, + BrushKind::Pattern(p) => p.scale_mode.is_some_and(wheel) && p.scale_range().0 != p.scale_range().1, + BrushKind::Bristle(_) => false, } } fn busy(&self) -> bool { @@ -775,7 +777,7 @@ mod tests { #[test] fn the_paintbrush_reads_the_wheel_only_with_a_stylus_wheel_brush() { - use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, Scatter, Variation}; + use vectorcraft_brush::{ArtBrush, Brush, BrushKind, Calligraphic, PatternBrush, Scatter, Variation}; let wheel = Variation::StylusWheel; let calligraphic = |modes, size| BrushKind::Calligraphic(Calligraphic { variation: [0.0, 0.0, size], modes: Some(modes), ..Calligraphic::default() }); @@ -783,6 +785,7 @@ mod tests { BrushKind::Scatter(Scatter { size, modes: Some([wheel, Variation::Fixed, Variation::Fixed, Variation::Fixed]), ..Scatter::default() }) }; let art = |width_mode, width_max| BrushKind::Art(ArtBrush { width_mode, width_max: Some(width_max), ..ArtBrush::default() }); + let pattern = |scale_mode, scale_max| BrushKind::Pattern(PatternBrush { scale_mode, scale_max: Some(scale_max), ..PatternBrush::default() }); let library = [ Brush { name: "Plain".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, Variation::Pressure], 2.0) }, Brush { name: "Nib".into(), kind: calligraphic([Variation::Fixed, Variation::Fixed, wheel], 2.0) }, @@ -792,6 +795,9 @@ mod tests { Brush { name: "Taper".into(), kind: art(Some(wheel), 200.0) }, Brush { name: "Even taper".into(), kind: art(Some(wheel), 100.0) }, Brush { name: "Flat".into(), kind: art(None, 200.0) }, + Brush { name: "Tiles".into(), kind: pattern(Some(wheel), 200.0) }, + Brush { name: "Even tiles".into(), kind: pattern(Some(wheel), 100.0) }, + Brush { name: "Fixed tiles".into(), kind: pattern(None, 200.0) }, ]; let (mut d, _) = doc_with_rect(); d.unknown.insert(vectorcraft_brush::DOC_KEY.into(), serde_json::to_value(library).unwrap()); @@ -808,6 +814,9 @@ mod tests { ("Taper", true), ("Even taper", false), ("Flat", false), + ("Tiles", true), + ("Even tiles", false), + ("Fixed tiles", false), ("Deleted", false), ]; for (name, varies) in brushes { From 40eaf74680e5faa8e8008aad29d319e53cd97b26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:07:56 -0800 Subject: [PATCH 24/28] Brushes: a canceled Pattern brush scale change does not reach the brush The Scale and Width row that art and pattern brushes share read the slider's in-progress value, so a held drag ended with Escape left the dragged value in the dialog and rounded a fractional stored value. Main reads brush option sliders, fields and menus through landed() and committed() so a canceled or unfinished edit does not reach the brush (#9752); the row now does the same and keeps the exact opening value. The new test drags Pattern Brush Options' Scale slider, cancels with Escape while the dialog stays open and checks the field still holds the opening 100.25 %, then checks a released drag is kept by OK. The Art brush width test now finds the mode menu by its name, Width: Mode. --- .../ui-egui/src/dialogs/brush_art_options.rs | 5 +- .../src/dialogs/brush_options/tests.rs | 52 ++++++++++++++++++- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 3c5d83efb1..389db7ad66 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -334,8 +334,9 @@ fn pen_size_row(size: PenSize) -> Param { Row::new() .show(ui, |ui, _| { let slid = Slider::new(Bind::given(clamped(f, key, range)), range.0..=range.1).step(1.0).label(label).id_salt(key).show(ui); - if let Some(value) = slid.value() { - f.set(key, value.round()); + if let Some(value) = slid.events.landed() { + // The slider quantizes new edits; Cancel restores the exact opening value. + f.set(key, *value); } number_cell(ui, f, max_key, max_label, range, UnitKind::Percent, mode.follows_pen()); id_select(ui, f, mode_key, mode_label, &entries, mode.id().to_string()); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index fbb487d8ba..4fb284b6e0 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -186,7 +186,7 @@ fn canceled_art_width_drag_restores_the_opening_width() { let initial = fields_of(&panel.app()).number("width").unwrap(); assert_eq!(initial, 100.25, "Cancel must preserve a valid fractional stored width"); let mode = fields_of(&panel.app()).text("widthMode").map(str::to_owned); - panel.click_role("Width", Role::COMBO_BOX); + panel.click_role("Width: Mode", Role::COMBO_BOX); panel.key(Key::ArrowDown, Modifiers::NONE); panel.key(Key::Escape, Modifiers::NONE); assert_eq!(fields_of(&panel.app()).text("widthMode").map(str::to_owned), mode); @@ -214,6 +214,56 @@ fn canceled_art_width_drag_restores_the_opening_width() { assert_eq!(panel.app().run("brush.get", json!({"name": "Arrow"})).unwrap(), original); } +/// Pattern Brush Options' Scale row: a held drag ended with Escape and a mode menu closed with +/// Escape leave the open dialog's fields as they opened, and Cancel leaves the brush as it was; a +/// released drag is kept by OK. +#[test] +fn canceled_pattern_scale_edits_do_not_reach_the_brush() { + use crate::tests::panel_harness::Panel; + use craft::ui::contract::Role; + use egui::{Key, Modifiers}; + + let mut app = app(); + app.run("brush.options", json!({"name": "Diamonds", "params": {"scale": 100.25}})).unwrap(); + let original = app.run("brush.get", json!({"name": "Diamonds"})).unwrap(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut panel = Panel::new(app, draw_hosted_options); + panel.room(egui::vec2(1000.0, 1000.0)); + open(&mut panel.app(), "Diamonds"); + panel.frame(); + let initial = fields_of(&panel.app()).number("scale").unwrap(); + assert_eq!(initial, 100.25, "Cancel must preserve a valid fractional stored scale"); + let mode = fields_of(&panel.app()).text("scaleMode").map(str::to_owned); + panel.click_role("Scale: Mode", Role::COMBO_BOX); + panel.key(Key::ArrowDown, Modifiers::NONE); + panel.key(Key::Escape, Modifiers::NONE); + assert!(is_open(&panel.app())); + assert_eq!(fields_of(&panel.app()).text("scaleMode").map(str::to_owned), mode); + panel.drag_hold_role("Scale", Role::SLIDER, egui::vec2(40.0, 0.0)); + assert_ne!(fields_of(&panel.app()).number("scale"), Some(initial), "the held drag previews another scale"); + panel.key(Key::Escape, Modifiers::NONE); + panel.release(); + assert!(is_open(&panel.app())); + assert_eq!(fields_of(&panel.app()).number("scale"), Some(initial), "the canceled drag restores the opening scale"); + panel.click("Cancel"); + panel.frame(); + assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo); + + open(&mut panel.app(), "Diamonds"); + panel.frame(); + panel.drag_hold_role("Scale", Role::SLIDER, egui::vec2(40.0, 0.0)); + panel.release(); + let accepted = fields_of(&panel.app()).number("scale").unwrap(); + assert_ne!(accepted, initial); + panel.click("OK"); + panel.frame(); + assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap()["scale"], accepted); + assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1); + panel.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(panel.app().run("brush.get", json!({"name": "Diamonds"})).unwrap(), original); +} + /// What a step of the table expects at a JSON pointer of the saved brush. enum Expect { Is(Value), From 9e408b8227b71571cbb36b4c8d13e85124beb425 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 06:03:06 -0800 Subject: [PATCH 25/28] Docs: drop Art, Pattern and Bristle from the pending pen-input lists Art, Pattern and Bristle brushes already follow pen tilt, bearing and rotation, so the Strokes, brushes rows and the Brushes entry list only native Wayland and the web as remaining for those inputs. --- docs/target-app-parity.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f53da1af47..86a9cea796 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -339,7 +339,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005); the Color Wheel panel's Show Opacity sets the opacity of the fill, stroke, gradient stop or freeform point it edits (part of #978), score and hours unchanged; gradient stop editor color-mode menu (#7918) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Appearance panel row context menus (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with unselected-row targeting, Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -611,7 +611,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fifteen generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fifteen generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -2193,7 +2193,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Gradient tool's freeform Lines mode, moving the pointer out of the object and back ends the line being drawn, and the next click on the object starts a new line from the point it adds. The help page describes this way of starting another line segment in the same object ([Create freeform gradient in lines mode](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=262)). As VectorCraft's own rules, the line ends as soon as the pointer, with no button held, moves off the object's own art, its fill, stroke or glyphs (other art lying over the object still counts as inside), and Escape and a click off the art still end it as before (`xform::freeform::tests::leaving_the_object_ends_the_line`). - **Freeform gradient colors in their own model:** Object ▸ Expand and Object ▸ Create Gradient Mesh (`object.mesh.create`) mix a freeform gradient's points in the color model they share: points of C50 M20 Y0 K10 give mesh points of C50 M20 Y0 K10, and RGB points keep their values in a working RGB space other than sRGB. The canvas, the gradient chips and the SVG, PDF, EPS and EMF writers mix the points in that model too. PDF and EPS write a gradient whose points are all CMYK, or all Gray in a CMYK file, as a CMYK image, which PDF's Output settings convert as they convert any CMYK image. Points in different models mix in display RGB (on the canvas in a CMYK document that shows transparency, as the inks of each point), and a CMYK document stores the result of Expand as CMYK through the color settings. Points colored along CMYK stops (`paint.editGradient {stops}`, or a CMYK gradient switched to freeform) are CMYK, and so are a point `paint.freeform.splitLine` adds between CMYK points and a point `paint.freeform.addPoint` adds without `color` to CMYK points. Public reference: [Gradients](https://web.archive.org/web/20250714042311/https://helpx.adobe.com/illustrator/using/gradients.html) and [Meshes](https://web.archive.org/web/20250812201019/https://helpx.adobe.com/illustrator/using/meshes.html), which do not state how colors in different models mix; the rule is VectorCraft's own. - **Strokes:** one stroke-geometry module shared by the canvas, SVG, PDF and Outline Stroke; dotted lines (zero-length dashes draw dots or squares); arrowheads with hollow outlines, tip-on-end or extend-past-end alignment and one opacity for line and head. SVG and PDF export arrowheads, width profiles, brushes and aligned strokes exactly as the canvas draws them; Outline Stroke and the live Outline Stroke effect outline every stroke item as drawn (dashes, heads, profiles, alignment); dashes can be fitted to corners and path ends; width profiles carry through dashes, and their corners take the join. The Stroke panel edits type's character strokes, follows the stroke units (its weight presets are round values in that unit: `0.25 mm`, `0.0625 in`, `1 px`, #426; fields show four decimals in mm, cm and inches, three in points), shows mixed values blank and opens from the Control bar. A width profile library, thirty-one more arrowheads (among them Line Arrow: two arms of the head's weight (stroke weight × arrowhead scale, at least 0.25 pt: the line's weight at 100 % for lines of 0.25 pt or more) at right angles, cut square, #5421), and Width Point Edit with multi-select and discontinuous points. Visual bounds and clicks cover the whole painted stroke. Scale Strokes & Effects, Scale Corners and Use Preview Bounds work everywhere, and new art inherits stroke options, a graphic style or the whole last appearance. A width profile's sides run as a smooth C1 curve between the width points (a monotone cubic Hermite, Fritsch–Carlson, with each end's own span slope and flat either side of a step), sampled adaptively along the path (two samples per profile segment, refined until the line between samples stays within the outline tolerance, and reusing a segment's own flattened points only where they already follow the curve) so straight runs draw it too; added samples offset along the source curve's exact tangent, not the flattened chord, so high zoom follows the true width; the sampled edges are fitted with G1 cubics within the flattening tolerance (0.01 pt) rather than one cubic per flatten step, so a profiled outline draws the same shape as a uniform one and exports stay close to its path data; a point reshapes the curve as far as its neighbours' neighbours (their slopes depend on it), and coincident points still step. - - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: a check of pen pressure on a Mac with a tablet, and tilt, bearing and rotation for Bristle brushes and on native Wayland and the web. + - **Brushes (part of #852):** double-clicking a brush in the Brushes panel (or the panel menu's Brush Options…) opens Calligraphic Brush Options (Name; Angle, Roundness and Size, each Fixed, Random, Pressure, Tilt, Bearing or Rotation with its Variation; live previews of the nib and of a light–heavy–light stroke) or Bristle Brush Options (Shape and the bristle sliders); OK edits the brush and every stroke painted with it. The Paintbrush records the pen pressure along each stroke (kept with the path, saved, and joined when a stroke continues a path); a Calligraphic value on Pressure goes from value − variation at the lightest pressure to value + variation at the heaviest, on the canvas and in SVG, PDF and the other exports. Brushes saved before keep their look. Scatter Brush Options (Size, Spacing, Scatter and Rotation, each Fixed, Random between two values, Pressure from the first at the lightest pressure to the second at the heaviest, Tilt, Bearing or Rotation; Rotation relative to Page or Path), Art Brush Options (Width, Scale Proportionately, Stretch to Fit Stroke Length or Stretch Between Guides with the guides' start and end, the four Directions, Flip Along and Across, Overlap) and Pattern Brush Options (Scale, Spacing, the five tiles shown, Flip Along and Across, Stretch to fit, Add space to fit or Approximate path) each have Colorization (None, Tints, Tints and Shades, Hue Shift with its Key Color picked from the art's colours) and a live stroke preview; values from files and commands are clamped to their ranges. Art Brush Options › Overlap places art on each run between sharp corners so folds do not overlap (`ArtBrush.overlap`; `art_brush_overlap_splits_at_corners`). Still to come: a check of pen pressure on a Mac with a tablet, and tilt, bearing and rotation on native Wayland and the web. Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). From 75d328e005c2109e89270471b9d86513592b47c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:05:34 -0800 Subject: [PATCH 26/28] Home: margin and gaps follow the framework's spacing tokens The app's size sets gave Home's page margin and its title, action, section, heading and link gaps fixed point values (60, 9, 27, 14, 33, 15, 5). They are dropped, so Home uses the framework's page tokens, which follow its spacing scale (space.gap.*), and the gaps between Home's sections, headings and cards share one rhythm. --- crates/ui-egui/src/theme.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 016e665e88..1aa688ceb9 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -146,10 +146,10 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option) { } /// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners -/// where the sets give pills, the Home title is 26-point under 60 points of page margin with a 36-point call to -/// action, Home keeps production's rhythm (its item spacing of 5 plus the room it added: 9 from title to subtitle, 27 -/// to New and Open, 28-point New and Open with 16 points beside their labels and 14 between them, 33 between sections, -/// 15 under a heading, 24-point link rows 5 apart), and the compact set takes the reference app's metrics: +/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16 +/// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections, +/// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set +/// takes the reference app's metrics: /// 26-point fields and spinners, 24-point push buttons, 10 points inside panels, 5 between rows, 16-point glyphs in /// icon buttons, 5-point control corners, 8-point menus and 10-point windows, 33-point panel tabs, 310-point dock /// columns with 14-point column bars and 38-point icon columns, 29-point menu rows, and dialogs 22 points inside their @@ -161,16 +161,9 @@ const SIZES: &[u8] = br#"{ "radius.button": 4, "typography.display.size": 26, "typography.display.line_height": 32, - "size.page.margin": 60, "size.page.action": 36, "size.page.button": 28, "size.page.button_side": 16, - "size.page.gap.title": 9, - "size.page.gap.lead": 27, - "size.page.gap.actions": 14, - "size.page.gap.section": 33, - "size.page.gap.heading": 15, - "size.page.gap.link": 5, "size.page.link": 24 }, "compact": { @@ -235,4 +228,17 @@ mod tests { fn the_app_sizes_are_read_whole() { assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty())); } + + /// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow + /// the framework's spacing scale. + #[test] + fn home_spacing_follows_the_framework_tokens() { + let sets: serde_json::Map = serde_json::from_slice(SIZES).unwrap(); + for (set, sizes) in &sets { + let keys = sizes.as_object().map(|o| o.keys().collect::>()).unwrap_or_default(); + for key in keys { + assert!(!key.starts_with("size.page.gap.") && key != "size.page.margin", "{set} sets {key}"); + } + } + } } From b464b1ecad9d0ddd6a2b8d935ba360e7982d6b74 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:08:13 -0800 Subject: [PATCH 27/28] PDF: check that the PDF/X-4 XMP packet stays well-formed The PDF/X test now asserts that the outer description declares the pdfxid namespace exactly once, and that the edited packet parses with the strict XML parser that File Info uses to read it back. --- crates/pdf/src/tests/pdfx.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/pdf/src/tests/pdfx.rs b/crates/pdf/src/tests/pdfx.rs index 6f9bce01f1..f9d6e90b5a 100644 --- a/crates/pdf/src/tests/pdfx.rs +++ b/crates/pdf/src/tests/pdfx.rs @@ -127,6 +127,9 @@ fn each_standard_writes_its_header_output_intent_boxes_and_identification() { // Validators expect the version property to inherit its namespace from the description. assert_eq!(attributes.contains(r#"xmlns:pdfxid="http://www.npes.org/pdfx/ns/id/""#), is_pdfx4, "{standard:?}: {attributes}"); assert_eq!(xmp_value(&xmp, "pdfxid:GTS_PDFXVersion"), is_pdfx4.then_some("PDF/X-4"), "{standard:?}"); + // The edited packet is still well-formed XML: the namespace is declared once. + assert_eq!(attributes.matches("xmlns:pdfxid=").count(), usize::from(is_pdfx4), "{standard:?}: {attributes}"); + assert!(craft_xml::Options::default().strict().parse(xmp.as_bytes()).is_ok(), "{standard:?}: {xmp}"); assert_eq!(t.contains("False"), standard == Standard::PdfX4); assert!(!t.contains("/Encrypt"), "{standard:?}"); // The file reads back. From 921dffdec037e810e5a2fe32562b9ba4fde9f651 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 08:25:06 -0800 Subject: [PATCH 28/28] File dialogs: drop the unread Waiting::owner field #9555 merged with a merge of main that brought back the `owner` field on `Waiting`. Main had removed it once the document check moved to the captured UID and Revert counter. Nothing reads it, so clippy's `-D warnings` failed main's gate with "field `owner` is never read" at crates/ui-egui/src/file_asks.rs:42. The fix commit on #9555's branch (8ed117a988) did not reach main before the merge. --- crates/ui-egui/src/file_asks.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_asks.rs b/crates/ui-egui/src/file_asks.rs index 61b8bd48be..f1e90aea30 100644 --- a/crates/ui-egui/src/file_asks.rs +++ b/crates/ui-egui/src/file_asks.rs @@ -39,7 +39,6 @@ pub(crate) enum Owner { /// A pick asked for and not yet answered. struct Waiting { ticket: PickId, - owner: Owner, /// The file service is writing bytes that the caller already prepared. saving: bool, /// The active drawing's UID and Revert counter when asked, if the request is document-owned. @@ -168,7 +167,7 @@ fn start( Owner::Free => None, }; let (scope, automated) = (ScopeHandle::capture(), app.automation_asked()); - app.file_asks.waiting.push(Waiting { ticket, owner, saving, doc, scope, automated, current, then: Box::new(then) }); + app.file_asks.waiting.push(Waiting { ticket, saving, doc, scope, automated, current, then: Box::new(then) }); json!({ "pending": "fileDialog" }) }